@biolibs/blast
v1.1.0
Published
NCBI's BLAST, verified against Biopython: qblast runs a search over HTTP with the same requests and polling rules, and parse, read and write turn its XML results, in either format, into records of hits of HSPs and back (Bio.Blast)
Maintainers
Readme
@biolibs/blast
NCBI's remote BLAST, over HTTP, sending the requests Biopython's Bio.Blast sends.
BLAST answers a question no aligner answers. An aligner is given two sequences and lines them up end to end; BLAST is given one sequence and a database of millions, and finds the patches that resemble it. A conserved domain buried in two otherwise unrelated genes is a strong BLAST hit and a terrible global alignment. It is a heuristic — short exact words are looked up and then grown — which is what makes searching GenBank take seconds, and what means a real similarity that shares no word can be missed. Every hit carries an E-value: how many hits this good you would expect by chance in a database this size.
qblast, with Biopython's parameters and defaults- The same two requests, byte for byte — the same parameter order, the same URL encoding, and
Python's own way of writing a number, so
EXPECT=10.0rather thanEXPECT=10 - The same manners — twenty seconds before the first look and a minute between the looks after it, counted from when NCBI was last spoken to, and a contact address sent with every search
- Both halves on their own —
submithands back the ticket,collectfetches once; hold the ticket and come back later rather than keeping a process waiting - One replaceable function touches the network — swap
settings.transportto route through a proxy, add caching, or test without a connection - The results read —
parseandreadturn BLAST XML, in the original format or XML2, into records of hits of HSPs, where each HSP is an alignment;writeputs them back in either format - Built on the rest —
@biolibs/entrezfor its URL encoding and the XML parserreadruns on,@biolibs/alignfor theAlignmentan HSP is, andseq,seqrecordandseqfeatureunder those
Install
npm install @biolibs/blastA search
import { qblast, settings } from "@biolibs/blast";
settings.email = "[email protected]"; // NCBI ask for this, and so does courtesy
settings.tool = "my-lab-notebook";
const found = await qblast({ program: "blastn", database: "nt", sequence: "ACGTACGT…" });
found.rid; // "FYJTMJBY016" — the ticket NCBI gave it
found.rtoe; // 30 — its estimate in seconds
found.polls; // how many times it was asked before the answer was ready
found.results; // the BLAST XMLReading the results
found.results is BLAST's XML. read turns the results for one query into a record; parse is for
several, one record each. Both take bytes, as Biopython's take a file opened in binary mode.
import { type HSP, read } from "@biolibs/blast";
const record = read(new TextEncoder().encode(found.results));
record.program; // "blastn"
record.query?.id; // "Query_1"
record.length; // how many database sequences were hit
const hit = record.get(0); // by position, or record.get("gi|…") by the target's id
hit.target.id; // "gi|16371813|ref|NP_000001.1|"
hit.target.description;
hit.length; // how many HSPs
const hsp = hit.get(0) as HSP; // an Alignment, with BLAST's numbers for it
hsp.annotations.get("evalue");
hsp.annotations.get("bit score");
hsp.coordinates; // where the stretches lie in the target and in the query
hsp.toString(); // BLAST's own summary, and the alignment under itA record is a list of hits, a hit is a list of HSPs, and an HSP is an Alignment from
@biolibs/align, so everything that package does with an alignment it does with these.
toString() on any of the three gives what Python's print gives, and repr() what its prompt shows.
import { ByteWriter } from "@biolibs/align";
import { parse, write } from "@biolibs/blast";
const records = parse(bytes); // an iterator, and a list
for (const record of records) record.query?.id;
const out = new ByteWriter();
write(parse(bytes), out, "XML2"); // or "XML"
out.toBytes();| Python | TypeScript |
|---|---|
| Blast.parse(source), Blast.read(source) | parse(bytes, name?), read(bytes, name?) |
| Blast.write(records, destination, fmt) | write(records, destination, fmt) |
| for record in records, next(records) | for (const record of records), records.next() |
| len(records), records[i], records[a:b] | records.length, records.get(i), records.getSlice(a, b) |
| with Blast.parse(...) as records: | records.close() when done |
| record[i], record["id"], record[a:b] | record.get(i), record.get("id"), record.getSlice(a, b) |
| record.keys(), "id" in record, record.index("id") | record.ids(), record.has("id"), record.index("id") |
| hit[i], hit[a:b] | hit.get(i), hit.getSlice(a, b) |
| str(x), repr(x) | x.toString(), x.repr() |
| hsp.annotations["evalue"], record.stat["db-num"], records.param["expect"] | .get("evalue") and so on: each is a Map |
Holding the ticket
A search can take minutes. submit and collect let something else wait:
import { collect, submit } from "@biolibs/blast";
const search = { program: "blastp", database: "nr", sequence: "MKVLILACLVALALAR" };
const { rid, rtoe } = await submit(search); // write these down somewhere
// … later, in another process …
const { ready, body } = await collect(search, rid);collect says whether what came back is the results or another "please wait" page. Honour NCBI's
rule either way: no more than one look a minute at a single ticket.
Building a request without sending it
import { getOf, putOf } from "@biolibs/blast";
putOf({ program: "blastn", database: "nt", sequence: "ACGT" }).body;
// "DATABASE=nt&ENTREZ_QUERY=%28none%29&EXPECT=10.0&HITLIST_SIZE=50&PROGRAM=blastn&QUERY=ACGT&CMD=Put&tool=biopython"
getOf({ program: "blastn", database: "nt", sequence: "ACGT" }, "ABC123").body;
// "ALIGNMENTS=500&DESCRIPTIONS=500&FORMAT_TYPE=XML&RID=ABC123&CMD=Get"Things to know
- A program NCBI does not take is refused here, before anything is sent, with Biopython's own
wording:
Program specified is BLASTN. Expected one of blastn, blastp, blastx, tblastn, tblastx. The five are lower case. shortQueryis dropped forblastn, whatever the sequence length, because NCBI's own handling ofSHORT_QUERY_ADJUSTis wired up wrongly for it. For a sequence under 31 bases the parameters it stood for are set by hand instead —EXPECT=1000,WORD_SIZE=7,NUCL_REWARD=1— and a warning says so, as Biopython's does.- Who is asking is sent only to NCBI. Point
urlBaseat a BLAST of your own and the address and tool name are left out, since they are NCBI's courtesy rule and nobody else's. RTOEis a whole number of seconds, and a page carrying anything else is refused.- Nothing is cached. The same search twice is two searches, and NCBI will notice.
rtoeis NCBI's guess, and it is sometimes wildly out. A search held in their queue waits there however long the queue is: estimates of 30 and 62 seconds have both gone past forty minutes on a bad afternoon, and making the query smaller does not help, because what is waited on is being let in rather than the search itself. When one is slow, ask NCBI rather than suspecting this code —curl "https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Get&FORMAT_OBJECT=SearchInfo&RID=<rid>"saysStatus=WAITINGwhile it is queued, which is an answer from them and not from here. This is the reasonsubmitandcollectare separate: hold the ticket, and let something else do the waiting.
Parity
| Upstream module | Items at parity | Checklist |
|---|---|---|
| Bio.Blast | 28 / 28 | Bio.Blast.md |
Measured, not claimed. reference/golden/gen_blast_cases.py runs the real qblast from Biopython
1.88 with urlopen, the clock and sleep replaced, and records what it would have sent. The tests
here replay the same calls — twelve searches, eight wait pages, six program names — and compare the
Put body, the Get body, the gaps between polls, the ticket read out of the page, and the words of
every error and warning.
Two things that comparison settled which reading the source had not: Python writes EXPECT=10.0 where
JavaScript would write 10, and the short-query workaround sends 1000 as an int; and RTOE
comes back as a number rather than text, with its own error for a page that carries something else.
The first draft here got the second one wrong, and the recorded cases caught it.
The results have their own generator, reference/golden/gen_blastparser_cases.py, and 1,259 recorded
cases. It makes BLAST output for all eight programs Biopython knows — blastn, megablast, blastp, blastx,
tblastn, tblastx, rpsblast, psiblast — and records what Biopython reads from each: every record, hit and
HSP with its numbers, coordinates and sequences, and the repr and str of each one.
| Cases | What they record |
|---|---|
| 78 | documents read in full: the original format, the same records as Biopython rewrites them, and XML2 with what only XML2 has |
| 117 | what is not right: not XML, legacy output, a tag the DTD lacks, numbers that are not numbers, ranges and frames that disagree, a file that stops |
| 115 | write, as XML and as XML2, compared byte for byte |
| 29 | a Records used as an iterator and as a list, in the orders that behave differently; a Record asked for hits by position, id and slice |
| 920 | good documents broken one character at a time, or cut short |
Where the claim stops:
- The documents are made, not collected. Each HSP is a random gapped alignment whose ranges, frames and counts are worked out the way BLAST works them out. No output from a real BLAST run is among the cases.
Bio.Blast.NCBIXMLis not ported. It is the older reader, with its own record classes.- Text is refused, as in Python:
parsetakes bytes, and a string raisesStreamModeError.found.resultsis a string because NCBI's reply has been decoded; encode it again, as above. - A float that is a whole number needs marking where Python prints it differently. Only one value
can be either:
eff-spacein the statistics is a number when BLAST wrote a whole number and aPyFloatwhen it wrote8.24e+10, so thatwriteputs back what Python would.
Oddities that are Biopython's and are kept:
- An exhausted
RecordsraisesAttributeErroron the nextnext(), notStopIterationa second time. - Records read from the original format cannot be written as XML2 if the file named a query for the whole
run:
XML2Writerhas no_write_query_id. Without one they are written with an<Iteration>that is never closed, except for psiblast. <Hsp_pattern-from>and<Hsp_pattern-to>, which PHI-BLAST writes, fail: the HSP cache has no slot for them.- A
bl2seq-modeparameter is read as an integer and then cannot be written.
License
MIT — see LICENSE.
