openchemlib-search-wasm 2.0.0 → 2.1.1

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.
@@ -0,0 +1,181 @@
1
+ import { INDEX_WORDS } from '../types.ts';
2
+
3
+ import dictionary from './dictionary.json' with { type: 'json' };
4
+
5
+ /**
6
+ * Where a key's answer comes from: one of the 512 function bits a record stores, a bit of the FragFp
7
+ * or the screen that holds exactly the same molecules, or a substructure search run when asked.
8
+ */
9
+ export type FunctionKeyTier = 'stored' | 'existingPlane' | 'onDemand';
10
+
11
+ /** One named function key: a functional group, a ring, a substituent, a natural product class. */
12
+ export interface FunctionKey {
13
+ /** Stable identifier. */
14
+ id: string;
15
+ /** The name to show. No other key carries it as name or synonym, case aside. */
16
+ name: string;
17
+ /** The other names it answers to, each also unique across the dictionary. */
18
+ synonyms: string[];
19
+ /** A key of {@link getFunctionCategories}. */
20
+ category: string;
21
+ /** A finer group within the category. */
22
+ subcategory: string;
23
+ tier: FunctionKeyTier;
24
+ /** For a `stored` key: its bit in the function words, 0 to 511. */
25
+ plane?: number;
26
+ /** For an `existingPlane` key: the fingerprint holding its bit. */
27
+ fingerprint?: 'fragFp' | 'screen';
28
+ /** For an `existingPlane` key: its bit in that fingerprint, 0 to 511. */
29
+ bit?: number;
30
+ /** The share of the 1,034,054 PubChem molecules it was counted on that hold it. */
31
+ prevalence: number;
32
+ /** Where its definition comes from: keys of {@link getFunctionKeySources}. */
33
+ sources: string[];
34
+ /** The SMARTS it was compiled from, absent for a key given as an idcode. */
35
+ smarts?: string;
36
+ /**
37
+ * Its query fragments, as idcodes: a molecule holds the key when it holds any of them, which is
38
+ * what `substructureSearch(key.fragments, entries)` tests.
39
+ */
40
+ fragments: string[];
41
+ }
42
+
43
+ /** A source the dictionary's definitions come from, and the licence they are used under. */
44
+ export interface FunctionKeySource {
45
+ name: string;
46
+ url: string;
47
+ licence: string;
48
+ }
49
+
50
+ /** Where a key's bit sits in the 48-word record of `getMoleculeRecords`. */
51
+ export interface RecordBit {
52
+ /** The word of the record: FragFp words first, then the screen, then the function bits. */
53
+ word: number;
54
+ /** The bit within that word. */
55
+ mask: number;
56
+ }
57
+
58
+ /** What {@link searchFunctionKeys} takes. */
59
+ export interface SearchFunctionKeysOptions {
60
+ /**
61
+ * Only the keys of this tier.
62
+ * @default every tier
63
+ */
64
+ tier?: FunctionKeyTier;
65
+ /**
66
+ * Only the keys of this category.
67
+ * @default every category
68
+ */
69
+ category?: string;
70
+ /**
71
+ * The most keys to return.
72
+ * @default no limit
73
+ */
74
+ limit?: number;
75
+ }
76
+
77
+ const KEYS = dictionary.keys as FunctionKey[];
78
+ let byName: Map<string, FunctionKey> | undefined;
79
+
80
+ /**
81
+ * Returns every function key: the 512 stored ones in bit order, then those equal to a FragFp or
82
+ * screen bit, then those computed on demand, by category and prevalence.
83
+ * @returns The keys. They are shared: do not modify them.
84
+ */
85
+ export function getFunctionKeys(): readonly FunctionKey[] {
86
+ return KEYS;
87
+ }
88
+
89
+ /**
90
+ * Finds a key by its id, its name or one of its synonyms, case aside.
91
+ * @param nameOrId - What to look up, such as `thioether`, `Boc` or `pyridin_2_one`.
92
+ * @returns The key, or undefined when nothing carries that name.
93
+ */
94
+ export function getFunctionKey(nameOrId: string): FunctionKey | undefined {
95
+ if (!byName) {
96
+ byName = new Map();
97
+ for (const key of KEYS) {
98
+ for (const name of [key.id, key.name, ...key.synonyms]) {
99
+ if (!byName.has(name.toLowerCase())) {
100
+ byName.set(name.toLowerCase(), key);
101
+ }
102
+ }
103
+ }
104
+ }
105
+ return byName.get(nameOrId.trim().toLowerCase());
106
+ }
107
+
108
+ /**
109
+ * Finds the keys whose id, name or synonyms hold every word of a text, case aside: an exact name
110
+ * first, then names starting with the text, then the rest, each by prevalence.
111
+ * @param text - Words to look for, such as `aromatic amine` or `lactam`.
112
+ * @param options - Narrows the result; see {@link SearchFunctionKeysOptions}.
113
+ * @returns The matching keys, best first.
114
+ */
115
+ export function searchFunctionKeys(
116
+ text: string,
117
+ options: SearchFunctionKeysOptions = {},
118
+ ): FunctionKey[] {
119
+ const { tier, category, limit = Number.POSITIVE_INFINITY } = options;
120
+ const wanted = text.trim().toLowerCase();
121
+ const words = wanted.split(/\s+/).filter(Boolean);
122
+ const scored: Array<{ key: FunctionKey; rank: number }> = [];
123
+ for (const key of KEYS) {
124
+ if (
125
+ (tier && key.tier !== tier) ||
126
+ (category && key.category !== category)
127
+ ) {
128
+ continue;
129
+ }
130
+ const names = [key.name, ...key.synonyms].map((name) => name.toLowerCase());
131
+ const haystack = `${key.id.toLowerCase()}\n${names.join('\n')}`;
132
+ if (!words.every((word) => haystack.includes(word))) continue;
133
+ const rank = names.includes(wanted)
134
+ ? 0
135
+ : names.some((name) => name.startsWith(wanted))
136
+ ? 1
137
+ : 2;
138
+ scored.push({ key, rank });
139
+ }
140
+ scored.sort((a, b) => a.rank - b.rank || b.key.prevalence - a.key.prevalence);
141
+ return scored.slice(0, limit).map(({ key }) => key);
142
+ }
143
+
144
+ /**
145
+ * Returns the categories keys are grouped in, in display order.
146
+ * @returns Category id to its title, such as `carbonyl` to `Carbonyl groups`.
147
+ */
148
+ export function getFunctionCategories(): Readonly<Record<string, string>> {
149
+ return dictionary.categories;
150
+ }
151
+
152
+ /**
153
+ * Returns the sources the definitions come from, with their licences, for attribution.
154
+ * @returns Source id, as a key's `sources` names it, to its name, address and licence.
155
+ */
156
+ export function getFunctionKeySources(): Readonly<
157
+ Record<string, FunctionKeySource>
158
+ > {
159
+ return dictionary.sources;
160
+ }
161
+
162
+ /**
163
+ * Says where a key's answer sits in a record of `getMoleculeRecords`, so a stored record answers it
164
+ * with one mask test: `(record[word] & mask) !== 0`.
165
+ * @param key - The key.
166
+ * @returns The word and mask, or undefined for a key computed on demand, which a record does not hold.
167
+ */
168
+ export function getRecordBit(key: FunctionKey): RecordBit | undefined {
169
+ let base: number;
170
+ let bit: number;
171
+ if (key.tier === 'stored' && key.plane !== undefined) {
172
+ base = 2 * INDEX_WORDS;
173
+ bit = key.plane;
174
+ } else if (key.tier === 'existingPlane' && key.bit !== undefined) {
175
+ base = key.fingerprint === 'screen' ? INDEX_WORDS : 0;
176
+ bit = key.bit;
177
+ } else {
178
+ return undefined;
179
+ }
180
+ return { word: base + (bit >> 5), mask: 1 << (31 - (bit & 31)) };
181
+ }
@@ -0,0 +1,56 @@
1
+ import { buildFunctions, readFunctionKeys } from './scan.ts';
2
+ import { INDEX_WORDS } from './types.ts';
3
+
4
+ /**
5
+ * Builds the 512 function bits of one idcode, as sixteen 32-bit words: bit i is set when any
6
+ * fragment of stored function key i is a substructure of the molecule.
7
+ *
8
+ * The keys are named chemistry — thioether, aromatic ring, uracil, Boc — so a question in words
9
+ * becomes bit arithmetic over stored words. Their names, categories and synonyms, and the keys that
10
+ * are computed on demand instead, are in the dictionary of `openchemlib-search-wasm/function-keys`.
11
+ * A key's bit always agrees with a substructure search for its fragments. The words are laid out
12
+ * as {@link getFunctionKeyFragments} shows.
13
+ * @param idCode - The molecule to read, as an idcode.
14
+ * @returns Sixteen words. An idcode that will not parse gives sixteen zeros.
15
+ */
16
+ export function getFunction(idCode: string): Int32Array {
17
+ const result = new Int32Array(INDEX_WORDS);
18
+ buildFunctions([idCode], result, 0, 1);
19
+ return result;
20
+ }
21
+
22
+ /**
23
+ * Builds the 512 function bits of every idcode, sixteen 32-bit words each.
24
+ *
25
+ * See {@link getFunction}. Each molecule's FragFp and screen are built too, because a key's fragment
26
+ * is only tried on a molecule holding its query words; `getMoleculeRecords` returns all three
27
+ * from one parse. The words are written into one buffer and returned as a view per molecule.
28
+ * @param idCodes - The molecules to read, as idcodes.
29
+ * @returns One sixteen-word view per idcode, in order.
30
+ */
31
+ export function getFunctions(idCodes: string[]): Int32Array[] {
32
+ const all = new Int32Array(idCodes.length * INDEX_WORDS);
33
+ buildFunctions(idCodes, all, 0, idCodes.length);
34
+ const words = new Array<Int32Array>(idCodes.length);
35
+ for (let i = 0; i < idCodes.length; i++) {
36
+ words[i] = all.subarray(i * INDEX_WORDS, (i + 1) * INDEX_WORDS);
37
+ }
38
+ return words;
39
+ }
40
+
41
+ /**
42
+ * Returns the fragments of the 512 stored function keys, in bit order: bit i of {@link getFunction}
43
+ * is set when any fragment of key i is a substructure of the molecule. Bit i sits in word `i >> 5`,
44
+ * the first key in the highest bit of word 0:
45
+ *
46
+ * ```js
47
+ * const held = (words, i) => (words[i >> 5] & (1 << (31 - (i & 31)))) !== 0;
48
+ * ```
49
+ *
50
+ * The list is frozen with the module: changing, adding or reordering a key changes every stored
51
+ * record, so it only changes in a major release.
52
+ * @returns 512 arrays of idcodes, each a key's fragments. The arrays are the caller's own.
53
+ */
54
+ export function getFunctionKeyFragments(): string[][] {
55
+ return readFunctionKeys();
56
+ }
package/src/index.ts CHANGED
@@ -4,6 +4,9 @@ import {
4
4
  buildNoStereoIdCodes,
5
5
  buildNoStereoTautomerHashes,
6
6
  buildNoStereoTautomerIdCodes,
7
+ buildQueryWords,
8
+ buildScreens,
9
+ readKeys,
7
10
  } from './scan.ts';
8
11
  import type { HashOptions } from './types.ts';
9
12
  import { DEFAULT_MAX_TAUTOMERS, INDEX_WORDS, NO_ID_CODE } from './types.ts';
@@ -13,15 +16,29 @@ export { setLogHandler } from './wasm/log.ts';
13
16
  export { hashToHex, hexToHash } from './hex.ts';
14
17
  export { strongHash } from './strongHash.ts';
15
18
  export { similaritySearch } from './similaritySearch.ts';
19
+ export {
20
+ getMoleculeRecords,
21
+ getMoleculeSizes,
22
+ getQueryAtomFloor,
23
+ } from './records.ts';
24
+ export {
25
+ getFunction,
26
+ getFunctionKeyFragments,
27
+ getFunctions,
28
+ } from './functions.ts';
16
29
  export {
17
30
  DEFAULT_MAX_TAUTOMERS,
18
31
  INDEX_WORDS,
19
32
  NO_HASH,
20
33
  NO_ID_CODE,
34
+ RECORD_WORDS,
21
35
  } from './types.ts';
22
36
  export type { LogHandler, LogStream } from './wasm/log.ts';
23
37
  export type {
24
38
  HashOptions,
39
+ MoleculeRecords,
40
+ MoleculeRecordsOptions,
41
+ MoleculeSizes,
25
42
  ResultBuffer,
26
43
  SearchMode,
27
44
  SearchOptions,
@@ -85,6 +102,111 @@ export function getIndexes(idCodes: string[]): Int32Array[] {
85
102
  return indexes;
86
103
  }
87
104
 
105
+ /**
106
+ * Builds the 512-bit screen of one idcode, as sixteen 32-bit words: bit i is set when key i of the
107
+ * screen dictionary is a substructure of the molecule.
108
+ *
109
+ * The screen sits next to the FragFp fingerprint of {@link getIndex}. A molecule is a candidate for
110
+ * a query only if it holds every bit of {@link getQueryIndex} in its fingerprint and every bit of
111
+ * {@link getQueryScreen} in its screen; requiring both lets through about a sixth of the
112
+ * non-matching molecules FragFp alone lets through. The dictionary is 512 OpenChemLib query
113
+ * fragments, matched the way FragFp matches its own keys, and a screen costs about 0.7 times a
114
+ * fingerprint.
115
+ *
116
+ * ```js
117
+ * const isCandidate = (query, molecule) =>
118
+ * query.every((word, i) => (word & molecule[i]) === word);
119
+ * isCandidate(getQueryScreen(query), getScreen(idCode));
120
+ * ```
121
+ * @param idCode - The molecule to screen, as an idcode.
122
+ * @returns Sixteen words. An idcode that will not parse gives sixteen zeros, which no non-empty
123
+ * query screen is a subset of.
124
+ */
125
+ export function getScreen(idCode: string): Int32Array {
126
+ const result = new Int32Array(INDEX_WORDS);
127
+ buildScreens([idCode], result, 0, 1);
128
+ return result;
129
+ }
130
+
131
+ /**
132
+ * Builds the 512-bit screen of every idcode, sixteen 32-bit words each.
133
+ *
134
+ * See {@link getScreen}. The screens are written into one buffer and returned as a view per
135
+ * molecule, each 8-byte aligned, as {@link getIndexes} does.
136
+ * @param idCodes - The molecules to screen, as idcodes.
137
+ * @returns One sixteen-word view per idcode, in order.
138
+ */
139
+ export function getScreens(idCodes: string[]): Int32Array[] {
140
+ const all = new Int32Array(idCodes.length * INDEX_WORDS);
141
+ buildScreens(idCodes, all, 0, idCodes.length);
142
+ const screens = new Array<Int32Array>(idCodes.length);
143
+ for (let i = 0; i < idCodes.length; i++) {
144
+ screens[i] = all.subarray(i * INDEX_WORDS, (i + 1) * INDEX_WORDS);
145
+ }
146
+ return screens;
147
+ }
148
+
149
+ /**
150
+ * Builds the screen of a query: the bits every molecule the query matches has in its
151
+ * {@link getScreen} screen.
152
+ *
153
+ * The query is screened on the fragment OpenChemLib's substructure search actually matches, so an
154
+ * exclude group cutting an aromatic ring and the atom ring sizes of the query are taken into account
155
+ * as the search takes them; a query with a "match formal bond order" bond gets no bits.
156
+ * @param idCodeQuery - The query, as an idcode; read as a fragment whatever its own fragment flag.
157
+ * @returns Sixteen words.
158
+ * @throws {Error} If the query cannot be parsed.
159
+ */
160
+ export function getQueryScreen(idCodeQuery: string): Int32Array {
161
+ return buildQueryWords('screen', idCodeQuery);
162
+ }
163
+
164
+ /**
165
+ * Builds the FragFp fingerprint of a query: the bits every molecule the query matches has in its
166
+ * {@link getIndex} fingerprint.
167
+ *
168
+ * It equals OpenChemLib's own query fingerprint, except for the queries that one wrongly rejects
169
+ * true matches of: an exclude group cutting an aromatic ring, or a "match formal bond order" bond
170
+ * (Actelion/openchemlib#177). The first is fingerprinted on the fragment the search matches; the
171
+ * second gets no bits.
172
+ * @param idCodeQuery - The query, as an idcode; read as a fragment whatever its own fragment flag.
173
+ * @returns Sixteen words.
174
+ * @throws {Error} If the query cannot be parsed.
175
+ */
176
+ export function getQueryIndex(idCodeQuery: string): Int32Array {
177
+ return buildQueryWords('index', idCodeQuery);
178
+ }
179
+
180
+ /**
181
+ * Returns the 512 key fragments of FragFp, in bit order: bit i of {@link getIndex} is set when key i
182
+ * is a substructure of the molecule. They are OpenChemLib's own keys, the list `openchemlib`'s
183
+ * `SSSearcherWithIndex.getKeyIDCode()` returns.
184
+ *
185
+ * Bit i sits in word `i >> 5`, the first key in the highest bit of word 0:
186
+ *
187
+ * ```js
188
+ * const keys = getFragFpKeys();
189
+ * const index = getIndex(idCode);
190
+ * const held = keys.filter((key, i) => index[i >> 5] & (1 << (31 - (i & 31))));
191
+ * ```
192
+ * @returns 512 idcodes, each a query fragment, in bit order. The array is the caller's own.
193
+ */
194
+ export function getFragFpKeys(): string[] {
195
+ return readKeys('index');
196
+ }
197
+
198
+ /**
199
+ * Returns the 512 key fragments of the screen, in bit order: bit i of {@link getScreen} is set when
200
+ * key i is a substructure of the molecule. The words are laid out as {@link getFragFpKeys} shows.
201
+ *
202
+ * The list is frozen: changing, adding or reordering a key changes every stored screen, so it only
203
+ * changes in a major release.
204
+ * @returns 512 idcodes, each a query fragment, in bit order. The array is the caller's own.
205
+ */
206
+ export function getScreenKeys(): string[] {
207
+ return readKeys('screen');
208
+ }
209
+
88
210
  /**
89
211
  * Hashes one idcode to the 64-bit value OpenChemLib identifies a molecule by up to tautomerism and
90
212
  * stereochemistry.
package/src/records.ts ADDED
@@ -0,0 +1,142 @@
1
+ import { recoveringFromTraps } from './scan.ts';
2
+ import type {
3
+ MoleculeRecords,
4
+ MoleculeRecordsOptions,
5
+ MoleculeSizes,
6
+ } from './types.ts';
7
+ import {
8
+ DEFAULT_MAX_TAUTOMERS,
9
+ NO_HASH,
10
+ NO_ID_CODE,
11
+ RECORD_WORDS,
12
+ } from './types.ts';
13
+ import { loadOCL } from './wasm/load.ts';
14
+
15
+ const { Search } = await loadOCL();
16
+
17
+ /**
18
+ * Computes everything a molecule table stores about each idcode, parsing each one once: the
19
+ * canonical idcode, the FragFp, the screen and the function bits, the atom count and the relative
20
+ * weight, and the no-stereo and tautomer hashes.
21
+ *
22
+ * Each value is the one the dedicated function returns — `getIndexes`, `getScreens`, `getFunctions`,
23
+ * `getNoStereoHashes`, `getNoStereoTautomerHashes` — with one deliberate exception: a molecule
24
+ * whose tautomer enumeration reached `maxTautomers` gets its no-stereo hash as its tautomer hash,
25
+ * because a key from a truncated enumeration depends on where it stopped and is not canonical.
26
+ * `tautomerCounts` says which molecules those are.
27
+ *
28
+ * ```js
29
+ * const records = getMoleculeRecords(idCodes, { maxTautomers: 5000 });
30
+ * const words = records.words.subarray(48 * i, 48 * (i + 1)); // FragFp, screen, functions
31
+ * ```
32
+ * @param idCodes - The molecules to read, as idcodes.
33
+ * @param options - See {@link MoleculeRecordsOptions}.
34
+ * @returns One entry per idcode in each array, in input order. A molecule that cannot be read gets
35
+ * `NO_ID_CODE`, zeros, 0 atoms, a `NaN` weight, `NO_HASH` and a tautomer count of 0, and does not
36
+ * cost the others in the batch.
37
+ */
38
+ export function getMoleculeRecords(
39
+ idCodes: string[],
40
+ options: MoleculeRecordsOptions = {},
41
+ ): MoleculeRecords {
42
+ const { maxTautomers = DEFAULT_MAX_TAUTOMERS } = options;
43
+ const count = idCodes.length;
44
+ const records: MoleculeRecords = {
45
+ idCodes: new Array<string>(count).fill(NO_ID_CODE),
46
+ words: new Int32Array(count * RECORD_WORDS),
47
+ atomCounts: new Int32Array(count),
48
+ weights: new Float64Array(count).fill(Number.NaN),
49
+ noStereoHashes: new BigInt64Array(count),
50
+ tautomerHashes: new BigInt64Array(count),
51
+ tautomerCounts: new Int32Array(count),
52
+ };
53
+ recoveringFromTraps(
54
+ (from, to) =>
55
+ Search.getMoleculeRecords(
56
+ idCodes,
57
+ records.idCodes,
58
+ records.words,
59
+ records.atomCounts,
60
+ records.weights,
61
+ records.noStereoHashes,
62
+ records.tautomerHashes,
63
+ records.tautomerCounts,
64
+ maxTautomers,
65
+ from,
66
+ to,
67
+ ),
68
+ (index) => markUnreadable(records, index),
69
+ 0,
70
+ count,
71
+ );
72
+ return records;
73
+ }
74
+
75
+ /**
76
+ * Reads the atom count and the relative weight of each idcode — exactly the `atomCounts` and
77
+ * `weights` of {@link getMoleculeRecords}, and nothing else, so it costs one parse and one formula
78
+ * per molecule.
79
+ * @param idCodes - The molecules to read, as idcodes.
80
+ * @returns One entry per idcode in each array, in input order: 0 atoms and a `NaN` weight for a
81
+ * molecule that cannot be read.
82
+ */
83
+ export function getMoleculeSizes(idCodes: string[]): MoleculeSizes {
84
+ const count = idCodes.length;
85
+ const sizes: MoleculeSizes = {
86
+ atomCounts: new Int32Array(count),
87
+ weights: new Float64Array(count).fill(Number.NaN),
88
+ };
89
+ recoveringFromTraps(
90
+ (from, to) =>
91
+ Search.getMoleculeSizes(
92
+ idCodes,
93
+ sizes.atomCounts,
94
+ sizes.weights,
95
+ from,
96
+ to,
97
+ ),
98
+ (index) => {
99
+ sizes.atomCounts[index] = 0;
100
+ sizes.weights[index] = Number.NaN;
101
+ },
102
+ 0,
103
+ count,
104
+ );
105
+ return sizes;
106
+ }
107
+
108
+ /**
109
+ * The fewest atoms a molecule needs to contain the query: its atoms once the exclude groups are
110
+ * removed, plain hydrogens aside. Each of them maps onto a distinct atom of any match, so a molecule
111
+ * whose atom count is below the floor cannot match and needs no substructure test.
112
+ *
113
+ * Wildcards and atom lists count — each still takes an atom of the match. A plain hydrogen does not,
114
+ * because it may match an implicit one; a deuterium or a tritium does.
115
+ * @param idCodeQuery - The query, as an idcode; read as a fragment whatever its own fragment flag.
116
+ * @returns The floor, or 0 for a query with no atoms.
117
+ * @throws {Error} If the query cannot be parsed.
118
+ */
119
+ export function getQueryAtomFloor(idCodeQuery: string): number {
120
+ try {
121
+ return Search.getQueryAtomFloor(idCodeQuery);
122
+ } catch (error) {
123
+ throw new Error(`"${idCodeQuery}" is not a valid query idcode`, {
124
+ cause: error,
125
+ });
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Writes the "could not read this" record of one molecule over whatever a trap left there.
131
+ * @param records - The records being filled.
132
+ * @param index - The molecule's position.
133
+ */
134
+ function markUnreadable(records: MoleculeRecords, index: number): void {
135
+ records.idCodes[index] = NO_ID_CODE;
136
+ records.words.fill(0, index * RECORD_WORDS, (index + 1) * RECORD_WORDS);
137
+ records.atomCounts[index] = 0;
138
+ records.weights[index] = Number.NaN;
139
+ records.noStereoHashes[index] = NO_HASH;
140
+ records.tautomerHashes[index] = NO_HASH;
141
+ records.tautomerCounts[index] = 0;
142
+ }
package/src/scan.ts CHANGED
@@ -151,6 +151,96 @@ export function buildIndexes(
151
151
  );
152
152
  }
153
153
 
154
+ /**
155
+ * Screens `idCodes[from .. to)` into `result`, sixteen words per molecule.
156
+ *
157
+ * Fails like {@link buildIndexes}: sixteen zeros for an idcode the WASM side cannot read.
158
+ * @param idCodes - The molecules to screen.
159
+ * @param result - The caller's buffer, `16 * idCodes.length` words long.
160
+ * @param from - The first index to screen.
161
+ * @param to - One past the last index to screen.
162
+ * @returns How many molecules were parsed and screened.
163
+ */
164
+ export function buildScreens(
165
+ idCodes: string[],
166
+ result: Int32Array,
167
+ from: number,
168
+ to: number,
169
+ ): number {
170
+ return Search.getScreens(idCodes, result, from, to);
171
+ }
172
+
173
+ /**
174
+ * Builds the function bits of `idCodes[from .. to)` into `result`, sixteen words per molecule.
175
+ *
176
+ * Fails like {@link buildIndexes}: sixteen zeros for an idcode the WASM side cannot read.
177
+ * @param idCodes - The molecules to read.
178
+ * @param result - The caller's buffer, `16 * idCodes.length` words long.
179
+ * @param from - The first index to read.
180
+ * @param to - One past the last index to read.
181
+ * @returns How many molecules were parsed and read.
182
+ */
183
+ export function buildFunctions(
184
+ idCodes: string[],
185
+ result: Int32Array,
186
+ from: number,
187
+ to: number,
188
+ ): number {
189
+ return recoveringFromTraps(
190
+ (first, last) => Search.getFunctions(idCodes, result, first, last),
191
+ (index) => result.fill(0, index * INDEX_WORDS, (index + 1) * INDEX_WORDS),
192
+ from,
193
+ to,
194
+ );
195
+ }
196
+
197
+ /**
198
+ * Reads the fragments of the 512 stored function keys, in bit order.
199
+ * @returns Per key, its fragment idcodes.
200
+ */
201
+ export function readFunctionKeys(): string[][] {
202
+ return Search.getFunctionKeys()
203
+ .split('\n')
204
+ .map((key) => key.split(' '));
205
+ }
206
+
207
+ /**
208
+ * Builds what every molecule a query matches has: its FragFp words, or its screen words.
209
+ * @param kind - `'index'` for the FragFp words, `'screen'` for the screen words.
210
+ * @param idCodeQuery - The query, as an idcode.
211
+ * @returns Sixteen words.
212
+ * @throws {Error} If the query cannot be parsed.
213
+ */
214
+ export function buildQueryWords(
215
+ kind: 'index' | 'screen',
216
+ idCodeQuery: string,
217
+ ): Int32Array {
218
+ const result = new Int32Array(INDEX_WORDS);
219
+ try {
220
+ if (kind === 'index') {
221
+ Search.getQueryIndex(idCodeQuery, result);
222
+ } else {
223
+ Search.getQueryScreen(idCodeQuery, result);
224
+ }
225
+ } catch (error) {
226
+ throw new Error(`"${idCodeQuery}" is not a valid query idcode`, {
227
+ cause: error,
228
+ });
229
+ }
230
+ return result;
231
+ }
232
+
233
+ /**
234
+ * Reads the key fragments behind the bits of the FragFp words, or of the screen words.
235
+ * @param kind - `'index'` for FragFp's keys, `'screen'` for the screen's.
236
+ * @returns 512 idcodes, in bit order.
237
+ */
238
+ export function readKeys(kind: 'index' | 'screen'): string[] {
239
+ const joined =
240
+ kind === 'index' ? Search.getFragFpKeys() : Search.getScreenKeys();
241
+ return joined.split('\n');
242
+ }
243
+
154
244
  /**
155
245
  * Hashes `idCodes[from .. to)` into `result`, one no-stereo tautomer hash per molecule.
156
246
  *
@@ -329,7 +419,7 @@ export function buildNoStereoTautomerIdCodes(
329
419
  * @param to - One past the last index to handle.
330
420
  * @returns How many molecules were handled.
331
421
  */
332
- function recoveringFromTraps(
422
+ export function recoveringFromTraps(
333
423
  call: (from: number, to: number) => number,
334
424
  markUnreadable: (index: number) => void,
335
425
  from: number,