Download code/vera/references.py from ryan-superman/bio-agent-trajectories: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/datasets/ryan-superman/bio-agent-trajectories/resolve/main/code/vera/references.py
- Command line
-
hf download hf://datasets/ryan-superman/bio-agent-trajectories/code/vera/references.py
-
curl -L -o references.py https://huggingface.co/datasets/ryan-superman/bio-agent-trajectories/resolve/main/code/vera/references.py
13.4 kB
| """Pre-staged references and tested reference-grade computation for agents. | |
| The motivating claim here was originally that the sandbox blocks reference downloads. | |
| That was measured on one transcript and it is **false**. Across every transcript we have, | |
| 39 attempted a reference fetch and they succeed: a 939 MB `hg38.fa` arrives, `bwa index` | |
| completes, `bwa mem` reports `Processed 533334 reads`, and 21 runs produce a sorted BAM. | |
| `Errno 101` appears exactly once. Agents can obtain and index references. | |
| What they get wrong is the statistic computed *from* the alignment. On the Cas9 problem | |
| the baseline built minimap2 from source, indexed hg38, aligned the full library and stated | |
| the correct plan itself -- rank loci by clusters of soft-clipped fragments, because a | |
| nuclease cut gives a sharp breakpoint peak. It then wrote that analysis in awk as | |
| if(c ~ /^[0-9]+S/) L[$4]++; # leading clip: junction at POS -- correct | |
| if(c ~ /[0-9]+S$/) R[$4+ref]++; # trailing clip: POS+ref -- off by one | |
| The last aligned base is POS + ref - 1. Its measurement therefore said left-clips at | |
| 46,373,178 and right-clips at 46,373,179, it read that as a cut between them, and its | |
| independent PAM calculation also said 179. Two errors agreed, so neither was caught, and | |
| the run reported a confident wrong coordinate. | |
| So staging a genome is a convenience. The contribution is a *tested* implementation of the | |
| computation the agent already knows it wants, rather than one re-derived in awk under a | |
| step budget where an off-by-one is invisible. `vera/breakpoints.py` carries a registered | |
| mutation for this exact defect. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import shutil | |
| import subprocess | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| # Roots searched for a staged reference, most specific first. Extend rather than edit: | |
| # an unreachable entry is skipped, so listing several machines is harmless. | |
| REFERENCE_ROOTS = ( | |
| Path(os.environ.get("VERA_REFERENCE_ROOT", "/extra/zhanglab1/pengchx3")), | |
| Path("/srv/disk00/sshfs/pengchx3"), | |
| Path("/tmp/galaxy_srv_disk00/pengchx3"), | |
| ) | |
| class Reference: | |
| """One staged reference genome or transcriptome. | |
| Attributes: | |
| key: Short name used by callers. | |
| relpath: Location under a reference root. | |
| fasta: Filename of the sequence file within that directory. | |
| aligner: Which aligner's index is expected alongside it. | |
| note: What questions this reference can answer. | |
| """ | |
| key: str | |
| relpath: str | |
| fasta: str | |
| aligners: tuple[str, ...] | |
| note: str | |
| def aligner(self) -> str: | |
| """The preferred aligner. Kept so callers that expect one name still work.""" | |
| return self.aligners[0] | |
| REFERENCES: dict[str, Reference] = { | |
| "hg38": Reference( | |
| key="hg38", relpath="hg38", fasta="hg38.fa", aligners=("minimap2", "bwa"), | |
| note="human genome; exact coordinates, split reads, on-target site location", | |
| ), | |
| "hg38-ml": Reference( | |
| key="hg38-ml", relpath="caduceus_hg38", fasta="hg38.ml.fa", | |
| aligners=("minimap2", "bwa"), | |
| note="human genome, alternative staging", | |
| ), | |
| } | |
| # Absolute fallbacks for binaries that may not be on an agent's PATH. The agent's shell | |
| # inherits whatever the harness set and commonly activates its own conda environment | |
| # mid-run, so `which` alone is not a reliable answer to "is this installed". | |
| KNOWN_BINARIES: dict[str, tuple[str, ...]] = { | |
| "minimap2": ("/home/pengchx3/miniconda/bin/minimap2",), | |
| "samtools": ("/usr/bin/samtools", "/home/pengchx3/miniconda/bin/samtools"), | |
| "bwa": ("/extra/zhanglab0/INDV/pengchx3/Biomni/biomni_env/biomni_tools/bin/bwa",), | |
| } | |
| def find_binary(name: str) -> str | None: | |
| """Locate an executable on PATH, falling back to known absolute locations.""" | |
| found = shutil.which(name) | |
| if found: | |
| return found | |
| for candidate in KNOWN_BINARIES.get(name, ()): | |
| if os.access(candidate, os.X_OK): | |
| return candidate | |
| return None | |
| def index_files(fasta: Path, aligner: str) -> tuple[Path, ...]: | |
| """Index files an aligner needs beside `fasta`. | |
| minimap2 can align straight from a FASTA, but building a human index costs minutes | |
| and about 11 GB every call, so a prebuilt `.sr.mmi` is treated as required. The | |
| suffix records the preset: an index built for one preset misaligns under another. | |
| """ | |
| if aligner == "bwa": | |
| return tuple(fasta.with_name(fasta.name + s) | |
| for s in (".amb", ".ann", ".bwt", ".pac", ".sa")) | |
| if aligner == "minimap2": | |
| return (fasta.with_suffix(".sr.mmi"),) | |
| return () | |
| def find_reference(key: str) -> Path | None: | |
| """Locate a staged reference, or None. | |
| Raises: | |
| KeyError: If `key` is not registered, so a typo fails loudly rather than being | |
| reported as a missing reference. | |
| """ | |
| spec = REFERENCES[key] | |
| for root in REFERENCE_ROOTS: | |
| candidate = root / spec.relpath / spec.fasta | |
| try: | |
| if candidate.is_file(): | |
| return candidate | |
| except OSError: | |
| # A stale network mount raises here rather than returning False; probing the | |
| # next root is the point of the loop. | |
| continue | |
| return None | |
| def has_index(fasta: Path, aligner: str = "bwa") -> bool: | |
| """Whether an aligner index sits alongside `fasta`. | |
| Checked because building one for a human genome takes roughly an hour, far beyond an | |
| agent's step budget -- an unindexed reference is not usable inside a run, and saying | |
| so is more useful than letting the agent discover it slowly. | |
| """ | |
| needed = index_files(fasta, aligner) | |
| return bool(needed) and all(p.exists() for p in needed) | |
| def usable_aligners(fasta: Path, spec: Reference) -> list[str]: | |
| """Aligners that are both installed here and indexed against `fasta`.""" | |
| return [name for name in spec.aligners | |
| if find_binary(name) is not None and has_index(fasta, name)] | |
| def aligner_target(fasta: Path, aligner: str) -> Path: | |
| """What to hand the aligner: bwa reads the FASTA, minimap2 reads its own index.""" | |
| return index_files(fasta, aligner)[0] if aligner == "minimap2" else fasta | |
| def available() -> list[dict]: | |
| """Every registered reference, with whether it is staged and indexed.""" | |
| out = [] | |
| for spec in REFERENCES.values(): | |
| path = find_reference(spec.key) | |
| usable = usable_aligners(path, spec) if path else [] | |
| out.append({"key": spec.key, "note": spec.note, | |
| "staged": path is not None, | |
| "indexed": bool(path and any(has_index(path, a) | |
| for a in spec.aligners)), | |
| "aligners": usable, | |
| "path": str(path) if path else ""}) | |
| return out | |
| def align_reads(fastq: Path, reference: str = "hg38", *, n_reads: int = 20_000, | |
| threads: int = 4, timeout: int = 1800) -> dict: | |
| """Align a head sample of reads to a staged reference and summarise where they land. | |
| Args: | |
| fastq: Reads, gzipped or plain. | |
| reference: Registry key. | |
| n_reads: Reads to take from the head. Bounded because the point is to locate | |
| signal, not to produce a publication-grade alignment, and an agent cannot | |
| wait for a full library. | |
| threads: Aligner threads. | |
| timeout: Wall clock, seconds. | |
| Returns: | |
| ``{"reference": path, "n_reads": int, "mapped": int, "top_loci": [...]}`` where | |
| loci are ``(chrom, position_bin, count)`` ordered by count. | |
| Raises: | |
| RuntimeError: If the reference is not staged or indexed, or the aligner is | |
| missing, naming which -- an agent cannot fix any of these from inside the | |
| sandbox, so a precise message is the useful failure. | |
| """ | |
| path, spec, aligner, binary = resolve(reference) | |
| head = fastq.with_suffix(".head.fq") | |
| reader = "zcat" if fastq.suffix == ".gz" else "cat" | |
| subprocess.run(f"{reader} {fastq} | head -n {n_reads * 4} > {head}", | |
| shell=True, check=False, timeout=timeout) | |
| try: | |
| proc = subprocess.run(align_command(aligner, binary, path, [head], threads), | |
| capture_output=True, text=True, errors="replace", | |
| timeout=timeout) | |
| loci: dict[tuple[str, int], int] = {} | |
| mapped = 0 | |
| for line in proc.stdout.splitlines(): | |
| if line.startswith("@"): | |
| continue | |
| parts = line.split("\t") | |
| if len(parts) < 4 or parts[2] == "*": | |
| continue | |
| mapped += 1 | |
| try: | |
| # 1 kb bins: enough to localise a site without pretending to base accuracy. | |
| loci[(parts[2], int(parts[3]) // 1000)] = \ | |
| loci.get((parts[2], int(parts[3]) // 1000), 0) + 1 | |
| except ValueError: | |
| continue | |
| top = sorted(loci.items(), key=lambda kv: -kv[1])[:15] | |
| return {"reference": str(path), "n_reads": n_reads, "mapped": mapped, | |
| "top_loci": [{"chrom": c, "start": b * 1000, "reads": n} | |
| for (c, b), n in top]} | |
| finally: | |
| head.unlink(missing_ok=True) | |
| def resolve(reference: str) -> tuple[Path, Reference, str, str]: | |
| """Locate a staged, indexed, installed reference/aligner pair. | |
| Returns: | |
| ``(fasta, spec, aligner_name, aligner_binary)``. | |
| Raises: | |
| RuntimeError: Naming which of the three preconditions failed. An agent cannot | |
| fix any of them from inside the sandbox, so a precise message is the useful | |
| failure -- and "bwa is missing" once reached a nine-minute alignment before | |
| failing inside a pipe, which is what naming it early prevents. | |
| """ | |
| path = find_reference(reference) | |
| if path is None: | |
| raise RuntimeError(f"reference {reference!r} is not staged on this machine") | |
| spec = REFERENCES[reference] | |
| usable = usable_aligners(path, spec) | |
| if not usable: | |
| installed = [a for a in spec.aligners if find_binary(a)] | |
| if not installed: | |
| raise RuntimeError(f"none of {', '.join(spec.aligners)} is installed") | |
| raise RuntimeError( | |
| f"reference {reference!r} has no index for {', '.join(installed)}; " | |
| f"building one exceeds an agent's budget") | |
| aligner = usable[0] | |
| return path, spec, aligner, find_binary(aligner) | |
| def align_command(aligner: str, binary: str, fasta: Path, fastqs: list[Path], | |
| threads: int) -> list[str]: | |
| """The argv that aligns `fastqs`, writing SAM to stdout.""" | |
| target = str(aligner_target(fasta, aligner)) | |
| reads = [str(f) for f in fastqs] | |
| if aligner == "minimap2": | |
| return [binary, "-ax", "sr", "-t", str(threads), target, *reads] | |
| if aligner == "bwa": | |
| return [binary, "mem", "-t", str(threads), target, *reads] | |
| raise RuntimeError(f"no command known for aligner {aligner!r}") | |
| def align_to_bam(fastqs: list[Path], reference: str = "hg38-ml", *, threads: int = 8, | |
| workdir: Path | None = None, timeout: int = 7200) -> Path: | |
| """Align a whole library to a staged reference, returning a sorted, indexed BAM. | |
| Unlike `align_reads`, this does not subsample: base-resolution questions -- an exact | |
| cut coordinate, a fusion junction -- are answered by a pile of reads agreeing on one | |
| base, and a head sample of a whole-genome library will not contain that pile. | |
| An existing BAM is reused, so an agent that asks a second question of the same reads | |
| pays the alignment once. | |
| Raises: | |
| RuntimeError: If the reference, its index, samtools or the aligner is missing, | |
| naming which; or if the aligner fails, quoting its stderr. | |
| """ | |
| fasta, _spec, aligner, binary = resolve(reference) | |
| samtools = find_binary("samtools") | |
| if samtools is None: | |
| raise RuntimeError("samtools is not installed") | |
| reads = [Path(f) for f in fastqs] | |
| for f in reads: | |
| if not f.is_file(): | |
| raise RuntimeError(f"no such reads file: {f}") | |
| work = Path(workdir or os.environ.get("VERA_WORK") or reads[0].parent / ".vera_align") | |
| work.mkdir(parents=True, exist_ok=True) | |
| stem = "_".join(f.stem for f in reads)[:80] | |
| bam = work / f"{stem}.{reference}.bam" | |
| if bam.exists() and (bam.with_suffix(".bam.bai")).exists(): | |
| return bam | |
| cmd = align_command(aligner, binary, fasta, reads, threads) | |
| sort = [samtools, "sort", "-@", "2", "-m", "1G", "-o", str(bam), "-"] | |
| with subprocess.Popen(cmd, stdout=subprocess.PIPE, | |
| stderr=subprocess.PIPE) as aln: | |
| proc = subprocess.run(sort, stdin=aln.stdout, capture_output=True, text=True, | |
| errors="replace", timeout=timeout) | |
| aln.stdout.close() | |
| err = (aln.stderr.read() or b"").decode("utf-8", "replace") | |
| aln.wait() | |
| if proc.returncode != 0 or not bam.exists() or bam.stat().st_size == 0: | |
| bam.unlink(missing_ok=True) | |
| raise RuntimeError(f"{aligner} failed: {(err or proc.stderr)[-400:]}") | |
| subprocess.run([samtools, "index", "-@", "2", str(bam)], check=True, timeout=1800) | |
| return bam | |