@biolibs/uniprot 0.0.0-stage → 0.1.0

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.
package/src/protein.ts ADDED
@@ -0,0 +1,258 @@
1
+ /**
2
+ * What UniProt knows about a protein, read into positions people count.
3
+ *
4
+ * `@biolibs/seqio` already reads UniProt's XML, faithfully, into Biopython's shapes: a `SeqRecord`
5
+ * with features whose locations are half-open and counted from zero. That is the right thing for a
6
+ * port to do and the wrong thing to hand a lab, so this turns it into the few facts somebody at a
7
+ * bench actually asks for, counted the way the rest of these packages count.
8
+ *
9
+ * The one that matters most is the **chain**. A UniProt entry's sequence is usually the precursor —
10
+ * the protein as it comes off the ribosome, signal peptide and all — and the thing a lab collects
11
+ * is the chain that is left after the cell has cut that off. They are different lengths and so
12
+ * different masses on a gel, and a tool that quietly used the precursor would send somebody looking
13
+ * for a band two kilodaltons too high. So the mature chain is worked out, given as its own
14
+ * sequence, and said to be what it is.
15
+ *
16
+ * The second is **what is modified**. For a protein like casein the phosphoserines are the whole
17
+ * point: they are what lets it build a micelle, and a host that does not put them on makes a
18
+ * protein that is the right mass and the wrong thing. UniProt records them one residue at a time,
19
+ * with evidence, and that is worth far more than anything a sequence alone can be asked.
20
+ */
21
+ import { UniprotIterator } from "@biolibs/seqio";
22
+ import { UniProtError } from "./ask.js";
23
+
24
+ /** A stretch of a protein, counted as people count: from 1, both ends included. */
25
+ export interface Stretch {
26
+ /** The first residue, counting from 1. */
27
+ from: number;
28
+ /** The last residue. */
29
+ to: number;
30
+ }
31
+
32
+ /** The mature protein: what is left once the cell has cut off what it cuts off. */
33
+ export interface Chain extends Stretch {
34
+ /** What UniProt calls it. */
35
+ name: string;
36
+ /** Its own sequence. */
37
+ sequence: string;
38
+ /** How many residues. */
39
+ length: number;
40
+ }
41
+
42
+ /** One residue that carries something after it is made. */
43
+ export interface Modified {
44
+ /** Where it is, counting from 1 on the whole entry's sequence. */
45
+ at: number;
46
+ /** The residue itself, as a letter. */
47
+ residue: string;
48
+ /** What is on it: `Phosphoserine`, `N-linked (GlcNAc) asparagine`, and so on. */
49
+ what: string;
50
+ /** Whether UniProt cites evidence for it. */
51
+ evidenced: boolean;
52
+ }
53
+
54
+ /** One place the protein is known to differ between individuals or breeds. */
55
+ export interface Variant extends Stretch {
56
+ /** What is usually there, and what it becomes. */
57
+ was: string;
58
+ /** What it becomes, or `""` where the residues are simply gone. */
59
+ now: string;
60
+ /** What UniProt says about it, which usually names the variant. */
61
+ note: string;
62
+ }
63
+
64
+ /** A named part of a protein: a domain, a region, a repeat. */
65
+ export interface Region extends Stretch {
66
+ /** What kind of thing it is, as UniProt types it. */
67
+ kind: string;
68
+ /** What it is called. */
69
+ name: string;
70
+ }
71
+
72
+ /** What is known about one protein. */
73
+ export interface Protein {
74
+ /** Its accession, which is what to cite it by. */
75
+ accession: string;
76
+ /** Every accession that leads here, since entries get merged. */
77
+ alsoKnownAs: string[];
78
+ /** The entry's name, such as `CASB_BOVIN`. */
79
+ entryName: string;
80
+ /** What the protein is called. */
81
+ name: string;
82
+ /** The gene it comes from, where the entry names one. */
83
+ gene: string | null;
84
+ /** What it is from, and where that sits. */
85
+ organism: string | null;
86
+ lineage: string[];
87
+ /**
88
+ * Whether a curator has been over this entry (Swiss-Prot) or it was made by machine (TrEMBL).
89
+ *
90
+ * It is the first thing to look at. A reviewed entry's modified residues have been read out of
91
+ * papers by somebody; an unreviewed entry's have been guessed from similarity, and saying they
92
+ * are the same thing would be a lie by omission.
93
+ */
94
+ reviewed: boolean;
95
+ /** The whole entry's sequence, which is usually the precursor. */
96
+ sequence: string;
97
+ length: number;
98
+ /** What UniProt says the whole entry weighs, in daltons. */
99
+ mass: number | null;
100
+ /** The signal peptide, if the entry marks one. */
101
+ signal: Stretch | null;
102
+ /** The mature chain, if the entry marks one: what a lab actually ends up holding. */
103
+ chain: Chain | null;
104
+ /** Each residue that carries something after it is made. */
105
+ modifications: Modified[];
106
+ /** Where it is known to differ between individuals or breeds. */
107
+ variants: Variant[];
108
+ /** Its named parts. */
109
+ regions: Region[];
110
+ /** The words UniProt files it under. */
111
+ keywords: string[];
112
+ /** Where a person would read it. */
113
+ lookAt: string;
114
+ }
115
+
116
+ /** What `@biolibs/seqio` gives back, in as much shape as is read here. */
117
+ interface Parsed {
118
+ id: string;
119
+ name: string;
120
+ description: string;
121
+ seq: { toString(): string };
122
+ annotations: Map<string, unknown>;
123
+ features: { type: string; location: { start: unknown; end: unknown }; qualifiers: Map<string, unknown> }[];
124
+ }
125
+
126
+ const words = (value: unknown): string | null => (typeof value === "string" && value.trim() !== "" ? value.trim() : null);
127
+ const list = (value: unknown): string[] => (Array.isArray(value) ? value.filter((one): one is string => typeof one === "string") : []);
128
+
129
+ /** A position out of a Biopython location, or `null` where it is not an exact number. */
130
+ const exact = (value: unknown): number | null => {
131
+ const at = Number(value);
132
+ return Number.isSafeInteger(at) ? at : null;
133
+ };
134
+
135
+ /** A feature's stretch, turned from half-open and counted from zero into how people count. */
136
+ function stretchOf(feature: Parsed["features"][number]): Stretch | null {
137
+ const [start, end] = [exact(feature.location.start), exact(feature.location.end)];
138
+ if (start === null || end === null || end <= start) return null;
139
+ return { from: start + 1, to: end };
140
+ }
141
+
142
+ const said = (feature: Parsed["features"][number], field: string): string => words(feature.qualifiers.get(field)) ?? "";
143
+
144
+ /**
145
+ * Read a protein out of a UniProt XML entry.
146
+ *
147
+ * @param xml - The entry, as UniProt sends it.
148
+ * @returns What is known about it.
149
+ * @throws {@link UniProtError} if that is not a UniProt entry.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * import { lookUpProtein, readProtein } from "@biolibs/uniprot";
154
+ *
155
+ * const casein = readProtein(await lookUpProtein("P02666"));
156
+ * casein.chain?.length; // 209, not the precursor's 224
157
+ * casein.modifications.map((one) => one.at); // [30, 32, 33, 34, 50]
158
+ * ```
159
+ */
160
+ export function readProtein(xml: Uint8Array | string): Protein {
161
+ const bytes = typeof xml === "string" ? new TextEncoder().encode(xml) : xml;
162
+ let record: Parsed;
163
+ try {
164
+ const [first] = [...new UniprotIterator(bytes)] as unknown as Parsed[];
165
+ if (first === undefined) throw new Error("the entry is empty");
166
+ record = first;
167
+ } catch (cause) {
168
+ throw new UniProtError(`That is not a UniProt entry: ${cause instanceof Error ? cause.message : String(cause)}`, "uniprotkb");
169
+ }
170
+ const sequence = String(record.seq).toUpperCase();
171
+ const accession = list(record.annotations.get("accessions"))[0] ?? record.id;
172
+
173
+ const signal = record.features.filter((one) => one.type === "signal peptide").map(stretchOf).find((one) => one !== null) ?? null;
174
+ const chainFeature = record.features.find((one) => one.type === "chain");
175
+ const chainAt = chainFeature === undefined ? null : stretchOf(chainFeature);
176
+ const chain: Chain | null = chainFeature === null || chainFeature === undefined || chainAt === null ? null : {
177
+ ...chainAt,
178
+ name: said(chainFeature, "description") || (words(record.description) ?? "the mature chain"),
179
+ sequence: sequence.slice(chainAt.from - 1, chainAt.to),
180
+ length: chainAt.to - chainAt.from + 1,
181
+ };
182
+
183
+ const modifications: Modified[] = [];
184
+ for (const feature of record.features) {
185
+ if (feature.type !== "modified residue" && feature.type !== "glycosylation site" && feature.type !== "lipid moiety-binding region") continue;
186
+ const at = stretchOf(feature);
187
+ if (at === null) continue;
188
+ modifications.push({
189
+ at: at.from, residue: sequence[at.from - 1] ?? "",
190
+ what: said(feature, "description") || feature.type,
191
+ evidenced: said(feature, "evidence") !== "",
192
+ });
193
+ }
194
+
195
+ const variants: Variant[] = [];
196
+ for (const feature of record.features) {
197
+ if (feature.type !== "sequence variant") continue;
198
+ const at = stretchOf(feature);
199
+ if (at === null) continue;
200
+ variants.push({ ...at, was: said(feature, "original"), now: said(feature, "variation"), note: said(feature, "description") });
201
+ }
202
+
203
+ const regions: Region[] = [];
204
+ for (const feature of record.features) {
205
+ if (!["domain", "region of interest", "repeat", "motif", "zinc finger region", "binding site", "active site"].includes(feature.type)) continue;
206
+ const at = stretchOf(feature);
207
+ if (at === null) continue;
208
+ regions.push({ ...at, kind: feature.type, name: said(feature, "description") || said(feature, "note") || feature.type });
209
+ }
210
+
211
+ const dataset = words(record.annotations.get("dataset"));
212
+ const mass = Number(record.annotations.get("sequence_mass"));
213
+ return {
214
+ accession, alsoKnownAs: list(record.annotations.get("accessions")).slice(1),
215
+ entryName: record.name, name: words(record.description) ?? record.name,
216
+ gene: words(record.annotations.get("gene_name_primary")),
217
+ organism: words(record.annotations.get("organism")),
218
+ lineage: list(record.annotations.get("taxonomy")),
219
+ // UniProt says "Swiss-Prot" for an entry a curator has been over and "TrEMBL" for one made by
220
+ // machine. Anything that is not plainly the first is treated as the second.
221
+ reviewed: dataset !== null && /swiss-?prot/i.test(dataset),
222
+ sequence, length: sequence.length,
223
+ mass: Number.isFinite(mass) && mass > 0 ? mass : null,
224
+ signal, chain,
225
+ modifications: modifications.sort((a, b) => a.at - b.at),
226
+ variants: variants.sort((a, b) => a.from - b.from),
227
+ regions: regions.sort((a, b) => a.from - b.from),
228
+ keywords: list(record.annotations.get("keywords")),
229
+ lookAt: `https://www.uniprot.org/uniprotkb/${accession}`,
230
+ };
231
+ }
232
+
233
+ /**
234
+ * Where a modification falls on the mature chain, rather than on the precursor.
235
+ *
236
+ * UniProt counts every position on the whole entry, signal peptide included. A lab holding the
237
+ * mature protein counts from the first residue it actually has, and the two differ by the length
238
+ * of what was cut off. Getting this wrong by fifteen residues is the easiest mistake here to make
239
+ * and the hardest to notice, because both numbers look perfectly reasonable.
240
+ *
241
+ * @param protein - The protein.
242
+ * @param at - A position on the entry's sequence, counting from 1.
243
+ * @returns The same residue counted from the start of the mature chain, or `null` if it is not on
244
+ * the chain at all — a residue inside the signal peptide is on nothing the lab holds.
245
+ *
246
+ * @example
247
+ * ```ts
248
+ * import { onTheChain } from "@biolibs/uniprot";
249
+ *
250
+ * onTheChain(casein, 30); // 15 — the first phosphoserine, counted on what a lab collects
251
+ * onTheChain(casein, 5); // null — that residue is in the signal peptide and is cut off
252
+ * ```
253
+ */
254
+ export function onTheChain(protein: Pick<Protein, "chain">, at: number): number | null {
255
+ const chain = protein.chain;
256
+ if (chain === null || at < chain.from || at > chain.to) return null;
257
+ return at - chain.from + 1;
258
+ }
package/src/search.ts ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Finding a protein, and fetching the entry for one.
3
+ *
4
+ * A search gives little — enough to choose between entries and no more — because the whole entry
5
+ * is large and most of a search's results are not the one wanted. The one thing it does give that
6
+ * matters before anything else is whether each entry has been **reviewed**: Swiss-Prot entries have
7
+ * been read out of papers by a curator, TrEMBL entries were made by machine from similarity, and
8
+ * treating a machine's guess as a curator's reading is the easiest way to be confidently wrong
9
+ * about a protein.
10
+ */
11
+ import { ask, looksLikeAccession, UniProtError } from "./ask.js";
12
+
13
+ /** The most results one search gives back. */
14
+ export const MOST_FOUND = 50;
15
+
16
+ /** One result: enough to choose by. */
17
+ export interface Hit {
18
+ /** Its accession, to fetch it by. */
19
+ accession: string;
20
+ /** The entry's name, such as `CASB_BOVIN`. */
21
+ entryName: string;
22
+ /** What the protein is called. */
23
+ name: string;
24
+ /** The gene, where the entry names one. */
25
+ gene: string | null;
26
+ /** What it is from. */
27
+ organism: string | null;
28
+ /** How many residues the entry's own sequence has, precursor and all. */
29
+ length: number | null;
30
+ /** Whether a curator has been over it. */
31
+ reviewed: boolean;
32
+ /** Where a person would read it. */
33
+ lookAt: string;
34
+ }
35
+
36
+ /** What a search found. */
37
+ export interface Search {
38
+ /** What was asked. */
39
+ query: string;
40
+ /** The results. */
41
+ results: Hit[];
42
+ }
43
+
44
+ /** What the service sends back, in as much shape as is read. */
45
+ interface RawHit {
46
+ entryType?: string;
47
+ primaryAccession?: string;
48
+ uniProtkbId?: string;
49
+ organism?: { scientificName?: string; commonName?: string };
50
+ proteinDescription?: { recommendedName?: { fullName?: { value?: string } }; submissionNames?: { fullName?: { value?: string } }[] };
51
+ genes?: { geneName?: { value?: string } }[];
52
+ sequence?: { length?: number };
53
+ }
54
+
55
+ const words = (value: unknown): string | null => (typeof value === "string" && value.trim() !== "" ? value.trim() : null);
56
+
57
+ /** One result, read into something steady. */
58
+ export function oneHit(raw: RawHit): Hit {
59
+ const accession = words(raw.primaryAccession) ?? "";
60
+ const organism = words(raw.organism?.scientificName);
61
+ const common = words(raw.organism?.commonName);
62
+ return {
63
+ accession,
64
+ entryName: words(raw.uniProtkbId) ?? "",
65
+ name: words(raw.proteinDescription?.recommendedName?.fullName?.value)
66
+ ?? words(raw.proteinDescription?.submissionNames?.[0]?.fullName?.value) ?? "Unnamed",
67
+ gene: words(raw.genes?.[0]?.geneName?.value),
68
+ organism: organism === null ? null : common === null ? organism : `${organism} (${common})`,
69
+ length: typeof raw.sequence?.length === "number" ? raw.sequence.length : null,
70
+ // "UniProtKB reviewed (Swiss-Prot)" against "UniProtKB unreviewed (TrEMBL)".
71
+ reviewed: /reviewed/i.test(raw.entryType ?? "") && !/unreviewed/i.test(raw.entryType ?? ""),
72
+ lookAt: `https://www.uniprot.org/uniprotkb/${accession}`,
73
+ };
74
+ }
75
+
76
+ /**
77
+ * Search for a protein.
78
+ *
79
+ * @param query - What to look for, in UniProt's own syntax: plain words, and fields such as
80
+ * `gene:CSN2`, `organism_id:9913`, `taxonomy_name:"Bos taurus"`, `reviewed:true`, `length:[200 TO 300]`.
81
+ * @param options - `limit` is how many to bring back; `reviewedOnly` adds the filter for entries a
82
+ * curator has been over, which is usually what somebody means.
83
+ * @returns What matched.
84
+ * @throws {@link UniProtError} if the service could not be reached or did not answer with results.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * import { searchProteins } from "@biolibs/uniprot";
89
+ *
90
+ * const found = await searchProteins("casein AND organism_id:9913", { reviewedOnly: true });
91
+ * found.results.map((one) => [one.accession, one.gene, one.name]);
92
+ * ```
93
+ */
94
+ export async function searchProteins(query: string, options: { limit?: number; reviewedOnly?: boolean } = {}): Promise<Search> {
95
+ const asked = query.trim();
96
+ if (asked === "") throw new UniProtError("There is nothing to search for.", "", null);
97
+ const whole = options.reviewedOnly === true ? `(${asked}) AND reviewed:true` : asked;
98
+ const body = await ask("uniprotkb/search", {
99
+ query: whole, format: "json",
100
+ size: Math.max(1, Math.min(MOST_FOUND, options.limit ?? 10)),
101
+ fields: "accession,id,protein_name,gene_names,organism_name,length,reviewed",
102
+ });
103
+ let answer: { results?: RawHit[] };
104
+ try { answer = JSON.parse(new TextDecoder().decode(body)); } catch { throw new UniProtError("UniProt sent back something that is not the answer to a search.", "uniprotkb/search"); }
105
+ return { query: whole, results: (answer.results ?? []).map(oneHit) };
106
+ }
107
+
108
+ /**
109
+ * Fetch one entry.
110
+ *
111
+ * @param accession - The accession, such as `P02666`.
112
+ * @returns The entry's XML, to be read with `readProtein`.
113
+ * @throws {@link UniProtError} if there is no such entry, or it could not be fetched.
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * import { lookUpProtein, readProtein } from "@biolibs/uniprot";
118
+ *
119
+ * const casein = readProtein(await lookUpProtein("P02666"));
120
+ * ```
121
+ */
122
+ export async function lookUpProtein(accession: string): Promise<Uint8Array> {
123
+ const id = accession.trim().toUpperCase();
124
+ if (!looksLikeAccession(id)) throw new UniProtError(`${JSON.stringify(accession)} is not a UniProt accession. One looks like P02666 or A0A0B4J2F0.`, "uniprotkb");
125
+ try {
126
+ return await ask(`uniprotkb/${id}.xml`);
127
+ } catch (cause) {
128
+ if (cause instanceof UniProtError && cause.status === 404) {
129
+ throw new UniProtError(`UniProt has no entry ${id}. It may have been merged into another; searchProteins finds the one that stands.`, cause.url, 404);
130
+ }
131
+ throw cause;
132
+ }
133
+ }