thoraxe.bulk_ensembl package
Submodules
thoraxe.bulk_ensembl.biomart module
biomart: download one exon table per species from the BioMart of a release.
transcript_query asks BioMart for the exon table of each gene. Here the same query (same 14 attributes, same dataset) is sent once per species without the gene filter, to the BioMart of the requested release:
the archive site of the release (
ARCHIVE_HOSTS) or--biomart-host;a host is used only if its mart registry advertises “Ensembl Genes <R>”, so that a dump never silently comes from another release;
the answer must end with BioMart’s completion stamp
[success], so that a truncated answer is never stored.
- thoraxe.bulk_ensembl.biomart.ARCHIVE_HOSTS = {112: 'https://may2024.archive.ensembl.org', 113: 'https://oct2024.archive.ensembl.org', 114: 'https://may2025.archive.ensembl.org', 115: 'https://sep2025.archive.ensembl.org', 116: 'https://jun2026.archive.ensembl.org'}
Archive site of each Ensembl release (https only).
- thoraxe.bulk_ensembl.biomart.ATTRIBUTES = ['ensembl_gene_id', 'ensembl_transcript_id', 'ensembl_peptide_id', 'strand', 'ensembl_exon_id', 'exon_chrom_start', 'exon_chrom_end', 'rank', 'cdna_coding_start', 'cdna_coding_end', 'genomic_coding_start', 'genomic_coding_end', 'phase', 'end_phase']
The BioMart attributes of transcript_query, in its order.
- thoraxe.bulk_ensembl.biomart.HEADERS = {'User-Agent': 'thoraxe-ensembl-bulk'}
Some mirrors refuse the default python-requests User-Agent.
- thoraxe.bulk_ensembl.biomart.biomart_host(release, host=None)
Return a BioMart host serving release (host if given, else the archive).
Raise ValueError if the host serves another release.
- thoraxe.bulk_ensembl.biomart.dataset_for_species(species)
BioMart gene dataset of species, as transcript_query names it.
- thoraxe.bulk_ensembl.biomart.download_species(host, species, raw_path, no_dataset_path, datasets=None)
Download the exon table of species into raw_path (gzipped TSV).
If the mart has no dataset for species, write no_dataset_path instead (transcript_query records such genes in errors.csv). Existing outputs are kept.
- thoraxe.bulk_ensembl.biomart.gene_datasets(host)
Names of the gene datasets of the Ensembl mart of host.
- thoraxe.bulk_ensembl.biomart.served_release(host)
Ensembl release advertised by the mart registry of host (None if none).
- thoraxe.bulk_ensembl.biomart.xml_query(dataset, header=True)
Return the BioMart XML query of transcript_query, without gene filter.
The completion stamp makes BioMart end a complete answer with [success].
thoraxe.bulk_ensembl.cli module
cli: the ensembl_bulk program (download and index the bulk files).
- thoraxe.bulk_ensembl.cli.main(argv=None)
Main function of ensembl_bulk.
- thoraxe.bulk_ensembl.cli.parse_command_line()
Parse command line.
It uses argparse to parse ensembl_bulk’s command line arguments and returns the argparse parser.
thoraxe.bulk_ensembl.compara module
compara: gene trees and orthologs from the Ensembl Compara bulk files.
transcript_query asks, per gene,
tree.nh: REST/genetree/member/id/<species>/<gene>?nh_format=full;the orthologs: REST
/homology/id/<species>/<gene>.
Here both come from the protein_default collection of Compara:
Compara.<R>.protein_default.nh.emf.gz: every gene tree (Newick) and its members, indexed intrees.sqlite;Compara.<R>.protein_default.homologies.tsv.gz: the homology pairs of one species, indexed inhomologies.sqlitefor the query species.
The homology file of a species does not hold all of its pairs: in release 115, the human file lacks every pair whose other gene belongs to cricetulus_griseus_picr, equus_caballus, mus_musculus, ovis_aries or sus_scrofa. Those pairs are only in the files of these species, with the human gene as homology partner. The index therefore reads the query species file and, in reverse, the files of the other downloaded species. missing_homology_species finds the species whose file is needed for a complete index.
A tree from the EMF dump has the same leaves, labels and branch lengths as the REST tree; the order of sibling subtrees can differ, as it does between two REST calls.
- thoraxe.bulk_ensembl.compara.DEFAULT_HOMOLOGY_SPECIES = {'homo_sapiens': ['cricetulus_griseus_picr', 'equus_caballus', 'mus_musculus', 'ovis_aries', 'sus_scrofa']}
Species whose homology file carries human pairs absent from the human file (Ensembl release 115, see the module documentation).
- thoraxe.bulk_ensembl.compara.build_homology_index(query_species, query_tsv, other_tsvs, db_path)
Index the homologies of query_species into db_path.
Rows of query_tsv are read forward (gene_stable_id is the query gene). Rows of the other files are kept only when homology_species is query_species, and stored with the homology partner as query gene. Table: homology(gene_id, species, type, target_gene_id, target_species).
- thoraxe.bulk_ensembl.compara.build_tree_index(emf_path, db_path)
Index the EMF Newick dump into db_path.
Tables: members(gene_id, species, peptide_id, gene_name, tree_id) and trees(tree_id, newick).
- thoraxe.bulk_ensembl.compara.homologies(homologies_db, gene_id)
Return the homologies of gene_id as REST /homology/id returns them.
Each element is a dict with ‘type’, ‘source’ and ‘target’ (‘species’ and ‘id’), the fields that transcript_query uses. Index order.
- thoraxe.bulk_ensembl.compara.index_query_species(homologies_db)
Return the query species the homology index was built for.
- thoraxe.bulk_ensembl.compara.missing_homology_species(trees_db, homologies_db, query_species)
Return the species that share a gene tree with a query_species gene but have no homology with it in the index (their homology file is needed).
- thoraxe.bulk_ensembl.compara.ortholog_species(query_species, query_tsv, other_tsvs)
Return the species with an ortholog of a query_species gene.
These are the species that transcript_query can query without --specieslist: any orthology type, at least two name parts, no hybrid cattle. The homology files are read as in build_homology_index.
- thoraxe.bulk_ensembl.compara.tree_newick(trees_db, gene_id)
Return the Newick text of the gene tree containing gene_id (None if none).
thoraxe.bulk_ensembl.download module
download: fetch the bulk files of one Ensembl release.
From the FTP site (https://ftp.ensembl.org/pub/release-<R>/), each file is
checked against the CHECKSUMS file of its directory (BSD sum, as Ensembl
publishes it):
Compara: the protein_default gene trees (EMF) and the homology TSV of the query species and of the --homology-species;
for each species: the complete GTF, the unmasked toplevel genome and the core database tables that tsl.csv needs. By default, the species are the query species and every species with an ortholog of it in the Compara homology files (199 species for homo_sapiens in Ensembl 115, about 120 GB).
From BioMart: one exon table per species (see biomart).
Existing files that match their checksum are kept, so an interrupted download can be resumed by running the same command again.
- class thoraxe.bulk_ensembl.download.FtpPlan(bulk)
The FTP files of a bulk folder: (url, destination, expected checksum).
- add(folder, name, dest)
Add folder/name, saved as dest, with its CHECKSUMS next to it.
- add_compara(species_list)
Compara gene trees and the homology TSV of each species.
- add_species(species, core_dirs)
GTF, genome and core database tables of species.
- checksums(folder)
CHECKSUMS of an FTP folder (relative to the release), kept locally too.
- core_dirs()
Core database dump folder of each species of the release.
- run(workers=4)
Download every planned file; return {status: count}.
- thoraxe.bulk_ensembl.download.bsd_sum(path)
BSD sum(1) of path: 16-bit rotating checksum and size in 1 KiB blocks.
- thoraxe.bulk_ensembl.download.download(bulk, species_list, homology_species, biomart_host=None, workers=4)
Download the bulk files of species_list into the bulk folder.
species_list None means every species with an ortholog of the query species in Compara, the species transcript_query uses without --specieslist; the query species is always added. homology_species are the species whose Compara homology TSV is read in reverse (see compara).
- thoraxe.bulk_ensembl.download.fetch(url, dest, expected)
Download url into dest unless dest already has the expected checksum.
Return ‘kept’ or ‘downloaded’. Raise if the download does not match.
- thoraxe.bulk_ensembl.download.list_dir(url)
Return the names listed in an FTP folder (HTML index) at url.
- thoraxe.bulk_ensembl.download.parse_checksums(text)
Return {file name: (checksum, blocks)} from a CHECKSUMS file.
>>> parse_checksums('45573 45635 a.gz') {'a.gz': (45573, 45635)}
- thoraxe.bulk_ensembl.download.read_text(url)
Return the text at url.
- thoraxe.bulk_ensembl.download.release_url(release)
Root of the FTP folder of an Ensembl release.
thoraxe.bulk_ensembl.exons module
exons: exonstable.tsv from the BioMart dump of each species.
The dump of a species (biomart.download_species) holds the answer that
transcript_query would get for each of its genes, one after the other. It is
indexed by gene (first column) in <species>.sqlite, keeping the dump order,
so that exon_table returns the text transcript_query writes for a gene.
- thoraxe.bulk_ensembl.exons.build_index(raw_path, db_path)
Index the BioMart dump raw_path into db_path.
Tables: exons(c0..c13, the dump columns, rowid = dump order) and meta(key, value) with the dump header.
- thoraxe.bulk_ensembl.exons.exon_table(db_path, gene_id, header=True)
Return the BioMart answer for gene_id (None if the gene has no rows).
The header line is included if header is True. The caller applies transcript_query’s column renaming.
thoraxe.bulk_ensembl.index module
index: build the indexes that transcript_query --bulk-dir reads.
Each index is written to a temporary file and renamed when complete, and existing indexes are kept: running the command again resumes an interrupted run. Delete an index to rebuild it.
- thoraxe.bulk_ensembl.index.index(bulk, species_list=None, workers=1)
Build every index of the bulk folder.
species_list defaults to the species of bulk_info.json. workers species are indexed in parallel (each one needs a few GB of memory).
- thoraxe.bulk_ensembl.index.index_compara(bulk)
Build the gene tree and homology indexes of the bulk folder.
The homology index is rebuilt when the downloaded homology files change. Raise if a species that shares gene trees with the query species has no homology in the index (its homology file has to be downloaded).
- thoraxe.bulk_ensembl.index.index_species(bulk, species)
Build the tsl tables, exon table, genome and GTF indexes of species.
thoraxe.bulk_ensembl.layout module
layout: where each bulk file and index lives inside a bulk folder.
<bulk>/bulk_info.json release, query species and species list
<bulk>/compara/emf/Compara.<R>.protein_default.nh.emf.gz
<bulk>/compara/tsv/<species>/Compara.<R>.protein_default.homologies.tsv.gz
<bulk>/compara/index/trees.sqlite gene trees and their members
<bulk>/compara/index/homologies.sqlite homologies of the query species
<bulk>/mysql/<species>_core_<R>_<N>/ core database dump (some tables)
<bulk>/tables/<species>/ transcripts.tsv, genes.tsv (tsl.csv)
<bulk>/exons/raw/<species>.tsv.gz BioMart dump of the species dataset
<bulk>/exons/<species>.sqlite the dump indexed by gene
<bulk>/gtf/<species>/<Species>.<assembly>.<R>.gtf.gz
<bulk>/genome/<species>/<Species>.<assembly>.dna.toplevel.fa.gz
<bulk>/genome_fa/<species>/ decompressed genome + .fai index
<bulk>/index/<species>.exons.sqlite GTF genes and exons
<R> is the Ensembl release. Species built by Ensembl Genomes (from release
116: caenorhabditis_elegans, drosophila_melanogaster, saccharomyces_cerevisiae)
also carry its release number <EG>: <species>_core_<EG>_<R>_<N> and
<Species>.<assembly>.<EG>.gtf.gz.
- class thoraxe.bulk_ensembl.layout.BulkDir(root, release=None, query_species=None)
Paths of one bulk folder (see the module documentation).
- compara_emf()
Compara gene trees (Newick EMF dump).
- compara_tsv(species)
Compara homologies of one species.
- compara_tsv_species()
Species with a downloaded Compara homology file.
- core_dir(species)
Core database dump folder of species.
- exons_db(species)
SQLite index of the BioMart dump of species.
- exons_no_dataset(species)
Marker written when BioMart has no gene dataset for species.
- exons_raw(species)
BioMart dump of species.
- genome_fa(species)
Decompressed genome of species (indexed with a .fai file).
- genome_gz(species)
Unmasked toplevel genome of species.
- gtf_db(species)
SQLite index of the GTF genes and exons of species.
- gtf_gz(species)
Complete GTF of species.
- homologies_db()
SQLite index of the homologies of the query species.
- property info_path
Path of bulk_info.json.
- missing_indexes(species)
Return the indexes of species that are not built yet (empty if ready).
A BioMart species without gene dataset counts as ready: its genes get recorded in errors.csv, as transcript_query does.
- mysql_dir()
Folder with the core database dumps.
- read_info()
Return the content of bulk_info.json ({} if it does not exist).
- ready_species()
Species of the bulk folder whose indexes are all built.
- trees_db()
SQLite index of the gene trees.
- tsl_tables_dir(species)
Transcript and gene tables of species, written by tsl.build_tables.
- write_info(**values)
Update bulk_info.json with values.
- thoraxe.bulk_ensembl.layout.EG_VERSION_OFFSET = 53
Ensembl Genomes numbering of an Ensembl release, as REST /info/eg_version returns it (release 115 is EG 62).
- thoraxe.bulk_ensembl.layout.eg_version(release)
Return the Ensembl Genomes version that transcript_query records.
>>> eg_version(115) 62
thoraxe.bulk_ensembl.query module
query: transcript_query --bulk-dir, the <gene>/Ensembl/ folder from bulk files.
run follows transcript_query’s main step by step and writes the same files with the same writers; only the data source changes. The functions of transcript_query that filter orthologs, rename the exon table columns and write tsl.csv, sequences.fasta and errors.csv are reused as they are.
- thoraxe.bulk_ensembl.query.QUERY_EXONS_LABEL = '{args.species}:{args.genename}'
transcript_query labels the records of the queried gene with this literal text (it is not formatted); kept so that both modes write the same file.
- thoraxe.bulk_ensembl.query.get_orthologs(bulk, gene_id)
Bulk version of transcript_query.get_orthologs.
- thoraxe.bulk_ensembl.query.resolve_gene(bulk, species, genename, verbose=False)
Return the Ensembl gene id of genename (a gene name or an Ensembl id).
- thoraxe.bulk_ensembl.query.run(args)
Write <genename>/Ensembl/ from the bulk folder args.bulk_dir.
args are transcript_query’s parsed arguments.
- thoraxe.bulk_ensembl.query.write_ensembl_version(folder, release)
Write ensembl_version.csv as transcript_query.save_ensembl_version does.
thoraxe.bulk_ensembl.sequences module
sequences: sequences.fasta from the genome FASTA and the GTF of each species.
transcript_query writes one record per exon returned by REST
/overlap/id/<gene>?feature=exon (every exon, of any gene and biotype, that
overlaps the gene), with the sequence from REST /sequence/id and the
description <coord_system>:<assembly>:<seq_region>:<start>:<end>:<strand>.
Here the exons and the gene spans come from the GTF (indexed in SQLite) and the
sequences from the unmasked toplevel genome, decompressed once and indexed with
a samtools-compatible .fai file. The sequence of an exon is the genomic
slice of its span, reverse complemented on the minus strand (whole exon,
UTRs included). The coordinate system and assembly of each sequence region come
from the genome FASTA headers.
Bulk files hold every exon, whereas REST /sequence/id silently skips some
exon ids (e.g. of some lncRNA genes overlapping the queried gene). The extra
records do not change thoraxe’s results: thoraxe only reads the exons listed in
exonstable.tsv.
- class thoraxe.bulk_ensembl.sequences.Genome(fa_path)
Random access to an indexed genome FASTA.
- close()
Close the FASTA file.
- fetch(name, start, end)
Return the forward strand sequence of name:start-end (1-based, inclusive).
- class thoraxe.bulk_ensembl.sequences.SpeciesSequences(fa_path, gtf_db)
Genome and GTF index of one species, opened once for many genes.
- close()
Close the genome and the GTF index.
- exon_records(gene_id, label)
Return the sequences.fasta records of gene_id.
Each record is a dict with ‘id’, ‘desc’ and ‘seq’ (the fields of the REST answer that transcript_query writes) and ‘label’. Raise KeyError if the gene is not in the GTF.
- thoraxe.bulk_ensembl.sequences.build_fai(fa_path)
Index fa_path: write <fa>.regions and <fa>.fai.
.fai(name, length, offset, line bases, line width) is the samtools index..regionskeepscoord_system:assemblyof each sequence, from the third word of its FASTA header..faiis written last: it marks the genome as indexed.
- thoraxe.bulk_ensembl.sequences.build_gtf_index(gtf_path, db_path)
Index the genes and exons of a GTF file into db_path.
Tables: gene(gene_id, seq, start, end, strand, biotype, name) and exon(exon_id, seq, start, end, strand), one row per exon id.
- thoraxe.bulk_ensembl.sequences.decompress(gz_path, fa_path)
Decompress gz_path into fa_path.
- thoraxe.bulk_ensembl.sequences.genes_named(db_path, name)
Return the ids of the genes called name in the GTF (case-insensitive).
- thoraxe.bulk_ensembl.sequences.reverse_complement(sequence)
Return the reverse complement of a DNA sequence.
>>> reverse_complement('AACGTN') 'NACGTT'
thoraxe.bulk_ensembl.tsl module
tsl: the rows of tsl.csv from the core database dump.
transcript_query writes, for every queried gene, one tsl.csv row per transcript
returned by REST /overlap/id/<gene>?feature=transcript: every current
transcript of any gene (any biotype) that overlaps the gene on the same
sequence region. The eight columns come from these REST fields:
column |
REST field |
core database |
|---|---|---|
Species |
(queried species) |
|
Name |
external_name |
xref.display_label |
TranscriptID |
id |
transcript.stable_id |
Source |
source |
transcript.source |
ExperimentSource |
logic_name |
analysis.logic_name |
Biotype |
biotype |
transcript.biotype |
Flags |
transcript_support_level |
transcript_attrib (code TSL) |
Version |
version |
transcript.version |
The core database dump is the only bulk file with all eight (the GTF has no logic_name). Missing values are written as NA. The TSL value loses its “tsl” prefix (“tsl1 (assigned to previous version 8)” becomes “1 (assigned to previous version 8)”), as in REST. Rows are sorted by the internal transcript_id, the order of the REST answer.
- class thoraxe.bulk_ensembl.tsl.SpeciesTables(tables_dir)
The tables of one species, loaded for overlap queries.
- rows(species, gene_id)
Return the tsl.csv rows of gene_id as dicts (REST field names).
Every current transcript overlapping the gene on its sequence region, in internal transcript_id order. Empty if gene_id is not a current gene.
- class thoraxe.bulk_ensembl.tsl.TablesCache(bulk, size=2)
Keep the tables of the last size species in memory.
The query species and one ortholog species at a time is enough: the orthologs of a gene are queried species by species.
- get(species)
Return the SpeciesTables of species.
- rows(species, gene_id)
Return the tsl.csv rows of gene_id in species.
- thoraxe.bulk_ensembl.tsl.build_tables(core_dir, out_dir)
Write genes.tsv and transcripts.tsv of one species into out_dir.
genes.tsv: gene_stable_id, seq_region_id, start, end (current genes). transcripts.tsv: TRANSCRIPT_COLUMNS (current transcripts), where db_id is the internal transcript_id.
Module contents
bulk_ensembl: build transcript_query’s input folders from Ensembl bulk files.
transcript_query asks the Ensembl REST API and BioMart, gene by gene, for the
files that thoraxe reads from <gene>/Ensembl/. This subpackage builds the
same files from the release-wide files that Ensembl publishes on its FTP site
and from one BioMart dump per species, downloaded once:
file |
online source (transcript_query) |
bulk source |
|---|---|---|
tree.nh |
REST /genetree/member/id |
Compara EMF dump |
orthologs |
REST /homology/id |
Compara homology TSV |
tsl.csv |
REST /overlap/id?feature=transcript |
core MySQL dump |
exonstable.tsv |
BioMart, one query per gene |
BioMart, one query per species |
sequences.fasta |
REST /overlap/id?feature=exon and /sequence/id |
genome FASTA + GTF |
ensembl_version.csv |
REST /info/eg_version |
release number |
The bulk folder is prepared once with ensembl_bulk download and
ensembl_bulk index, then transcript_query --bulk-dir <folder> reads it.
Every query is then local, so the inputs of a run do not depend on the state of
the Ensembl servers at download time, and they always come from one release.