Metadata-Version: 2.4
Name: norvara-bed-lite
Version: 1.0.0rc1
Summary: Interval intersect, nearest-neighbour and summary over BED, GFF3 and GTF, from no third-party dependencies
Author-email: Norvara Therapeutics <research@norvaratx.com>
Maintainer-email: Norvara Therapeutics <research@norvaratx.com>
License-Expression: PolyForm-Noncommercial-1.0.0
Project-URL: Homepage, https://github.com/Norvara-Therapeutics/bed-lite
Project-URL: Repository, https://github.com/Norvara-Therapeutics/bed-lite.git
Project-URL: Issues, https://github.com/Norvara-Therapeutics/bed-lite/issues
Keywords: bioinformatics,genomic-intervals,bed,gff3,gtf,interval-tree,annotation
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pyflakes>=3; extra == "dev"
Requires-Dist: build>=1; extra == "dev"
Requires-Dist: tomli>=1; python_version < "3.11" and extra == "dev"
Dynamic: license-file

# bed-lite

Intersect, measure distance between and summarise genomic intervals in BED,
GFF3 and GTF files, from no third-party dependencies and no compiled
extensions. Three commands answer the three questions: what overlaps what,
what is nearest what, and what is in a file at all.

It is not a reimplementation of BEDTools. It reads the three formats in their
own coordinate conventions and reports in one, says which side of an operation
it holds in memory, and answers the question a record count hides - how much
territory a set of features actually covers once their overlaps are resolved.

## Install

```bash
pip install --pre norvara-bed-lite
```

Python 3.10 or newer. Nothing else.

## Quickstart

How much of the HBB locus do its exons actually cover? The example annotation
carries every transcript Ensembl knows about, so the 59 exon records are
12.4 kb of feature length lying on 1.7 kb of DNA.

```bash
bed-lite summary examples/hbb_locus.gff3 --feature exon
```

```
examples/hbb_locus.gff3 (GFF3, 1-based, end inclusive)
  records                     59
  sequences                   1
  bases covered               1.7 kb
  blocks once merged          7
  total feature length        12.4 kb
  redundancy                  7.11x
  overlapping another record  56 of 59
  length                      shortest 56 bp, median 223 bp, longest 537 bp
  in position order           no

  chrom  records  blocks  covered_bases    first     last  span  density  longest
  -----  -------  ------  -------------  -------  -------  ----  -------  -------
  11          59       7           1749  5225463  5229395  3932    0.445      537

  record length in bases
  0         0
  1         0
  2-4       0
  5-9       0
  10-19     0
  20-49     0
  50-99     5  ████
  100-199  19  ██████████████
  200-499  33  ████████████████████████
  500-999   2  █

  feature types
  exon  59  ████████████████████████

  note: Restricted to types exon: 59 records of 128 are in it.

  note: The records are not in position order. Every figure here is still correct; an operation that assumes sorted input is not.

  note: 56 of 59 records (95%) overlap another record in this file, so counts of records and lengths of territory are different measurements.
```

Which gene does each pathogenic variant fall in, and what is it called?
`--feature` keeps only records of the given type, in every input, which is what
makes the answer one row per variant rather than one per transcript and exon.
`--annotate` carries an attribute of the record that was hit across into a
column of the result.

```bash
bed-lite intersect examples/hbb_variants.bed examples/hbb_locus.gff3 --feature gene --annotate Name --region 11:5227001-5227002
```

```
examples/hbb_variants.bed against examples/hbb_locus.gff3
  queries                   6
  with an overlap           6 (100.0%)
  with none                 0
  overlapping pairs         6
  searched records matched  1
  query bases covered       45 bp of 45 bp (100.0%)

  chrom    start      end  name          strand  subject_chrom  subject_start  subject_end  subject_name          subject_strand  subject_type  overlap_bases  share_of_query  share_of_subject  Name
  -----  -------  -------  ------------  ------  -------------  -------------  -----------  --------------------  --------------  ------------  -------------  --------------  ----------------  ----
  11     5226976  5227002  VCV000869233  .       11                   5225463      5229395  gene:ENSG00000244734  -               gene                     26               1             0.007  HBB
  11     5226989  5227002  VCV000869232  .       11                   5225463      5229395  gene:ENSG00000244734  -               gene                     13               1             0.003  HBB
  11     5227000  5227002  VCV003766686  .       11                   5225463      5229395  gene:ENSG00000244734  -               gene                      2               1             0.001  HBB
  11     5227001  5227002  VCV000015333  .       11                   5225463      5229395  gene:ENSG00000244734  -               gene                      1               1             0.000  HBB
  11     5227001  5227002  VCV000015418  .       11                   5225463      5229395  gene:ENSG00000244734  -               gene                      1               1             0.000  HBB
  11     5227001  5227003  VCV000036301  .       11                   5225463      5229395  gene:ENSG00000244734  -               gene                      2               1             0.001  HBB

  note: Only the records of the first input in 11:5227001-5227002 were asked about. The searched file was not restricted, so a record reported here may lie outside that region.

  note: Only records of type gene were used. A record with no type column, as in BED, was kept either way.
```

Where is the nearest exon to the variants at the start of the region, not
counting the one a variant is already inside? The window chooses which
variants to ask about; the exon that answers lies outside it.

```bash
bed-lite nearest examples/hbb_variants.bed examples/hbb_locus.gff3 --feature exon --ignore-overlapping --region 11:5225480-5225484
```

```
examples/hbb_variants.bed beside examples/hbb_locus.gff3
  queries                  3
  with a neighbour         3
  with none                0
  touching or overlapping  0
  median distance          171 bp
  nearest is upstream      0
  nearest is downstream    3
  with a tie for nearest   0

  chrom    start      end  name          strand  subject_chrom  subject_start  subject_end  subject_name     subject_strand  subject_type  distance  side
  -----  -------  -------  ------------  ------  -------------  -------------  -----------  ---------------  --------------  ------------  --------  ----------
  11     5225481  5225482  VCV000015474  .       11                   5225654      5225726  ENSE00001866802  -               exon               172  downstream
  11     5225481  5225483  VCV000869259  .       11                   5225654      5225726  ENSE00001866802  -               exon               171  downstream
  11     5225483  5225488  VCV000015506  .       11                   5225654      5225726  ENSE00001866802  -               exon               166  downstream

  note: Only the records of the first input in 11:5225480-5225484 were asked about. The searched file was not restricted, so a record reported here may lie outside that region.

  note: Only records of type exon were used. A record with no type column, as in BED, was kept either way.

  note: Distances are signed by coordinate - negative towards the start of the sequence - while the side is read from the query's strand, so the two disagree for a query on the minus strand.
```

When two files name their sequences differently - one `11` and the other
`chr11`, as Ensembl and the UCSC browser do - every query misses, and an empty
result looks like a finding. That case is checked for and named.

```bash
bed-lite intersect examples/hbb_variants.bed examples/hbb_transcripts.bed --mode count --region 11:5227001-5227002
```

```
examples/hbb_variants.bed against examples/hbb_transcripts.bed
  queries                   6
  with an overlap           0 (0.0%)
  with none                 6
  overlapping pairs         0
  searched records matched  0
  query bases covered       0 bp of 45 bp (0.0%)

  chrom    start      end  name          strand  overlaps  covered_bases  covered_share
  -----  -------  -------  ------------  ------  --------  -------------  -------------
  11     5226976  5227002  VCV000869233  .              0              0
  11     5226989  5227002  VCV000869232  .              0              0
  11     5227000  5227002  VCV003766686  .              0              0
  11     5227001  5227002  VCV000015333  .              0              0
  11     5227001  5227002  VCV000015418  .              0              0
  11     5227001  5227003  VCV000036301  .              0              0

  note: Only the records of the first input in 11:5227001-5227002 were asked about. The searched file was not restricted, so a record reported here may lie outside that region.

  note: examples/hbb_variants.bed and examples/hbb_transcripts.bed name no sequence in common (11 against chr11), so nothing could have been found. One file is probably using UCSC names and the other Ensembl names.
```

## The commands

| Command | What it answers |
| --- | --- |
| `intersect` | which records of one file overlap another, and by how much |
| `nearest` | which records of another file are nearest each record, and on which side |
| `summary` | what is in one file: coverage, lengths, overlaps, gaps |

`intersect` and `nearest` take two files. The second is loaded and indexed; the
first is streamed past it, so the first may be any size. `summary` takes one
file and loads it, since what is measured about a file depends on all of it.
Any input may be `-` for standard input, and a gzipped file is read as one
whatever it is called.

Sorting, merging and restricting to a region are options rather than commands,
available to all three, because they are things to do to an input rather than
questions to ask of it. Merging a file and writing it back out is therefore:

```bash
bed-lite summary genes.gff3 --merge --intervals merged.bed --interval-format bed -f none
```

Because `--feature` applies to every input, filtering the two sides of an
intersection differently is a pipe as well; so is merging the file an
intersection searches:

```bash
bed-lite summary genes.gff3 --feature gene --intervals - -f none \
  | bed-lite intersect exons.gff3 - --feature exon --mode count
```

## Options

Shared by all three commands:

| Option | Effect |
| --- | --- |
| `--input-format` | name the format instead of working it out from the first record |
| `--feature TYPE[,TYPE]` | keep only records of these GFF types, in every input; a record with no type column, as in BED, is kept either way |
| `--region CHROM:START-END` | ask only about the first input's records in this region, counting from 1 |
| `--merge`, `--merge-distance`, `--merge-strand` | merge the first input before anything else |
| `--sort` | write records in position order rather than file order |
| `-f`, `--format` | what goes to standard output: `table`, `tsv`, `json` or `none` |
| `-o`, `--output` | the rows, as a TSV |
| `--intervals`, `--interval-format` | the records themselves, as BED, GFF3 or GTF |
| `--report` | a self-contained HTML report |

`intersect` adds `--mode` (`pairs`, `unique`, `absent` or `count`), `--strand`,
`--fraction`, `--subject-fraction`, `--reciprocal` and `--annotate`.
`nearest` adds `-k`/`--count`, `--strand`, `--ignore-overlapping`,
`--maximum-distance` and `--annotate`.

`--fraction` and `--subject-fraction` are different questions. The first is the
least share of the query an overlap must cover, which is what to ask when the
query is small and the annotation large; the second is the reverse, as when
asking which exons a large deletion removes. `--reciprocal` requires
`--fraction` of both, which is how to ask whether two features are the same
feature.

## Reading the output

`--mode absent` with `--intervals` is how the command is used as a filter: it
writes the query records that overlapped nothing, in whichever format is asked
for.

The HTML report embeds its own style and charts, loads nothing from the network
and runs no script, so it opens the same from a disk, an attachment or an
archive. Each table in it downloads as the tab-separated file `--output` would
have written, carried as a data URI; both come from the same serialiser, and a
test asserts they are identical byte for byte. The same input produces the same
document, byte for byte, so reports can be compared between runs.

Figures printed for a person are rounded; the files are not. A share that is
not zero but rounds to zero prints as `<0.1%` rather than `0.0%`, because
nothing found and almost nothing found say opposite things.

## Coordinate conventions

BED counts from 0 with an exclusive end. GFF3 and GTF count from 1 with an
inclusive end. Both are read in their own convention, converted once, and
reported in BED's: `chr1 100 150` is 50 bases, and an interval beginning at 150
does not overlap it. A region given with `--region` counts from 1 and includes
both ends, as a genome browser does, because that is how a person types one.

Two consequences are worth knowing before reading any result:

1. Intervals that touch do not overlap, but nothing lies between them. `--merge`
   joins them and `intersect` does not report them; `nearest` calls them zero
   apart.
2. A zero-length interval, which BED permits for marking a position between two
   bases, overlaps nothing at all - not even an interval containing its
   position. It is counted separately rather than silently dropped or silently
   matched.

Every table written is 0-based and half-open whatever the input format was,
which is what makes tables built from a BED file and from a GFF3 file safe to
join against each other.

## What it does not do

It has no genome file, so it does not know where a sequence ends: there is no
complement operation and no gap reported before the first record or after the
last. It does not compute coverage depth per base, cluster, shuffle, or sample
randomly. It holds the searched file in memory, so crossing two whole-genome
annotations is not what it is for; `--merge`, `--sort` and `--report` each load
what they work on as well, while `--output` and `--intervals` are written as
the results stream past. It does not index with tabix or read BAM, bigBed or
VCF.

## Development

```bash
pip install -e ".[dev]"
python -m pytest
python -m pyflakes src/bed_lite tests scripts examples
python scripts/check_wheel.py
```

`examples/fetch_examples.py` rebuilds the example files from Ensembl and the
UCSC genome browser; `--check` verifies the committed ones against their
recorded checksums. The GTF example is derived from the GFF3, since Ensembl's
REST service does not serve GTF, and the script says how.

## License

PolyForm Noncommercial License 1.0.0. Free for noncommercial use; commercial
use requires a separate licence from Norvara Therapeutics.
