openchemlib-search-wasm 1.0.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.
Files changed (47) hide show
  1. package/LICENSE +275 -0
  2. package/README.md +172 -0
  3. package/lib/index.d.ts +42 -0
  4. package/lib/index.d.ts.map +1 -0
  5. package/lib/index.js +55 -0
  6. package/lib/index.js.map +1 -0
  7. package/lib/jpath.d.ts +28 -0
  8. package/lib/jpath.d.ts.map +1 -0
  9. package/lib/jpath.js +73 -0
  10. package/lib/jpath.js.map +1 -0
  11. package/lib/runSearch.d.ts +41 -0
  12. package/lib/runSearch.d.ts.map +1 -0
  13. package/lib/runSearch.js +50 -0
  14. package/lib/runSearch.js.map +1 -0
  15. package/lib/scan.d.ts +40 -0
  16. package/lib/scan.d.ts.map +1 -0
  17. package/lib/scan.js +103 -0
  18. package/lib/scan.js.map +1 -0
  19. package/lib/similaritySearch.d.ts +28 -0
  20. package/lib/similaritySearch.d.ts.map +1 -0
  21. package/lib/similaritySearch.js +86 -0
  22. package/lib/similaritySearch.js.map +1 -0
  23. package/lib/substructureSearch.d.ts +26 -0
  24. package/lib/substructureSearch.d.ts.map +1 -0
  25. package/lib/substructureSearch.js +81 -0
  26. package/lib/substructureSearch.js.map +1 -0
  27. package/lib/types.d.ts +169 -0
  28. package/lib/types.d.ts.map +1 -0
  29. package/lib/types.js +30 -0
  30. package/lib/types.js.map +1 -0
  31. package/lib/wasm/load.d.ts +10 -0
  32. package/lib/wasm/load.d.ts.map +1 -0
  33. package/lib/wasm/load.js +42 -0
  34. package/lib/wasm/load.js.map +1 -0
  35. package/package.json +80 -0
  36. package/src/index.ts +68 -0
  37. package/src/jpath.ts +77 -0
  38. package/src/runSearch.ts +99 -0
  39. package/src/scan.ts +141 -0
  40. package/src/similaritySearch.ts +104 -0
  41. package/src/substructureSearch.ts +97 -0
  42. package/src/types.ts +197 -0
  43. package/src/wasm/load.ts +50 -0
  44. package/wasm/data.d.ts +2 -0
  45. package/wasm/data.js +3 -0
  46. package/wasm/runtime.d.ts +25 -0
  47. package/wasm/runtime.js +30 -0
package/LICENSE ADDED
@@ -0,0 +1,275 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026 cheminfo
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its contributors
16
+ may be used to endorse or promote products derived from this software
17
+ without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
+
30
+ ================================================================================
31
+
32
+ This package ships `wasm/data.js` and `wasm/runtime.js`, which are a binary
33
+ distribution of two other works:
34
+
35
+ * `wasm/data.js` is a WebAssembly module compiled from OpenChemLib
36
+ (https://github.com/cheminfo/openchemlib) together with the parts of the
37
+ TeaVM class library it reaches. OpenChemLib is distributed under the
38
+ BSD 3-Clause License, reproduced below.
39
+
40
+ * `wasm/runtime.js` is the TeaVM WebAssembly runtime
41
+ (https://github.com/konsoletyper/teavm), version 0.14.1, copied verbatim
42
+ from the TeaVM build output. TeaVM is distributed under the Apache License,
43
+ Version 2.0, reproduced below.
44
+
45
+ --------------------------------------------------------------------------------
46
+ OpenChemLib - https://github.com/cheminfo/openchemlib
47
+ --------------------------------------------------------------------------------
48
+
49
+ Copyright (c) 1997 - 2016
50
+ Actelion Pharmaceuticals Ltd.
51
+ Gewerbestrasse 16
52
+ CH-4123 Allschwil, Switzerland
53
+
54
+ All rights reserved.
55
+
56
+ Redistribution and use in source and binary forms, with or without
57
+ modification, are permitted provided that the following conditions are met:
58
+
59
+ 1. Redistributions of source code must retain the above copyright notice, this
60
+ list of conditions and the following disclaimer.
61
+ 2. Redistributions in binary form must reproduce the above copyright notice,
62
+ this list of conditions and the following disclaimer in the documentation
63
+ and/or other materials provided with the distribution.
64
+ 3. Neither the name of the the copyright holder nor the
65
+ names of its contributors may be used to endorse or promote products
66
+ derived from this software without specific prior written permission.
67
+
68
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
69
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
70
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
71
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
72
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
73
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
74
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
75
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
76
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
77
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
78
+
79
+ --------------------------------------------------------------------------------
80
+ TeaVM - https://github.com/konsoletyper/teavm
81
+ --------------------------------------------------------------------------------
82
+
83
+ Copyright 2014 Alexey Andreev
84
+
85
+ Licensed under the Apache License, Version 2.0 (the "License");
86
+ you may not use this file except in compliance with the License.
87
+ You may obtain a copy of the License at
88
+
89
+ http://www.apache.org/licenses/LICENSE-2.0
90
+
91
+ Unless required by applicable law or agreed to in writing, software
92
+ distributed under the License is distributed on an "AS IS" BASIS,
93
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
94
+ See the License for the specific language governing permissions and
95
+ limitations under the License.
96
+
97
+ The full text of the Apache License, Version 2.0 follows.
98
+
99
+ Apache License
100
+ Version 2.0, January 2004
101
+ http://www.apache.org/licenses/
102
+
103
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
104
+
105
+ 1. Definitions.
106
+
107
+ "License" shall mean the terms and conditions for use, reproduction,
108
+ and distribution as defined by Sections 1 through 9 of this document.
109
+
110
+ "Licensor" shall mean the copyright owner or entity authorized by
111
+ the copyright owner that is granting the License.
112
+
113
+ "Legal Entity" shall mean the union of the acting entity and all
114
+ other entities that control, are controlled by, or are under common
115
+ control with that entity. For the purposes of this definition,
116
+ "control" means (i) the power, direct or indirect, to cause the
117
+ direction or management of such entity, whether by contract or
118
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
119
+ outstanding shares, or (iii) beneficial ownership of such entity.
120
+
121
+ "You" (or "Your") shall mean an individual or Legal Entity
122
+ exercising permissions granted by this License.
123
+
124
+ "Source" form shall mean the preferred form for making modifications,
125
+ including but not limited to software source code, documentation
126
+ source, and configuration files.
127
+
128
+ "Object" form shall mean any form resulting from mechanical
129
+ transformation or translation of a Source form, including but
130
+ not limited to compiled object code, generated documentation,
131
+ and conversions to other media types.
132
+
133
+ "Work" shall mean the work of authorship, whether in Source or
134
+ Object form, made available under the License, as indicated by a
135
+ copyright notice that is included in or attached to the work
136
+ (an example is provided in the Appendix below).
137
+
138
+ "Derivative Works" shall mean any work, whether in Source or Object
139
+ form, that is based on (or derived from) the Work and for which the
140
+ editorial revisions, annotations, elaborations, or other modifications
141
+ represent, as a whole, an original work of authorship. For the purposes
142
+ of this License, Derivative Works shall not include works that remain
143
+ separable from, or merely link (or bind by name) to the interfaces of,
144
+ the Work and Derivative Works thereof.
145
+
146
+ "Contribution" shall mean any work of authorship, including
147
+ the original version of the Work and any modifications or additions
148
+ to that Work or Derivative Works thereof, that is intentionally
149
+ submitted to Licensor for inclusion in the Work by the copyright owner
150
+ or by an individual or Legal Entity authorized to submit on behalf of
151
+ the copyright owner. For the purposes of this definition, "submitted"
152
+ means any form of electronic, verbal, or written communication sent
153
+ to the Licensor or its representatives, including but not limited to
154
+ communication on electronic mailing lists, source code control systems,
155
+ and issue tracking systems that are managed by, or on behalf of, the
156
+ Licensor for the purpose of discussing and improving the Work, but
157
+ excluding communication that is conspicuously marked or otherwise
158
+ designated in writing by the copyright owner as "Not a Contribution."
159
+
160
+ "Contributor" shall mean Licensor and any individual or Legal Entity
161
+ on behalf of whom a Contribution has been received by Licensor and
162
+ subsequently incorporated within the Work.
163
+
164
+ 2. Grant of Copyright License. Subject to the terms and conditions of
165
+ this License, each Contributor hereby grants to You a perpetual,
166
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
167
+ copyright license to reproduce, prepare Derivative Works of,
168
+ publicly display, publicly perform, sublicense, and distribute the
169
+ Work and such Derivative Works in Source or Object form.
170
+
171
+ 3. Grant of Patent License. Subject to the terms and conditions of
172
+ this License, each Contributor hereby grants to You a perpetual,
173
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
174
+ (except as stated in this section) patent license to make, have made,
175
+ use, offer to sell, sell, import, and otherwise transfer the Work,
176
+ where such license applies only to those patent claims licensable
177
+ by such Contributor that are necessarily infringed by their
178
+ Contribution(s) alone or by combination of their Contribution(s)
179
+ with the Work to which such Contribution(s) was submitted. If You
180
+ institute patent litigation against any entity (including a
181
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
182
+ or a Contribution incorporated within the Work constitutes direct
183
+ or contributory patent infringement, then any patent licenses
184
+ granted to You under this License for that Work shall terminate
185
+ as of the date such litigation is filed.
186
+
187
+ 4. Redistribution. You may reproduce and distribute copies of the
188
+ Work or Derivative Works thereof in any medium, with or without
189
+ modifications, and in Source or Object form, provided that You
190
+ meet the following conditions:
191
+
192
+ (a) You must give any other recipients of the Work or
193
+ Derivative Works a copy of this License; and
194
+
195
+ (b) You must cause any modified files to carry prominent notices
196
+ stating that You changed the files; and
197
+
198
+ (c) You must retain, in the Source form of any Derivative Works
199
+ that You distribute, all copyright, patent, trademark, and
200
+ attribution notices from the Source form of the Work,
201
+ excluding those notices that do not pertain to any part of
202
+ the Derivative Works; and
203
+
204
+ (d) If the Work includes a "NOTICE" text file as part of its
205
+ distribution, then any Derivative Works that You distribute must
206
+ include a readable copy of the attribution notices contained
207
+ within such NOTICE file, excluding those notices that do not
208
+ pertain to any part of the Derivative Works, in at least one
209
+ of the following places: within a NOTICE text file distributed
210
+ as part of the Derivative Works; within the Source form or
211
+ documentation, if provided along with the Derivative Works; or,
212
+ within a display generated by the Derivative Works, if and
213
+ wherever such third-party notices normally appear. The contents
214
+ of the NOTICE file are for informational purposes only and
215
+ do not modify the License. You may add Your own attribution
216
+ notices within Derivative Works that You distribute, alongside
217
+ or as an addendum to the NOTICE text from the Work, provided
218
+ that such additional attribution notices cannot be construed
219
+ as modifying the License.
220
+
221
+ You may add Your own copyright statement to Your modifications and
222
+ may provide additional or different license terms and conditions
223
+ for use, reproduction, or distribution of Your modifications, or
224
+ for any such Derivative Works as a whole, provided Your use,
225
+ reproduction, and distribution of the Work otherwise complies with
226
+ the conditions stated in this License.
227
+
228
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
229
+ any Contribution intentionally submitted for inclusion in the Work
230
+ by You to the Licensor shall be under the terms and conditions of
231
+ this License, without any additional terms or conditions.
232
+ Notwithstanding the above, nothing herein shall supersede or modify
233
+ the terms of any separate license agreement you may have executed
234
+ with Licensor regarding such Contributions.
235
+
236
+ 6. Trademarks. This License does not grant permission to use the trade
237
+ names, trademarks, service marks, or product names of the Licensor,
238
+ except as required for reasonable and customary use in describing the
239
+ origin of the Work and reproducing the content of the NOTICE file.
240
+
241
+ 7. Disclaimer of Warranty. Unless required by applicable law or
242
+ agreed to in writing, Licensor provides the Work (and each
243
+ Contributor provides its Contributions) on an "AS IS" BASIS,
244
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
245
+ implied, including, without limitation, any warranties or conditions
246
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
247
+ PARTICULAR PURPOSE. You are solely responsible for determining the
248
+ appropriateness of using or redistributing the Work and assume any
249
+ risks associated with Your exercise of permissions under this License.
250
+
251
+ 8. Limitation of Liability. In no event and under no legal theory,
252
+ whether in tort (including negligence), contract, or otherwise,
253
+ unless required by applicable law (such as deliberate and grossly
254
+ negligent acts) or agreed to in writing, shall any Contributor be
255
+ liable to You for damages, including any direct, indirect, special,
256
+ incidental, or consequential damages of any character arising as a
257
+ result of this License or out of the use or inability to use the
258
+ Work (including but not limited to damages for loss of goodwill,
259
+ work stoppage, computer failure or malfunction, or any and all
260
+ other commercial damages or losses), even if such Contributor
261
+ has been advised of the possibility of such damages.
262
+
263
+ 9. Accepting Warranty or Additional Liability. While redistributing
264
+ the Work or Derivative Works thereof, You may choose to offer,
265
+ and charge a fee for, acceptance of support, warranty, indemnity,
266
+ or other liability obligations and/or rights consistent with this
267
+ License. However, in accepting such obligations, You may act only
268
+ on Your own behalf and on Your sole responsibility, not on behalf
269
+ of any other Contributor, and only if You agree to indemnify,
270
+ defend, and hold each Contributor harmless for any liability
271
+ incurred by, or claims asserted against, such Contributor by reason
272
+ of your accepting any such warranty or additional liability.
273
+
274
+ END OF TERMS AND CONDITIONS
275
+
package/README.md ADDED
@@ -0,0 +1,172 @@
1
+ # openchemlib-search-wasm
2
+
3
+ Batch substructure search, batch similarity search and FragFp fingerprints over arrays of
4
+ OpenChemLib idcodes — with OpenChemLib compiled to WebAssembly.
5
+
6
+ ## Install
7
+
8
+ ```sh
9
+ npm install openchemlib-search-wasm
10
+ ```
11
+
12
+ That is all. The WebAssembly module ships inside the package as a compressed string, so there is no
13
+ `.wasm` file to serve, no bundler plugin, no submodule to clone and no Java to install. Node 22 or
14
+ later, or a current browser; `SharedArrayBuffer` is needed only for the worker recipe below.
15
+
16
+ Updating is a plain `npm update openchemlib-search-wasm` — a release carries its own OpenChemLib, so
17
+ you never track one separately. **Building the module, and moving it to a newer OpenChemLib, is a
18
+ maintainer job**: the `openchemlib` git submodule and the JDK it needs live in
19
+ [CONTRIBUTING.md](CONTRIBUTING.md), not here.
20
+
21
+ ## Use
22
+
23
+ ```ts
24
+ substructureSearch<Entry>(idCodeQuery: string, entries: Entry[],
25
+ options?: SubstructureSearchOptions): SubstructureSearchResult<Entry>;
26
+ similaritySearch<Entry>(idCodeQuery: string, entries: Entry[],
27
+ options?: SimilaritySearchOptions): SimilaritySearchResult<Entry>;
28
+
29
+ // the 512-bit FragFp, for a fingerprint table: sixteen 32-bit words per molecule
30
+ getIndex(idCode: string): Int32Array;
31
+ getIndexes(idCodes: string[]): Int32Array[];
32
+ ```
33
+
34
+ **Give it your objects and it gives them back.** An entry is an idcode or anything carrying one — a
35
+ database row, a candidate a prescreen yielded — and `matches` holds those same objects, so nothing
36
+ has to map positions back onto the array they came from.
37
+
38
+ ```js
39
+ import { similaritySearch, substructureSearch } from 'openchemlib-search-wasm';
40
+
41
+ const benzene = 'gFp@DiTt@@B';
42
+ // benzene, formic acid, naphthalene
43
+ const idCodes = ['gFp@DiTt@@B', 'eMDARVB', 'det@@DjYUX^d@@@@B'];
44
+
45
+ const { matches, indexes, result } = substructureSearch(benzene, idCodes);
46
+ // matches ['gFp@DiTt@@B', 'det@@DjYUX^d@@@@B']
47
+ // indexes [0, 2]
48
+ // result Uint8Array [1, 2, 1] — match, no match, match
49
+
50
+ // the idcode can sit anywhere in your entry; a numeric segment indexes an array
51
+ substructureSearch(benzene, rows, { jpath: 'molecule.idCode' });
52
+
53
+ const similar = similaritySearch(benzene, idCodes);
54
+ // similar.matches most similar first
55
+ // similar.similarities Float32Array [1, 0.75, 0.125] — aligned with matches
56
+ ```
57
+
58
+ The query is searched as a fragment whatever its own fragment flag says. Similarity is the Tanimoto
59
+ coefficient on OpenChemLib's 512-bit FragFp.
60
+
61
+ ### Options
62
+
63
+ | option | default | |
64
+ | ----------- | ------------------------- | ------------------------------------------------------------------- |
65
+ | `jpath` | `'idCode'` | where the idcode sits in an entry |
66
+ | `onStep` | — | called after each step; return `false` to stop |
67
+ | `stepSize` | `4096` / `128` | entries per step — about 100 ms either way |
68
+ | `collect` | `true` | off fills `result` alone, for a worker writing into a shared buffer |
69
+ | `limit` | `Number.MAX_SAFE_INTEGER` | substructure: stop at this many matches. similarity: keep the best |
70
+ | `threshold` | `0` | similarity only: the coefficient at or above which an entry counts |
71
+
72
+ Every search returns `{ matches, indexes, result, matched, unparsable, processed, total, elapsed,
73
+ stopped }`, and a similarity search adds `similarities`.
74
+
75
+ ### Result codes
76
+
77
+ `result` holds one entry per input, in input order, so it can be read while the scan runs.
78
+
79
+ | substructure | | similarity | |
80
+ | ------------ | ---------------------- | ---------- | ---------------------- |
81
+ | `0` | not scanned yet | `NaN` | not scanned yet |
82
+ | `1` | matches | `0`–`1` | the coefficient |
83
+ | `2` | does not | `-1` | idcode would not parse |
84
+ | `3` | idcode would not parse | | |
85
+
86
+ `0` is a legitimate similarity, which is why "not yet" is `NaN` there.
87
+
88
+ ## Stopping early
89
+
90
+ `limit` is what makes a common query cheap. Over 409,686 real molecules, benzene matches 62% of
91
+ them:
92
+
93
+ | | scanned | |
94
+ | --------------------------- | ------: | ---------: |
95
+ | whole corpus | 409,686 | 8.78 s |
96
+ | `limit: 100` | 4,096 | 43 ms |
97
+ | `limit: 100, stepSize: 256` | 512 | 4.5 ms |
98
+ | `limit: 100, stepSize: 64` | 320 | **2.9 ms** |
99
+
100
+ A search stops at the end of the step that reached `limit`, so `stepSize` is the floor on how little
101
+ it can read — worth lowering when a common query only needs a first page.
102
+
103
+ The bounded rows read the front of the array they are handed, which is what a bounded scan always
104
+ does; in this corpus that front happens to hold smaller molecules than average (25.4 characters
105
+ against 38.7), so their cost per entry is below the whole-corpus figure rather than a fifth of it.
106
+
107
+ `onStep` gives the same control with a condition of your own — a deadline, an abort signal, a count.
108
+ It is synchronous and the scan does not yield, so keeping a UI responsive is yours to do: slice the
109
+ array across calls, or run the search in a worker.
110
+
111
+ ## Across workers
112
+
113
+ `result` holds one code per entry in input order, so a corpus splits across workers with no
114
+ bookkeeping: give each worker a contiguous slice of the entries and `collect: false`, so it scans
115
+ without building match arrays it would only have to post back, then copy the `result` it returns
116
+ into that worker's slice of one `SharedArrayBuffer`.
117
+
118
+ 409,686 molecules, benzene, one shared buffer:
119
+
120
+ | workers | 1 | 8 |
121
+ | ------- | ------ | ---------- |
122
+ | wall | 8.78 s | **1.74 s** |
123
+
124
+ Browsers only allow `SharedArrayBuffer` in a cross-origin-isolated page: serve
125
+ `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`. Node
126
+ needs nothing.
127
+
128
+ ## Fingerprints
129
+
130
+ `getIndex` returns the FragFp in the same layout `openchemlib`'s `createIndex` produces, so a
131
+ `BigInt64Array` view over it is the eight columns `openchemlib-sqlite` stores — no conversion, no
132
+ copy:
133
+
134
+ ```js
135
+ const index = getIndex(idCode);
136
+ const columns = new BigInt64Array(index.buffer, index.byteOffset, 8);
137
+ ```
138
+
139
+ This is the expensive half of importing a library, and where the biggest speedup is.
140
+
141
+ ## What you actually win
142
+
143
+ Against `openchemlib` 9.25.0, on 409,686 real idcodes, with identical hit counts for every query:
144
+
145
+ | | openchemlib | this | |
146
+ | ------------------------------------- | ----------: | ------: | ------------- |
147
+ | substructure, per molecule | 42.0 µs | 20.8 µs | **2.02x** |
148
+ | substructure, whole corpus, 8 workers | 3.81 s | 1.74 s | **2.19x** |
149
+ | fingerprint, per molecule | 4580 µs | 832 µs | **5.51x** |
150
+ | gzipped payload | 336 kB | 95 kB | **3.5x** less |
151
+
152
+ The substructure row is benzene; the six queries the benchmark runs span 2.00x to 2.22x.
153
+
154
+ **Substructure is only about 2x because half the work is decoding the idcode**, and that half is
155
+ only 1.7x faster; the graph match is 1.9x. Benchmarks that search molecules already parsed in memory
156
+ report 3–6x — this API is handed idcodes and pays the parse on every one. It is also **per core**:
157
+ `openchemlib` parallelises across workers just as well.
158
+
159
+ Full tables, and how each number was taken, in [benchmark/README.md](benchmark/README.md).
160
+
161
+ ## When not to use it
162
+
163
+ **You already store fingerprints.** `similaritySearch` builds the FragFp for every idcode, and that
164
+ is the entire cost — the Tanimoto comparison itself is 0.03 µs in plain JavaScript. Compare the
165
+ stored ones directly and skip this; it exists for when idcodes are all you have.
166
+
167
+ **You can prescreen in SQL.** A fingerprint screen in the query removes most candidates before
168
+ anything is parsed, which is worth far more than 2x. Search the survivors, not the whole table.
169
+
170
+ ## License
171
+
172
+ BSD-3-Clause.
package/lib/index.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ export { substructureSearch } from './substructureSearch.ts';
2
+ export { similaritySearch } from './similaritySearch.ts';
3
+ export { INDEX_WORDS } from './types.ts';
4
+ export type { ResultBuffer, SearchMode, SearchOptions, SearchResult, SearchStep, SimilaritySearchOptions, SimilaritySearchResult, SubstructureSearchOptions, SubstructureSearchResult, } from './types.ts';
5
+ export { SimilarityResult, SubstructureResult } from './types.ts';
6
+ /**
7
+ * Builds the 512-bit FragFp fingerprint of one idcode, as sixteen 32-bit words.
8
+ *
9
+ * This is what a fingerprint table is made of, and building it is the expensive part of importing a
10
+ * library: about 897 µs per molecule, against 4484 µs for `openchemlib-js` — six minutes instead of
11
+ * thirty for 400,000 molecules. Calling this once per molecule costs the same as one batched call,
12
+ * so a row-at-a-time importer needs no restructuring to get that.
13
+ *
14
+ * The words are in the same order `openchemlib-js`'s `createIndex` produces, so they are
15
+ * interchangeable with an existing table, and a `BigInt64Array` view over the result is exactly the
16
+ * eight columns `openchemlib-sqlite` stores — no conversion, no copy:
17
+ *
18
+ * ```js
19
+ * const index = getIndex(idCode);
20
+ * const columns = new BigInt64Array(index.buffer, index.byteOffset, 8); // ss_index0..7
21
+ * insert.run(mw, entryId, ...columns);
22
+ * ```
23
+ * @param idCode - The molecule to fingerprint, as an idcode.
24
+ * @returns Sixteen words. An idcode that will not parse gives sixteen zeros, which no non-empty
25
+ * query is a subset of, so it can never be a false candidate.
26
+ */
27
+ export declare function getIndex(idCode: string): Int32Array;
28
+ /**
29
+ * Builds the 512-bit FragFp fingerprint of every idcode, sixteen 32-bit words each.
30
+ *
31
+ * See {@link getIndex} for the one-molecule form, which costs the same per molecule: the 512 key
32
+ * fragments OpenChemLib matches against are parsed once and held for the module's lifetime, so
33
+ * there is nothing for a batch to amortise.
34
+ *
35
+ * The fingerprints are written into one buffer and returned as a view per molecule, so the array
36
+ * costs one allocation rather than one per molecule, and every view is still 8-byte aligned and can
37
+ * be read as the eight `BigInt64` columns {@link getIndex} shows.
38
+ * @param idCodes - The molecules to fingerprint, as idcodes.
39
+ * @returns One sixteen-word view per idcode, in order.
40
+ */
41
+ export declare function getIndexes(idCodes: string[]): Int32Array[];
42
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,YAAY,EACV,YAAY,EACZ,UAAU,EACV,aAAa,EACb,YAAY,EACZ,UAAU,EACV,uBAAuB,EACvB,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAElE;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAInD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,UAAU,EAAE,CAQ1D"}
package/lib/index.js ADDED
@@ -0,0 +1,55 @@
1
+ import { buildIndexes } from "./scan.js";
2
+ import { INDEX_WORDS } from "./types.js";
3
+ export { substructureSearch } from "./substructureSearch.js";
4
+ export { similaritySearch } from "./similaritySearch.js";
5
+ export { INDEX_WORDS } from "./types.js";
6
+ export { SimilarityResult, SubstructureResult } from "./types.js";
7
+ /**
8
+ * Builds the 512-bit FragFp fingerprint of one idcode, as sixteen 32-bit words.
9
+ *
10
+ * This is what a fingerprint table is made of, and building it is the expensive part of importing a
11
+ * library: about 897 µs per molecule, against 4484 µs for `openchemlib-js` — six minutes instead of
12
+ * thirty for 400,000 molecules. Calling this once per molecule costs the same as one batched call,
13
+ * so a row-at-a-time importer needs no restructuring to get that.
14
+ *
15
+ * The words are in the same order `openchemlib-js`'s `createIndex` produces, so they are
16
+ * interchangeable with an existing table, and a `BigInt64Array` view over the result is exactly the
17
+ * eight columns `openchemlib-sqlite` stores — no conversion, no copy:
18
+ *
19
+ * ```js
20
+ * const index = getIndex(idCode);
21
+ * const columns = new BigInt64Array(index.buffer, index.byteOffset, 8); // ss_index0..7
22
+ * insert.run(mw, entryId, ...columns);
23
+ * ```
24
+ * @param idCode - The molecule to fingerprint, as an idcode.
25
+ * @returns Sixteen words. An idcode that will not parse gives sixteen zeros, which no non-empty
26
+ * query is a subset of, so it can never be a false candidate.
27
+ */
28
+ export function getIndex(idCode) {
29
+ const result = new Int32Array(INDEX_WORDS);
30
+ buildIndexes([idCode], result, 0, 1);
31
+ return result;
32
+ }
33
+ /**
34
+ * Builds the 512-bit FragFp fingerprint of every idcode, sixteen 32-bit words each.
35
+ *
36
+ * See {@link getIndex} for the one-molecule form, which costs the same per molecule: the 512 key
37
+ * fragments OpenChemLib matches against are parsed once and held for the module's lifetime, so
38
+ * there is nothing for a batch to amortise.
39
+ *
40
+ * The fingerprints are written into one buffer and returned as a view per molecule, so the array
41
+ * costs one allocation rather than one per molecule, and every view is still 8-byte aligned and can
42
+ * be read as the eight `BigInt64` columns {@link getIndex} shows.
43
+ * @param idCodes - The molecules to fingerprint, as idcodes.
44
+ * @returns One sixteen-word view per idcode, in order.
45
+ */
46
+ export function getIndexes(idCodes) {
47
+ const all = new Int32Array(idCodes.length * INDEX_WORDS);
48
+ buildIndexes(idCodes, all, 0, idCodes.length);
49
+ const indexes = new Array(idCodes.length);
50
+ for (let i = 0; i < idCodes.length; i++) {
51
+ indexes[i] = all.subarray(i * INDEX_WORDS, (i + 1) * INDEX_WORDS);
52
+ }
53
+ return indexes;
54
+ }
55
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAYzC,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAElE;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,QAAQ,CAAC,MAAc;IACrC,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC;IAC3C,YAAY,CAAC,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACrC,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,UAAU,CAAC,OAAiB;IAC1C,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,OAAO,CAAC,MAAM,GAAG,WAAW,CAAC,CAAC;IACzD,YAAY,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAC9C,MAAM,OAAO,GAAG,IAAI,KAAK,CAAa,OAAO,CAAC,MAAM,CAAC,CAAC;IACtD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACxC,OAAO,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,QAAQ,CAAC,CAAC,GAAG,WAAW,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC"}
package/lib/jpath.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Reads the idcode every entry carries, following a jpath.
3
+ *
4
+ * The jpath is the dot-separated form the rest of the ecosystem uses (`get-jpaths`,
5
+ * `derived-props`): `idCode`, `molecule.idCode`, `spectra.0.idCode`. A numeric segment indexes an
6
+ * array, because `array['0']` and `array[0]` are the same property.
7
+ *
8
+ * The path is split once and walked with a plain loop per entry, so a scan of 400,000 entries costs
9
+ * one string split rather than 400,000 of them.
10
+ * @param entries - The entries to read.
11
+ * @param jpath - Where the idcode sits in each entry.
12
+ * @returns One idcode per entry, in order. An entry with no string at the jpath gives an empty
13
+ * string, which the scan reports as unparsable like any other idcode it cannot read.
14
+ * @throws {Error} If no entry at all has a string there, which means the jpath is wrong rather than
15
+ * the data.
16
+ */
17
+ export declare function readIdCodes(entries: readonly unknown[], jpath: string): string[];
18
+ /**
19
+ * Turns whatever the caller passed into the array of idcodes the scan reads.
20
+ *
21
+ * An array of idcodes is used as it is — that is the hot path a worker scanning a decoded chunk
22
+ * takes, and copying it would allocate one reference per molecule for nothing.
23
+ * @param entries - Idcodes, or entries carrying one at `jpath`.
24
+ * @param jpath - Where the idcode sits in an entry.
25
+ * @returns The idcodes to scan.
26
+ */
27
+ export declare function toIdCodes(entries: readonly unknown[], jpath: string): string[];
28
+ //# sourceMappingURL=jpath.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jpath.d.ts","sourceRoot":"","sources":["../src/jpath.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,CACzB,OAAO,EAAE,SAAS,OAAO,EAAE,EAC3B,KAAK,EAAE,MAAM,GACZ,MAAM,EAAE,CAuCV;AAED;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CACvB,OAAO,EAAE,SAAS,OAAO,EAAE,EAC3B,KAAK,EAAE,MAAM,GACZ,MAAM,EAAE,CAIV"}
package/lib/jpath.js ADDED
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Reads the idcode every entry carries, following a jpath.
3
+ *
4
+ * The jpath is the dot-separated form the rest of the ecosystem uses (`get-jpaths`,
5
+ * `derived-props`): `idCode`, `molecule.idCode`, `spectra.0.idCode`. A numeric segment indexes an
6
+ * array, because `array['0']` and `array[0]` are the same property.
7
+ *
8
+ * The path is split once and walked with a plain loop per entry, so a scan of 400,000 entries costs
9
+ * one string split rather than 400,000 of them.
10
+ * @param entries - The entries to read.
11
+ * @param jpath - Where the idcode sits in each entry.
12
+ * @returns One idcode per entry, in order. An entry with no string at the jpath gives an empty
13
+ * string, which the scan reports as unparsable like any other idcode it cannot read.
14
+ * @throws {Error} If no entry at all has a string there, which means the jpath is wrong rather than
15
+ * the data.
16
+ */
17
+ export function readIdCodes(entries, jpath) {
18
+ const segments = jpath.split('.');
19
+ const idCodes = new Array(entries.length);
20
+ let found = 0;
21
+ if (segments.length === 1) {
22
+ const key = segments[0];
23
+ for (let i = 0; i < entries.length; i++) {
24
+ const value = entries[i]?.[key];
25
+ if (typeof value === 'string') {
26
+ idCodes[i] = value;
27
+ found++;
28
+ }
29
+ else {
30
+ idCodes[i] = '';
31
+ }
32
+ }
33
+ }
34
+ else {
35
+ for (let i = 0; i < entries.length; i++) {
36
+ let value = entries[i];
37
+ for (const segment of segments) {
38
+ if (value === null || value === undefined)
39
+ break;
40
+ value = value[segment];
41
+ }
42
+ if (typeof value === 'string') {
43
+ idCodes[i] = value;
44
+ found++;
45
+ }
46
+ else {
47
+ idCodes[i] = '';
48
+ }
49
+ }
50
+ }
51
+ if (found === 0 && entries.length > 0) {
52
+ throw new Error(`no entry holds a string at jpath "${jpath}": pass the jpath option if the idcode is` +
53
+ ' somewhere else');
54
+ }
55
+ return idCodes;
56
+ }
57
+ /**
58
+ * Turns whatever the caller passed into the array of idcodes the scan reads.
59
+ *
60
+ * An array of idcodes is used as it is — that is the hot path a worker scanning a decoded chunk
61
+ * takes, and copying it would allocate one reference per molecule for nothing.
62
+ * @param entries - Idcodes, or entries carrying one at `jpath`.
63
+ * @param jpath - Where the idcode sits in an entry.
64
+ * @returns The idcodes to scan.
65
+ */
66
+ export function toIdCodes(entries, jpath) {
67
+ if (entries.length === 0)
68
+ return [];
69
+ if (typeof entries[0] === 'string')
70
+ return entries;
71
+ return readIdCodes(entries, jpath);
72
+ }
73
+ //# sourceMappingURL=jpath.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jpath.js","sourceRoot":"","sources":["../src/jpath.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,WAAW,CACzB,OAA2B,EAC3B,KAAa;IAEb,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,MAAM,OAAO,GAAG,IAAI,KAAK,CAAS,OAAO,CAAC,MAAM,CAAC,CAAC;IAClD,IAAI,KAAK,GAAG,CAAC,CAAC;IAEd,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1B,MAAM,GAAG,GAAG,QAAQ,CAAC,CAAC,CAAW,CAAC;QAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACxC,MAAM,KAAK,GAAI,OAAO,CAAC,CAAC,CAAoC,EAAE,CAAC,GAAG,CAAC,CAAC;YACpE,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;gBACnB,KAAK,EAAE,CAAC;YACV,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;YAClB,CAAC;QACH,CAAC;IACH,CAAC;SAAM,CAAC;QACN,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACxC,IAAI,KAAK,GAAY,OAAO,CAAC,CAAC,CAAC,CAAC;YAChC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;gBAC/B,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;oBAAE,MAAM;gBACjD,KAAK,GAAI,KAAiC,CAAC,OAAO,CAAC,CAAC;YACtD,CAAC;YACD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;gBACnB,KAAK,EAAE,CAAC;YACV,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;YAClB,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,KAAK,KAAK,CAAC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACtC,MAAM,IAAI,KAAK,CACb,qCAAqC,KAAK,2CAA2C;YACnF,iBAAiB,CACpB,CAAC;IACJ,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,SAAS,CACvB,OAA2B,EAC3B,KAAa;IAEb,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACpC,IAAI,OAAO,OAAO,CAAC,CAAC,CAAC,KAAK,QAAQ;QAAE,OAAO,OAA8B,CAAC;IAC1E,OAAO,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AACrC,CAAC"}