scigantic-ucsc 0.1.0__tar.gz

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.
@@ -0,0 +1,16 @@
1
+ MIT No Attribution
2
+
3
+ Copyright 2026 Scigantic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this
6
+ software and associated documentation files (the "Software"), to deal in the Software
7
+ without restriction, including without limitation the rights to use, copy, modify,
8
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
9
+ permit persons to whom the Software is furnished to do so.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
12
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
13
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
14
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
15
+ CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
16
+ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: scigantic-ucsc
3
+ Version: 0.1.0
4
+ Summary: Read UCSC Genome Browser conservation scores, multiz alignments and mammal assembly lists straight from UCSC's public S3 bucket, without downloading the files.
5
+ Author: Scigantic
6
+ License: MIT-0
7
+ Project-URL: Homepage, https://scigantic.com
8
+ Project-URL: Repository, https://github.com/Scigantic/scigantic-ucsc
9
+ Project-URL: Issues, https://github.com/Scigantic/scigantic-ucsc/issues
10
+ Keywords: ucsc,genome-browser,comparative-genomics,phylop,multiz,bigwig
11
+ Classifier: License :: OSI Approved :: MIT No Attribution License (MIT-0)
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Typing :: Typed
17
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: numpy>=1.24
22
+ Requires-Dist: pyBigWig>=0.3.22
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7; extra == "dev"
25
+ Requires-Dist: mypy>=1.10; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # scigantic-ucsc
29
+
30
+ Python readers for four kinds of data in UCSC's public S3 bucket (`s3://genome-browser`, us-east-1, anonymous access): per-base conservation scores, hg38 multiz alignment blocks, TOGA gene annotations, and the assembly lists of UCSC's genome hubs. Each function reads only the byte ranges it needs over HTTPS, so no file is downloaded in full.
31
+
32
+ ```python
33
+ import scigantic_ucsc as ucsc
34
+
35
+ # phyloP scores, hg38, 0-based half-open coordinates
36
+ scores = ucsc.conservation("chr17", 43_044_295, 43_044_395, track="phyloP447way")
37
+
38
+ # mean score in 50 equal windows
39
+ bins = ucsc.conservation_bins("chr17", 43_044_295, 43_054_295, bins=50)
40
+
41
+ # multiz alignment blocks overlapping a region
42
+ blocks = ucsc.multiz_blocks("chr1", 1_000_000, 1_000_300, species=["mm10", "canFam3"])
43
+
44
+ # the same region as one string per species, one column per hg38 base
45
+ aln = ucsc.multiz_alignment("chr1", 1_000_000, 1_000_100, species=["mm10", "canFam3"])
46
+
47
+ # assemblies listed in the mammals hub
48
+ ucsc.find("marmoset")
49
+
50
+ # TOGA genes classified "Lost" in a region of a query assembly
51
+ genes = ucsc.toga_genes("GCF_001458135.1", "CZRN01000001", 0, 5_000_000, status="Lost")
52
+ ```
53
+
54
+ ## Installation
55
+
56
+ ```console
57
+ $ pip install scigantic-ucsc
58
+ ```
59
+
60
+ Requires Python 3.10 or later, numpy and pyBigWig.
61
+
62
+ ## Functions and sources
63
+
64
+ | Function | Reads | Method |
65
+ |---|---|---|
66
+ | `conservation`, `conservation_bins` | bigWig files under `goldenPath/hg38/` | pyBigWig remote range reads |
67
+ | `multiz_blocks`, `multiz_alignment` | `gbdb/hg38/multiz100way/defaultMaf/<chrom>.maf` | binary search by position over HTTP byte ranges; the files have no index |
68
+ | `assemblies`, `find` | `hubs/<group>/assemblyList.json` | one JSON file per group, cached in memory |
69
+ | `toga_genes`, `toga_chromosomes` | the `*TOGA*.bb` bigBed in `hubs/<GCF or GCA>/.../<accession>/bbi/` | pyBigWig remote range reads; the file is found by listing the assembly's `bbi/` prefix |
70
+
71
+ Conservation tracks: `phyloP100way`, `phastCons100way`, `phyloP447way` (default), `phyloP447wayPrimates`, `phyloP447wayLRT`. All are hg38.
72
+
73
+ `toga_genes` returns the reference transcript, the region on the query assembly, UCSC's gene classification (`status`) and the chain and intactness scores stored in the file. It omits the four columns that hold HTML and SVG for the browser popup.
74
+
75
+ ## Measurements
76
+
77
+ Taken on 2026-10-13 from a single machine, one request at a time.
78
+
79
+ - Conservation: opening a bigWig took about 1 s the first time. A 20-base query took 0.13 s, and a mean over 10 kb took 0.54 s.
80
+ - Multiz on chr1 (a 4.9 GB file): locating a position took 16 requests and 4.2 s.
81
+ - TOGA on one marmoset assembly: 239 genes from a 5 Mb region took 1.4 s.
82
+ - Multiz search correctness: the position search was compared with a full parse of `chrY.maf` (558,379 blocks). Over 300 random windows the two returned identical block lists.
83
+ - The mammals hub listed 1,006 assemblies on 2026-10-13.
84
+
85
+ ## Limits
86
+
87
+ - The multiz files that can be read this way contain nine species: hg38, rheMac3, canFam3, loxAfr3, galGal4, mm10, xenTro7, danRer10 and petMar2 (the species the UCSC browser shows by default). The full 100-way MAFs under `goldenPath/hg38/multiz100way/maf/` are plain gzip, which cannot be read from the middle, so this package does not use them.
88
+ - The Cactus 241-way and 447-way alignments are HAL files of about 0.8 and 1.2 TB on UCSC's own server, not in this bucket. This package does not read them. Only their conservation scores are read, from the bigWig files UCSC publishes.
89
+ - Conservation and multiz cover hg38 only.
90
+ - TOGA annotations exist for a minority of assemblies. In a random sample of 20 mammal and 20 bird assemblies, 2 of each had one. `toga_genes` raises `ValueError` if an assembly has none. Coordinates are on the query assembly and use its own sequence names, listed by `toga_chromosomes(accession)`.
91
+ - TOGA reads over 2 Mb windows were slow on some assemblies: the 20-assembly mammal sample took 382 s in total, against 8 s for the bird sample. The cause has not been identified.
92
+ - `multiz_alignment` projects onto hg38. Insertions relative to hg38 are dropped, a species with a gap gets `-`, and a base that no block covers is `.` in every row.
93
+ - `multiz_blocks` raises if a window needs more than `max_bytes` (64 MB by default) of a file.
94
+ - Chromosome names `1`, `chr1`, `CHR1` and `MT` are normalized to UCSC's spelling. A name that is not in hg38, a negative start, or a window past the end of the chromosome raises `ValueError`.
95
+ - The tests that read the live bucket are skipped unless `SCIGANTIC_UCSC_LIVE=1` is set, so CI does not depend on UCSC or AWS.
96
+
97
+ ## Data and citation
98
+
99
+ The data is produced by UCSC and by the groups behind each track. The track description pages on genome.ucsc.edu give the citation for each. This package is not affiliated with UCSC.
@@ -0,0 +1,72 @@
1
+ # scigantic-ucsc
2
+
3
+ Python readers for four kinds of data in UCSC's public S3 bucket (`s3://genome-browser`, us-east-1, anonymous access): per-base conservation scores, hg38 multiz alignment blocks, TOGA gene annotations, and the assembly lists of UCSC's genome hubs. Each function reads only the byte ranges it needs over HTTPS, so no file is downloaded in full.
4
+
5
+ ```python
6
+ import scigantic_ucsc as ucsc
7
+
8
+ # phyloP scores, hg38, 0-based half-open coordinates
9
+ scores = ucsc.conservation("chr17", 43_044_295, 43_044_395, track="phyloP447way")
10
+
11
+ # mean score in 50 equal windows
12
+ bins = ucsc.conservation_bins("chr17", 43_044_295, 43_054_295, bins=50)
13
+
14
+ # multiz alignment blocks overlapping a region
15
+ blocks = ucsc.multiz_blocks("chr1", 1_000_000, 1_000_300, species=["mm10", "canFam3"])
16
+
17
+ # the same region as one string per species, one column per hg38 base
18
+ aln = ucsc.multiz_alignment("chr1", 1_000_000, 1_000_100, species=["mm10", "canFam3"])
19
+
20
+ # assemblies listed in the mammals hub
21
+ ucsc.find("marmoset")
22
+
23
+ # TOGA genes classified "Lost" in a region of a query assembly
24
+ genes = ucsc.toga_genes("GCF_001458135.1", "CZRN01000001", 0, 5_000_000, status="Lost")
25
+ ```
26
+
27
+ ## Installation
28
+
29
+ ```console
30
+ $ pip install scigantic-ucsc
31
+ ```
32
+
33
+ Requires Python 3.10 or later, numpy and pyBigWig.
34
+
35
+ ## Functions and sources
36
+
37
+ | Function | Reads | Method |
38
+ |---|---|---|
39
+ | `conservation`, `conservation_bins` | bigWig files under `goldenPath/hg38/` | pyBigWig remote range reads |
40
+ | `multiz_blocks`, `multiz_alignment` | `gbdb/hg38/multiz100way/defaultMaf/<chrom>.maf` | binary search by position over HTTP byte ranges; the files have no index |
41
+ | `assemblies`, `find` | `hubs/<group>/assemblyList.json` | one JSON file per group, cached in memory |
42
+ | `toga_genes`, `toga_chromosomes` | the `*TOGA*.bb` bigBed in `hubs/<GCF or GCA>/.../<accession>/bbi/` | pyBigWig remote range reads; the file is found by listing the assembly's `bbi/` prefix |
43
+
44
+ Conservation tracks: `phyloP100way`, `phastCons100way`, `phyloP447way` (default), `phyloP447wayPrimates`, `phyloP447wayLRT`. All are hg38.
45
+
46
+ `toga_genes` returns the reference transcript, the region on the query assembly, UCSC's gene classification (`status`) and the chain and intactness scores stored in the file. It omits the four columns that hold HTML and SVG for the browser popup.
47
+
48
+ ## Measurements
49
+
50
+ Taken on 2026-10-13 from a single machine, one request at a time.
51
+
52
+ - Conservation: opening a bigWig took about 1 s the first time. A 20-base query took 0.13 s, and a mean over 10 kb took 0.54 s.
53
+ - Multiz on chr1 (a 4.9 GB file): locating a position took 16 requests and 4.2 s.
54
+ - TOGA on one marmoset assembly: 239 genes from a 5 Mb region took 1.4 s.
55
+ - Multiz search correctness: the position search was compared with a full parse of `chrY.maf` (558,379 blocks). Over 300 random windows the two returned identical block lists.
56
+ - The mammals hub listed 1,006 assemblies on 2026-10-13.
57
+
58
+ ## Limits
59
+
60
+ - The multiz files that can be read this way contain nine species: hg38, rheMac3, canFam3, loxAfr3, galGal4, mm10, xenTro7, danRer10 and petMar2 (the species the UCSC browser shows by default). The full 100-way MAFs under `goldenPath/hg38/multiz100way/maf/` are plain gzip, which cannot be read from the middle, so this package does not use them.
61
+ - The Cactus 241-way and 447-way alignments are HAL files of about 0.8 and 1.2 TB on UCSC's own server, not in this bucket. This package does not read them. Only their conservation scores are read, from the bigWig files UCSC publishes.
62
+ - Conservation and multiz cover hg38 only.
63
+ - TOGA annotations exist for a minority of assemblies. In a random sample of 20 mammal and 20 bird assemblies, 2 of each had one. `toga_genes` raises `ValueError` if an assembly has none. Coordinates are on the query assembly and use its own sequence names, listed by `toga_chromosomes(accession)`.
64
+ - TOGA reads over 2 Mb windows were slow on some assemblies: the 20-assembly mammal sample took 382 s in total, against 8 s for the bird sample. The cause has not been identified.
65
+ - `multiz_alignment` projects onto hg38. Insertions relative to hg38 are dropped, a species with a gap gets `-`, and a base that no block covers is `.` in every row.
66
+ - `multiz_blocks` raises if a window needs more than `max_bytes` (64 MB by default) of a file.
67
+ - Chromosome names `1`, `chr1`, `CHR1` and `MT` are normalized to UCSC's spelling. A name that is not in hg38, a negative start, or a window past the end of the chromosome raises `ValueError`.
68
+ - The tests that read the live bucket are skipped unless `SCIGANTIC_UCSC_LIVE=1` is set, so CI does not depend on UCSC or AWS.
69
+
70
+ ## Data and citation
71
+
72
+ The data is produced by UCSC and by the groups behind each track. The track description pages on genome.ucsc.edu give the citation for each. This package is not affiliated with UCSC.
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "scigantic-ucsc"
7
+ version = "0.1.0"
8
+ description = "Read UCSC Genome Browser conservation scores, multiz alignments and mammal assembly lists straight from UCSC's public S3 bucket, without downloading the files."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT-0" }
12
+ authors = [{ name = "Scigantic" }]
13
+ keywords = ["ucsc", "genome-browser", "comparative-genomics", "phylop", "multiz", "bigwig"]
14
+ classifiers = [
15
+ "License :: OSI Approved :: MIT No Attribution License (MIT-0)",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Typing :: Typed",
21
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
22
+ ]
23
+
24
+ dependencies = [
25
+ "numpy>=1.24",
26
+ "pyBigWig>=0.3.22",
27
+ ]
28
+
29
+ [project.optional-dependencies]
30
+ dev = ["pytest>=7", "mypy>=1.10"]
31
+
32
+ [project.urls]
33
+ Homepage = "https://scigantic.com"
34
+ Repository = "https://github.com/Scigantic/scigantic-ucsc"
35
+ Issues = "https://github.com/Scigantic/scigantic-ucsc/issues"
36
+
37
+ [tool.setuptools.packages.find]
38
+ where = ["src"]
39
+
40
+ [tool.setuptools.package-data]
41
+ scigantic_ucsc = ["py.typed"]
42
+
43
+ [tool.pytest.ini_options]
44
+ testpaths = ["tests"]
45
+ markers = ["live: reads the real UCSC bucket; run with SCIGANTIC_UCSC_LIVE=1"]
46
+
47
+ [tool.mypy]
48
+ strict = true
49
+
50
+ # pyBigWig ships no type stubs; nothing to fix on our side.
51
+ [[tool.mypy.overrides]]
52
+ module = "pyBigWig.*"
53
+ ignore_missing_imports = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,12 @@
1
+ """Read UCSC Genome Browser data from its public S3 bucket without downloading it."""
2
+ from .assemblies import Assembly, assemblies, find
3
+ from .conservation import TRACKS, chromosomes, conservation, conservation_bins
4
+ from .toga import Gene, toga_chromosomes, toga_genes
5
+ from .multiz import Block, Row, alignment as multiz_alignment, blocks as multiz_blocks
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = [
10
+ "Assembly", "Block", "Gene", "Row", "TRACKS",
11
+ "assemblies", "multiz_alignment", "toga_chromosomes", "toga_genes", "chromosomes", "conservation", "conservation_bins", "find", "multiz_blocks",
12
+ ]
@@ -0,0 +1,46 @@
1
+ """Byte-range reads against the public UCSC bucket."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+ import urllib.error
6
+ import urllib.request
7
+ from typing import Any
8
+
9
+ BASE = "https://genome-browser.s3.amazonaws.com"
10
+ _RETRIES = 3
11
+
12
+
13
+ def url(key: str) -> str:
14
+ return f"{BASE}/{key.lstrip('/')}"
15
+
16
+
17
+ def _open(req: urllib.request.Request) -> Any:
18
+ last: Exception | None = None
19
+ for attempt in range(_RETRIES):
20
+ try:
21
+ return urllib.request.urlopen(req, timeout=30)
22
+ except urllib.error.HTTPError as exc:
23
+ # 4xx other than throttling will not get better by asking again.
24
+ if exc.code < 500 and exc.code != 429:
25
+ raise
26
+ last = exc
27
+ except (urllib.error.URLError, TimeoutError) as exc:
28
+ last = exc
29
+ time.sleep(0.5 * 2**attempt)
30
+ assert last is not None
31
+ raise last
32
+
33
+
34
+ def size(key: str) -> int:
35
+ resp = _open(urllib.request.Request(url(key), method="HEAD"))
36
+ return int(resp.headers["Content-Length"])
37
+
38
+
39
+ def get_range(key: str, start: int, end: int) -> bytes:
40
+ """Bytes start..end inclusive."""
41
+ req = urllib.request.Request(url(key), headers={"Range": f"bytes={start}-{end}"})
42
+ return _open(req).read() # type: ignore[no-any-return]
43
+
44
+
45
+ def get(key: str) -> bytes:
46
+ return _open(urllib.request.Request(url(key))).read() # type: ignore[no-any-return]
@@ -0,0 +1,15 @@
1
+ """Chromosome name handling shared by the readers."""
2
+ from __future__ import annotations
3
+
4
+
5
+ def chrom_name(chrom: str) -> str:
6
+ """'1', 'chr1', 'CHR1' -> 'chr1'; 'MT', 'M', 'chrMT' -> 'chrM'."""
7
+ c = chrom.strip()
8
+ if c.lower().startswith("chr"):
9
+ c = c[3:]
10
+ if c.upper() in ("M", "MT"):
11
+ return "chrM"
12
+ if not c:
13
+ raise ValueError("empty chromosome name")
14
+ # UCSC spells X, Y and alt contigs with the chr prefix and keeps the rest.
15
+ return "chr" + (c.upper() if c.upper() in ("X", "Y") or c.isdigit() else c)
@@ -0,0 +1,48 @@
1
+ """The genome assemblies UCSC lists for a hub group, such as mammals or birds."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from dataclasses import dataclass
6
+ from functools import lru_cache
7
+
8
+ from . import _http
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Assembly:
13
+ tax_id: int
14
+ asm_id: str
15
+ genbank: str | None
16
+ refseq: str | None
17
+ scientific_name: str
18
+ common_name: str
19
+ browser_url: str
20
+
21
+
22
+ @lru_cache(maxsize=8)
23
+ def assemblies(group: str = "mammals") -> tuple[Assembly, ...]:
24
+ """Every assembly in hubs/<group> (for example 'mammals', 'birds', 'fish', 'VGP')."""
25
+ raw = json.loads(_http.get(f"hubs/{group}/assemblyList.json"))
26
+ cols = [c["name"] for c in raw["columns"]]
27
+ out = []
28
+ for row in raw["data"]:
29
+ # UCSC writes each row as an object; fall back to positional for a list.
30
+ r = row if isinstance(row, dict) else dict(zip(cols, row))
31
+ out.append(
32
+ Assembly(
33
+ tax_id=r["taxId"],
34
+ asm_id=r["asmId"],
35
+ genbank=r.get("genBank"),
36
+ refseq=r.get("refSeq"),
37
+ scientific_name=r["sciName"],
38
+ common_name=r["comName"],
39
+ browser_url=r["ucscBrowser"],
40
+ )
41
+ )
42
+ return tuple(out)
43
+
44
+
45
+ def find(text: str, group: str = "mammals") -> list[Assembly]:
46
+ """Assemblies whose scientific or common name contains `text` (case-insensitive)."""
47
+ t = text.lower()
48
+ return [a for a in assemblies(group) if t in a.scientific_name.lower() or t in a.common_name.lower()]
@@ -0,0 +1,86 @@
1
+ """Per-base conservation scores (phyloP, phastCons) from UCSC bigWig files."""
2
+ from __future__ import annotations
3
+
4
+ import threading
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+ import numpy.typing as npt
9
+
10
+ from ._http import url
11
+ from ._names import chrom_name
12
+
13
+ # track name -> published path in the bucket. hg38 only: these are the files
14
+ # UCSC publishes under goldenPath/hg38.
15
+ TRACKS: dict[str, str] = {
16
+ "phyloP100way": "goldenPath/hg38/phyloP100way/hg38.phyloP100way.bw",
17
+ "phastCons100way": "goldenPath/hg38/phastCons100way/hg38.phastCons100way.bw",
18
+ "phyloP447way": "goldenPath/hg38/phyloP447way/hg38.phyloP447way.bw",
19
+ "phyloP447wayPrimates": "goldenPath/hg38/phyloP447way/hg38.phyloP447wayPrimates.bw",
20
+ "phyloP447wayLRT": "goldenPath/hg38/phyloP447way/hg38.phyloP447wayLRT.bw",
21
+ }
22
+
23
+
24
+ # pyBigWig does not document its handles as thread-safe, so each thread opens
25
+ # its own rather than sharing one behind a lock.
26
+ _local = threading.local()
27
+
28
+
29
+ def _open(track: str) -> Any:
30
+ import pyBigWig
31
+
32
+ try:
33
+ key = TRACKS[track]
34
+ except KeyError:
35
+ raise ValueError(f"unknown track {track!r}; choose from {sorted(TRACKS)}") from None
36
+ handles = _local.__dict__.setdefault("handles", {})
37
+ if track not in handles:
38
+ bw = pyBigWig.open(url(key))
39
+ if bw is None:
40
+ raise OSError(f"could not open {url(key)}")
41
+ handles[track] = bw
42
+ return handles[track]
43
+
44
+
45
+ def _check(bw: Any, chrom: str, start: int, end: int) -> str:
46
+ if end <= start:
47
+ raise ValueError("end must be greater than start")
48
+ chrom = chrom_name(chrom)
49
+ sizes = bw.chroms()
50
+ if chrom not in sizes:
51
+ raise ValueError(f"{chrom!r} is not in this track's assembly (hg38)")
52
+ if start < 0 or end > sizes[chrom]:
53
+ raise ValueError(f"{chrom}:{start}-{end} is outside 0-{sizes[chrom]}")
54
+ return chrom
55
+
56
+
57
+ def conservation(
58
+ chrom: str, start: int, end: int, track: str = "phyloP447way"
59
+ ) -> npt.NDArray[np.float64]:
60
+ """Score for every base in chrom:start-end (0-based, end exclusive).
61
+
62
+ Bases the track has no value for come back as NaN.
63
+ """
64
+ if end <= start:
65
+ raise ValueError("end must be greater than start")
66
+ bw = _open(track)
67
+ chrom = _check(bw, chrom, start, end)
68
+ values = bw.values(chrom, start, end)
69
+ return np.asarray(values, dtype=np.float64)
70
+
71
+
72
+ def conservation_bins(
73
+ chrom: str, start: int, end: int, bins: int = 100, track: str = "phyloP447way"
74
+ ) -> npt.NDArray[np.float64]:
75
+ """Mean score in `bins` equal windows across chrom:start-end. NaN where empty."""
76
+ if end <= start:
77
+ raise ValueError("end must be greater than start")
78
+ bw = _open(track)
79
+ chrom = _check(bw, chrom, start, end)
80
+ out = bw.stats(chrom, start, end, type="mean", nBins=bins)
81
+ return np.array([np.nan if v is None else v for v in out], dtype=np.float64)
82
+
83
+
84
+ def chromosomes(track: str = "phyloP447way") -> dict[str, int]:
85
+ """Chromosome name -> length for the track's assembly."""
86
+ return dict(_open(track).chroms())
@@ -0,0 +1,199 @@
1
+ """Slice the hg38 multiz alignment by position without downloading a chromosome.
2
+
3
+ UCSC publishes the alignment as one uncompressed MAF per chromosome under
4
+ gbdb/hg38/multiz100way/defaultMaf. A MAF is sorted by reference position and
5
+ has no index, so a position is found by binary search over byte-range reads:
6
+ about 16 requests for chr1, a few seconds.
7
+
8
+ defaultMaf holds only the nine species the browser shows by default (human,
9
+ rhesus, dog, elephant, chicken, mouse, frog, zebrafish, sea lamprey), not the
10
+ full 100. The full 100-way files under goldenPath are plain gzip and cannot be
11
+ seeked, so they are not used here.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ import urllib.error
17
+ from dataclasses import dataclass
18
+ from typing import Callable, Iterable
19
+
20
+ from . import _http
21
+ from ._names import chrom_name
22
+
23
+ PREFIX = "gbdb/hg38/multiz100way/defaultMaf"
24
+ _PROBE = 1 << 16
25
+ _READ = 1 << 20
26
+
27
+ _HEADER = re.compile(r"(?m)^a score")
28
+ _S_LINE = re.compile(r"\ns (\S+)\s+(\d+)\s+(\d+)\s+([+-])\s+(\d+)\s+(\S+)")
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Row:
33
+ src: str
34
+ start: int
35
+ size: int
36
+ strand: str
37
+ src_size: int
38
+ text: str
39
+
40
+ @property
41
+ def species(self) -> str:
42
+ return self.src.split(".", 1)[0]
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Block:
47
+ score: float
48
+ rows: tuple[Row, ...]
49
+
50
+ @property
51
+ def ref(self) -> Row:
52
+ return self.rows[0]
53
+
54
+ def by_species(self) -> dict[str, Row]:
55
+ return {r.species: r for r in self.rows}
56
+
57
+
58
+ Reader = Callable[[str, int, int], bytes]
59
+
60
+
61
+ def parse_block(text: str) -> Block:
62
+ lines = text.strip("\n").split("\n")
63
+ score = 0.0
64
+ if lines[0].startswith("a"):
65
+ m = re.search(r"score=(\S+)", lines[0])
66
+ score = float(m.group(1)) if m else 0.0
67
+ rows = []
68
+ for ln in lines[1:]:
69
+ if ln.startswith("s "):
70
+ f = ln.split()
71
+ rows.append(Row(f[1], int(f[2]), int(f[3]), f[4], int(f[5]), f[6]))
72
+ return Block(score, tuple(rows))
73
+
74
+
75
+ def _next_block(data: str, off: int) -> tuple[int, int] | None:
76
+ """(offset in data of the first block start at/after off, its ref start)."""
77
+ i = data.find("\na score", off)
78
+ if i < 0:
79
+ return None
80
+ i += 1
81
+ m = _S_LINE.search(data, i)
82
+ if m is None:
83
+ return None
84
+ return i, int(m.group(2))
85
+
86
+
87
+ def _seek(key: str, pos: int, n: int, read: Reader) -> int:
88
+ """Byte offset from which reading forward reaches every block overlapping pos."""
89
+ lo, hi = 0, n
90
+ while hi - lo > 2 * _PROBE:
91
+ mid = (lo + hi) // 2
92
+ data = read(key, mid, min(mid + _PROBE, n - 1)).decode("latin1")
93
+ nb = _next_block(data, 0)
94
+ if nb is None or nb[1] >= pos:
95
+ hi = mid
96
+ else:
97
+ lo = mid
98
+ return lo
99
+
100
+
101
+ def blocks(
102
+ chrom: str,
103
+ start: int,
104
+ end: int,
105
+ species: Iterable[str] | None = None,
106
+ max_bytes: int = 64 << 20,
107
+ *,
108
+ _read: Reader | None = None,
109
+ _size: int | None = None,
110
+ ) -> list[Block]:
111
+ """Alignment blocks overlapping chrom:start-end (0-based, end exclusive).
112
+
113
+ Blocks are returned whole, so they can extend past the requested window.
114
+ `species` keeps only those rows (the human reference row is always kept).
115
+ Raises if the window needs more than `max_bytes` of the file.
116
+ """
117
+ if end <= start:
118
+ raise ValueError("end must be greater than start")
119
+ chrom = chrom_name(chrom)
120
+ key = f"{PREFIX}/{chrom}.maf"
121
+ read = _read or _http.get_range
122
+ try:
123
+ n = _size if _size is not None else _http.size(key)
124
+ except urllib.error.HTTPError as exc:
125
+ if exc.code in (403, 404):
126
+ raise ValueError(f"no hg38 alignment file for {chrom!r}") from None
127
+ raise
128
+ keep = set(species) if species is not None else None
129
+
130
+ off = _seek(key, start, n, read)
131
+ out: list[Block] = []
132
+ carry = ""
133
+ fetched = 0
134
+ done = False
135
+ while off < n and not done:
136
+ if fetched >= max_bytes:
137
+ raise ValueError(f"window needs more than {max_bytes} bytes of {key}; narrow it")
138
+ chunk = read(key, off, min(off + _READ, n) - 1).decode("latin1")
139
+ fetched += len(chunk)
140
+ off += len(chunk)
141
+ text = carry + chunk
142
+ parts = text.split("\n\n")
143
+ carry = parts.pop() if off < n else ""
144
+ if off >= n:
145
+ parts = text.split("\n\n")
146
+ for part in parts:
147
+ m = _HEADER.search(part)
148
+ if m is None:
149
+ continue
150
+ b = parse_block(part[m.start():])
151
+ if not b.rows:
152
+ continue
153
+ r = b.ref
154
+ if r.start >= end:
155
+ done = True
156
+ break
157
+ if r.start + r.size <= start:
158
+ continue
159
+ if keep is not None:
160
+ b = Block(b.score, tuple(x for x in b.rows if x is b.rows[0] or x.species in keep))
161
+ out.append(b)
162
+ return out
163
+
164
+
165
+ def alignment(
166
+ chrom: str,
167
+ start: int,
168
+ end: int,
169
+ species: Iterable[str] | None = None,
170
+ max_bytes: int = 64 << 20,
171
+ **kw: object,
172
+ ) -> dict[str, str]:
173
+ """Species -> aligned string of exactly end-start columns, one per hg38 base.
174
+
175
+ The alignment is projected onto the human reference: insertions relative to
176
+ hg38 are dropped, a species with a gap gets '-', and a base that no block
177
+ covers is '.' in every row. Soft-masking (lowercase) is kept.
178
+ """
179
+ bl = blocks(chrom, start, end, species=species, max_bytes=max_bytes, **kw) # type: ignore[arg-type]
180
+ width = end - start
181
+ names: list[str] = ["hg38"]
182
+ for b in bl:
183
+ for r in b.rows[1:]:
184
+ if r.species not in names:
185
+ names.append(r.species)
186
+ grid = {n: ["."] * width for n in names}
187
+ for b in bl:
188
+ pos = b.ref.start
189
+ present = {r.species: r.text for r in b.rows}
190
+ for col, base in enumerate(b.ref.text):
191
+ if base == "-":
192
+ continue # insertion relative to hg38
193
+ if start <= pos < end:
194
+ i = pos - start
195
+ for n in names:
196
+ t = present.get(n)
197
+ grid[n][i] = "-" if t is None else t[col]
198
+ pos += 1
199
+ return {n: "".join(v) for n, v in grid.items()}
File without changes
@@ -0,0 +1,132 @@
1
+ """TOGA gene annotations for any assembly in a UCSC hub, read by region.
2
+
3
+ TOGA (Tool to infer Orthologs from Genome Alignments) projects a reference
4
+ annotation (human for mammals, chicken for birds) onto a query assembly and
5
+ classifies each gene as intact, lost and so on. UCSC mirrors the result as one
6
+ bigBed per assembly. Coordinates are on the query assembly, not on hg38.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import threading
12
+ import urllib.request
13
+ from dataclasses import dataclass
14
+ from functools import lru_cache
15
+ from typing import Any
16
+
17
+ from . import _http
18
+
19
+ _ACC = re.compile(r"^(GC[AF])_(\d{3})(\d{3})(\d{3})\.(\d+)$")
20
+
21
+ # bigBed columns after chrom/start/end, in file order, up to the last scalar.
22
+ # The remaining four are HTML and SVG blobs that are tens of kB per gene.
23
+ _FIELDS = (
24
+ "name", "score", "strand", "thick_start", "thick_end", "item_rgb", "block_count",
25
+ "block_sizes", "block_starts", "ref_transcript", "ref_region", "query_region",
26
+ "chain_score", "chain_synteny", "chain_flank", "chain_gl_cds_fract",
27
+ "chain_loc_cds_fract", "chain_exon_cov", "chain_intron_cov", "status",
28
+ "perc_intact_ign_missing", "perc_intact_int_missing", "intact_codon_prop",
29
+ "ouf_prop", "mid_intact", "mid_present",
30
+ )
31
+ _FLOATS = {
32
+ "chain_score", "chain_synteny", "chain_flank", "chain_gl_cds_fract",
33
+ "chain_loc_cds_fract", "chain_exon_cov", "chain_intron_cov",
34
+ "perc_intact_ign_missing", "perc_intact_int_missing", "intact_codon_prop", "ouf_prop",
35
+ }
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Gene:
40
+ chrom: str
41
+ start: int
42
+ end: int
43
+ name: str
44
+ strand: str
45
+ ref_transcript: str
46
+ ref_region: str
47
+ query_region: str
48
+ status: str
49
+ fields: dict[str, Any]
50
+
51
+ @property
52
+ def gene_symbol(self) -> str:
53
+ """The reference gene symbol, from names like ENST00000308824.PCMTD2.47."""
54
+ parts = self.name.split(".")
55
+ return parts[1] if len(parts) >= 3 else self.name
56
+
57
+
58
+ def _prefix(accession: str) -> str:
59
+ m = _ACC.match(accession.strip())
60
+ if m is None:
61
+ raise ValueError(f"{accession!r} is not a GenBank or RefSeq accession like GCF_001458135.1")
62
+ return f"hubs/{m[1]}/{m[2]}/{m[3]}/{m[4]}/{accession.strip()}/bbi/"
63
+
64
+
65
+ @lru_cache(maxsize=256)
66
+ def toga_key(accession: str) -> str:
67
+ """Bucket key of the TOGA bigBed for an assembly accession."""
68
+ prefix = _prefix(accession)
69
+ xml = urllib.request.urlopen(
70
+ f"{_http.BASE}/?list-type=2&prefix={prefix}", timeout=30
71
+ ).read().decode()
72
+ keys = [k for k in re.findall(r"<Key>([^<]+)</Key>", xml) if "TOGA" in k and k.endswith(".bb")]
73
+ if not keys:
74
+ raise ValueError(f"no TOGA annotation for {accession}")
75
+ return str(keys[0])
76
+
77
+
78
+ _local = threading.local()
79
+
80
+
81
+ def _open(accession: str) -> Any:
82
+ import pyBigWig
83
+
84
+ handles = _local.__dict__.setdefault("handles", {})
85
+ if accession not in handles:
86
+ bb = pyBigWig.open(_http.url(toga_key(accession)))
87
+ if bb is None:
88
+ raise OSError(f"could not open the TOGA track for {accession}")
89
+ handles[accession] = bb
90
+ return handles[accession]
91
+
92
+
93
+ def toga_chromosomes(accession: str) -> dict[str, int]:
94
+ """Sequence name -> length for the query assembly."""
95
+ return dict(_open(accession).chroms())
96
+
97
+
98
+ def parse_entry(chrom: str, start: int, end: int, rest: str) -> Gene:
99
+ vals = rest.split("\t")
100
+ f: dict[str, Any] = {}
101
+ for key, raw in zip(_FIELDS, vals):
102
+ f[key] = float(raw) if key in _FLOATS else raw
103
+ return Gene(
104
+ chrom=chrom, start=start, end=end, name=f["name"], strand=f["strand"],
105
+ ref_transcript=f.get("ref_transcript", ""), ref_region=f.get("ref_region", ""),
106
+ query_region=f.get("query_region", ""), status=f.get("status", ""), fields=f,
107
+ )
108
+
109
+
110
+ def toga_genes(
111
+ accession: str, chrom: str, start: int, end: int, status: str | None = None
112
+ ) -> list[Gene]:
113
+ """TOGA genes overlapping chrom:start-end on the query assembly.
114
+
115
+ `status` keeps one classification, for example "Intact" or "Lost" (compared
116
+ case-insensitively). The sequence name is the assembly's own, such as a
117
+ scaffold id; see `toga_chromosomes`.
118
+ """
119
+ if end <= start:
120
+ raise ValueError("end must be greater than start")
121
+ bb = _open(accession)
122
+ sizes = bb.chroms()
123
+ if chrom not in sizes:
124
+ raise ValueError(f"{chrom!r} is not a sequence in {accession}")
125
+ if start < 0 or end > sizes[chrom]:
126
+ raise ValueError(f"{chrom}:{start}-{end} is outside 0-{sizes[chrom]}")
127
+ out = []
128
+ for s, e, rest in bb.entries(chrom, start, end) or []:
129
+ g = parse_entry(chrom, s, e, rest)
130
+ if status is None or g.status.lower() == status.lower():
131
+ out.append(g)
132
+ return out
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: scigantic-ucsc
3
+ Version: 0.1.0
4
+ Summary: Read UCSC Genome Browser conservation scores, multiz alignments and mammal assembly lists straight from UCSC's public S3 bucket, without downloading the files.
5
+ Author: Scigantic
6
+ License: MIT-0
7
+ Project-URL: Homepage, https://scigantic.com
8
+ Project-URL: Repository, https://github.com/Scigantic/scigantic-ucsc
9
+ Project-URL: Issues, https://github.com/Scigantic/scigantic-ucsc/issues
10
+ Keywords: ucsc,genome-browser,comparative-genomics,phylop,multiz,bigwig
11
+ Classifier: License :: OSI Approved :: MIT No Attribution License (MIT-0)
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Typing :: Typed
17
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: numpy>=1.24
22
+ Requires-Dist: pyBigWig>=0.3.22
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7; extra == "dev"
25
+ Requires-Dist: mypy>=1.10; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # scigantic-ucsc
29
+
30
+ Python readers for four kinds of data in UCSC's public S3 bucket (`s3://genome-browser`, us-east-1, anonymous access): per-base conservation scores, hg38 multiz alignment blocks, TOGA gene annotations, and the assembly lists of UCSC's genome hubs. Each function reads only the byte ranges it needs over HTTPS, so no file is downloaded in full.
31
+
32
+ ```python
33
+ import scigantic_ucsc as ucsc
34
+
35
+ # phyloP scores, hg38, 0-based half-open coordinates
36
+ scores = ucsc.conservation("chr17", 43_044_295, 43_044_395, track="phyloP447way")
37
+
38
+ # mean score in 50 equal windows
39
+ bins = ucsc.conservation_bins("chr17", 43_044_295, 43_054_295, bins=50)
40
+
41
+ # multiz alignment blocks overlapping a region
42
+ blocks = ucsc.multiz_blocks("chr1", 1_000_000, 1_000_300, species=["mm10", "canFam3"])
43
+
44
+ # the same region as one string per species, one column per hg38 base
45
+ aln = ucsc.multiz_alignment("chr1", 1_000_000, 1_000_100, species=["mm10", "canFam3"])
46
+
47
+ # assemblies listed in the mammals hub
48
+ ucsc.find("marmoset")
49
+
50
+ # TOGA genes classified "Lost" in a region of a query assembly
51
+ genes = ucsc.toga_genes("GCF_001458135.1", "CZRN01000001", 0, 5_000_000, status="Lost")
52
+ ```
53
+
54
+ ## Installation
55
+
56
+ ```console
57
+ $ pip install scigantic-ucsc
58
+ ```
59
+
60
+ Requires Python 3.10 or later, numpy and pyBigWig.
61
+
62
+ ## Functions and sources
63
+
64
+ | Function | Reads | Method |
65
+ |---|---|---|
66
+ | `conservation`, `conservation_bins` | bigWig files under `goldenPath/hg38/` | pyBigWig remote range reads |
67
+ | `multiz_blocks`, `multiz_alignment` | `gbdb/hg38/multiz100way/defaultMaf/<chrom>.maf` | binary search by position over HTTP byte ranges; the files have no index |
68
+ | `assemblies`, `find` | `hubs/<group>/assemblyList.json` | one JSON file per group, cached in memory |
69
+ | `toga_genes`, `toga_chromosomes` | the `*TOGA*.bb` bigBed in `hubs/<GCF or GCA>/.../<accession>/bbi/` | pyBigWig remote range reads; the file is found by listing the assembly's `bbi/` prefix |
70
+
71
+ Conservation tracks: `phyloP100way`, `phastCons100way`, `phyloP447way` (default), `phyloP447wayPrimates`, `phyloP447wayLRT`. All are hg38.
72
+
73
+ `toga_genes` returns the reference transcript, the region on the query assembly, UCSC's gene classification (`status`) and the chain and intactness scores stored in the file. It omits the four columns that hold HTML and SVG for the browser popup.
74
+
75
+ ## Measurements
76
+
77
+ Taken on 2026-10-13 from a single machine, one request at a time.
78
+
79
+ - Conservation: opening a bigWig took about 1 s the first time. A 20-base query took 0.13 s, and a mean over 10 kb took 0.54 s.
80
+ - Multiz on chr1 (a 4.9 GB file): locating a position took 16 requests and 4.2 s.
81
+ - TOGA on one marmoset assembly: 239 genes from a 5 Mb region took 1.4 s.
82
+ - Multiz search correctness: the position search was compared with a full parse of `chrY.maf` (558,379 blocks). Over 300 random windows the two returned identical block lists.
83
+ - The mammals hub listed 1,006 assemblies on 2026-10-13.
84
+
85
+ ## Limits
86
+
87
+ - The multiz files that can be read this way contain nine species: hg38, rheMac3, canFam3, loxAfr3, galGal4, mm10, xenTro7, danRer10 and petMar2 (the species the UCSC browser shows by default). The full 100-way MAFs under `goldenPath/hg38/multiz100way/maf/` are plain gzip, which cannot be read from the middle, so this package does not use them.
88
+ - The Cactus 241-way and 447-way alignments are HAL files of about 0.8 and 1.2 TB on UCSC's own server, not in this bucket. This package does not read them. Only their conservation scores are read, from the bigWig files UCSC publishes.
89
+ - Conservation and multiz cover hg38 only.
90
+ - TOGA annotations exist for a minority of assemblies. In a random sample of 20 mammal and 20 bird assemblies, 2 of each had one. `toga_genes` raises `ValueError` if an assembly has none. Coordinates are on the query assembly and use its own sequence names, listed by `toga_chromosomes(accession)`.
91
+ - TOGA reads over 2 Mb windows were slow on some assemblies: the 20-assembly mammal sample took 382 s in total, against 8 s for the bird sample. The cause has not been identified.
92
+ - `multiz_alignment` projects onto hg38. Insertions relative to hg38 are dropped, a species with a gap gets `-`, and a base that no block covers is `.` in every row.
93
+ - `multiz_blocks` raises if a window needs more than `max_bytes` (64 MB by default) of a file.
94
+ - Chromosome names `1`, `chr1`, `CHR1` and `MT` are normalized to UCSC's spelling. A name that is not in hg38, a negative start, or a window past the end of the chromosome raises `ValueError`.
95
+ - The tests that read the live bucket are skipped unless `SCIGANTIC_UCSC_LIVE=1` is set, so CI does not depend on UCSC or AWS.
96
+
97
+ ## Data and citation
98
+
99
+ The data is produced by UCSC and by the groups behind each track. The track description pages on genome.ucsc.edu give the citation for each. This package is not affiliated with UCSC.
@@ -0,0 +1,19 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/scigantic_ucsc/__init__.py
5
+ src/scigantic_ucsc/_http.py
6
+ src/scigantic_ucsc/_names.py
7
+ src/scigantic_ucsc/assemblies.py
8
+ src/scigantic_ucsc/conservation.py
9
+ src/scigantic_ucsc/multiz.py
10
+ src/scigantic_ucsc/py.typed
11
+ src/scigantic_ucsc/toga.py
12
+ src/scigantic_ucsc.egg-info/PKG-INFO
13
+ src/scigantic_ucsc.egg-info/SOURCES.txt
14
+ src/scigantic_ucsc.egg-info/dependency_links.txt
15
+ src/scigantic_ucsc.egg-info/requires.txt
16
+ src/scigantic_ucsc.egg-info/top_level.txt
17
+ tests/test_conservation_assemblies.py
18
+ tests/test_multiz.py
19
+ tests/test_toga.py
@@ -0,0 +1,6 @@
1
+ numpy>=1.24
2
+ pyBigWig>=0.3.22
3
+
4
+ [dev]
5
+ pytest>=7
6
+ mypy>=1.10
@@ -0,0 +1 @@
1
+ scigantic_ucsc
@@ -0,0 +1,53 @@
1
+ import os
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import scigantic_ucsc as u
7
+
8
+ live = pytest.mark.skipif(not os.environ.get("SCIGANTIC_UCSC_LIVE"), reason="live bucket")
9
+
10
+
11
+ def test_unknown_track():
12
+ with pytest.raises(ValueError, match="unknown track"):
13
+ u.conservation("chr1", 0, 10, track="nope")
14
+
15
+
16
+ def test_empty_window():
17
+ with pytest.raises(ValueError):
18
+ u.conservation("chr1", 5, 5)
19
+
20
+
21
+ @live
22
+ def test_live_conservation():
23
+ v = u.conservation("chr1", 1_000_000, 1_000_020)
24
+ assert v.shape == (20,) and np.isfinite(v).any()
25
+ assert u.conservation_bins("chr17", 43_044_295, 43_054_295, bins=10).shape == (10,)
26
+
27
+
28
+ @live
29
+ def test_live_assemblies():
30
+ a = u.assemblies("mammals")
31
+ assert len(a) > 500
32
+ assert any("aardvark" in x.common_name for x in u.find("aardvark"))
33
+
34
+
35
+ def test_chrom_names():
36
+ from scigantic_ucsc._names import chrom_name
37
+ assert [chrom_name(x) for x in ("1", "chr1", "CHR1", "x", "MT", "chrM", "chrUn_KI270302v1")] == [
38
+ "chr1", "chr1", "chr1", "chrX", "chrM", "chrM", "chrUn_KI270302v1"]
39
+ with pytest.raises(ValueError):
40
+ chrom_name(" ")
41
+
42
+
43
+ @live
44
+ def test_live_bad_inputs_are_readable_errors():
45
+ with pytest.raises(ValueError, match="not in this track"):
46
+ u.conservation("chrZ", 0, 10)
47
+ with pytest.raises(ValueError, match="outside"):
48
+ u.conservation("chr1", -5, 10)
49
+ with pytest.raises(ValueError, match="outside"):
50
+ u.conservation("chr1", 248956400, 248956500)
51
+ with pytest.raises(ValueError, match="no hg38 alignment"):
52
+ u.multiz_blocks("chrZ", 0, 10)
53
+ assert u.conservation("1", 1_000_000, 1_000_010).shape == (10,)
@@ -0,0 +1,97 @@
1
+ import os, random
2
+
3
+ import pytest
4
+
5
+ from scigantic_ucsc import multiz
6
+
7
+
8
+ def _maf(n_blocks=4000, seed=1):
9
+ rnd = random.Random(seed)
10
+ out = ["##maf version=1 scoring=roast.v3.3\n"]
11
+ pos = 100
12
+ spans = []
13
+ for i in range(n_blocks):
14
+ size = rnd.randint(20, 400)
15
+ seq = "".join(rnd.choice("acgt") for _ in range(size))
16
+ out.append(f"a score={i}.0\n"
17
+ f"s hg38.chr1 {pos} {size} + 1000000 {seq}\n"
18
+ f"s mm10.chr2 {pos + 5} {size} - 900000 {seq}\n"
19
+ f"s canFam4.chr3 {pos + 9} {size} + 800000 {seq}\n\n")
20
+ spans.append((pos, pos + size))
21
+ pos += size + rnd.randint(1, 300)
22
+ return "".join(out).encode(), spans
23
+
24
+
25
+ DATA, SPANS = _maf()
26
+
27
+
28
+ def _read(key, a, b):
29
+ return DATA[a:b + 1]
30
+
31
+
32
+ def _blocks(start, end, **kw):
33
+ return multiz.blocks("chr1", start, end, _read=_read, _size=len(DATA), **kw)
34
+
35
+
36
+ def test_finds_exactly_the_overlapping_blocks():
37
+ start, end = SPANS[2500][0] + 3, SPANS[2510][1] - 3
38
+ got = [b.ref.start for b in _blocks(start, end)]
39
+ want = [s for s, e in SPANS if s < end and e > start]
40
+ assert got == want
41
+
42
+
43
+ def test_window_inside_one_block_and_in_a_gap():
44
+ s, e = SPANS[1000]
45
+ assert [b.ref.start for b in _blocks(s + 1, s + 2)] == [s]
46
+ gap_a, gap_b = SPANS[1000][1], SPANS[1001][0]
47
+ if gap_b > gap_a:
48
+ assert _blocks(gap_a, gap_b) == []
49
+
50
+
51
+ def test_window_at_the_start_and_end_of_the_file():
52
+ assert _blocks(0, SPANS[0][1])[0].ref.start == SPANS[0][0]
53
+ assert _blocks(SPANS[-1][0], SPANS[-1][1] + 10)[-1].ref.start == SPANS[-1][0]
54
+
55
+
56
+ def test_species_filter_keeps_reference():
57
+ b = _blocks(SPANS[10][0], SPANS[10][1], species=["mm10"])[0]
58
+ assert sorted(b.by_species()) == ["hg38", "mm10"]
59
+
60
+
61
+ def test_row_fields():
62
+ r = _blocks(SPANS[5][0], SPANS[5][1])[0].by_species()["mm10"]
63
+ assert (r.strand, r.src_size, r.start) == ("-", 900000, SPANS[5][0] + 5)
64
+
65
+
66
+ def test_budget_is_enforced():
67
+ with pytest.raises(ValueError, match="narrow it"):
68
+ _blocks(0, 10**9, max_bytes=1 << 16)
69
+
70
+
71
+ def test_empty_window_rejected():
72
+ with pytest.raises(ValueError):
73
+ _blocks(10, 10)
74
+
75
+
76
+ @pytest.mark.live
77
+ @pytest.mark.skipif(not os.environ.get("SCIGANTIC_UCSC_LIVE"), reason="live bucket")
78
+ def test_live_chr1_region():
79
+ bl = multiz.blocks("chr1", 1_000_000, 1_000_300)
80
+ assert bl and bl[0].ref.src.startswith("hg38.chr1")
81
+ assert any(b.ref.start <= 1_000_000 < b.ref.start + b.ref.size or b.ref.start > 1_000_000 for b in bl)
82
+
83
+
84
+ def test_alignment_projects_onto_reference():
85
+ s, e = SPANS[40]
86
+ a = multiz.alignment("chr1", s + 2, e - 2, _read=_read, _size=len(DATA))
87
+ assert set(a) == {"hg38", "mm10", "canFam4"}
88
+ assert all(len(v) == e - s - 4 for v in a.values())
89
+ # mm10 starts 5 bases later than hg38 in the synthetic block, canFam4 9 later
90
+ # but the synthetic rows reuse one sequence, so columns line up one to one
91
+ assert a["hg38"] == a["mm10"] == a["canFam4"]
92
+
93
+
94
+ def test_alignment_marks_uncovered_bases():
95
+ gap_a, gap_b = SPANS[1000][1], SPANS[1001][0]
96
+ a = multiz.alignment("chr1", gap_a - 3, gap_a + (gap_b - gap_a) + 3, _read=_read, _size=len(DATA))
97
+ assert "." in a["hg38"] and a["hg38"].count(".") == gap_b - gap_a
@@ -0,0 +1,34 @@
1
+ import os
2
+
3
+ import pytest
4
+
5
+ from scigantic_ucsc import toga
6
+
7
+ ROW = ("ENST00000308824.PCMTD2.47\t1000\t-\t183903\t197236\t0,0,200\t5\t377,124,\t0,2655,"
8
+ "\tENST00000308824.PCMTD2\tchr20:64255747-64276226\tCZRN01000001:183903-197236\t0.99\t343\t0.30"
9
+ "\t0.03\t0.09\t0.99\t0.63\tIntact\t0.99\t0.98\t0.97\t0.0\t1\t1\t<TT>big html blob")
10
+
11
+
12
+ def test_parse_entry():
13
+ g = toga.parse_entry("CZRN01000001", 183903, 197236, ROW)
14
+ assert (g.status, g.strand, g.gene_symbol) == ("Intact", "-", "PCMTD2")
15
+ assert g.fields["chain_score"] == 0.99 and g.fields["perc_intact_ign_missing"] == 0.99
16
+ assert "prot_alignment" not in g.fields and "<TT>" not in str(g.fields)
17
+
18
+
19
+ def test_accession_paths():
20
+ assert toga._prefix("GCF_001458135.1") == "hubs/GCF/001/458/135/GCF_001458135.1/bbi/"
21
+ assert toga._prefix("GCA_009769595.1").startswith("hubs/GCA/009/769/595/")
22
+ with pytest.raises(ValueError):
23
+ toga._prefix("marmoset")
24
+
25
+
26
+ @pytest.mark.skipif(not os.environ.get("SCIGANTIC_UCSC_LIVE"), reason="live bucket")
27
+ def test_live_marmoset():
28
+ genes = toga.toga_genes("GCF_001458135.1", "CZRN01000001", 0, 5_000_000)
29
+ assert len(genes) > 100
30
+ assert all(g.status for g in genes)
31
+ intact = toga.toga_genes("GCF_001458135.1", "CZRN01000001", 0, 5_000_000, status="intact")
32
+ assert 0 < len(intact) <= len(genes)
33
+ with pytest.raises(ValueError, match="no TOGA"):
34
+ toga.toga_key("GCF_000000000.1")