sci-form-wasm 0.4.2 → 0.4.3
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/README.md
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
# sci-form
|
|
2
|
+
|
|
3
|
+
**High-performance 3D molecular conformer generation and quantum-chemistry-inspired property computation**, written in pure Rust.
|
|
4
|
+
|
|
5
|
+
Generates chemically valid 3D coordinates from SMILES strings with RDKit-quality accuracy (ETKDGv2), and provides a full suite of computational chemistry tools: Extended Hückel Theory, electrostatic potentials, density of states, population analysis, molecular alignment, force field energy evaluation (UFF + MMFF94), partial charges, SASA, and materials framework assembly.
|
|
6
|
+
|
|
7
|
+
Native bindings for **Rust**, **Python**, **TypeScript/JavaScript (WASM)**, and a **cross-platform CLI**.
|
|
8
|
+
|
|
9
|
+
[](https://crates.io/crates/sci-form)
|
|
10
|
+
[](https://pypi.org/project/sciforma)
|
|
11
|
+
[](https://www.npmjs.com/package/sci-form-wasm)
|
|
12
|
+
[](LICENSE)
|
|
13
|
+
|
|
14
|
+
## Features
|
|
15
|
+
|
|
16
|
+
### Conformer Generation
|
|
17
|
+
- **ETKDGv2 Distance Geometry** — CSD torsion preferences (846 SMARTS patterns), matches RDKit accuracy
|
|
18
|
+
- **High Accuracy** — 0.00% heavy-atom RMSD > 0.5 Å vs RDKit on GDB-20 (2000 molecules, ensemble comparison)
|
|
19
|
+
- **Fast** — 60+ molecules/second in Rust, parallel batch processing via rayon
|
|
20
|
+
- **Full chemical coverage** — organics, stereocenters, macrocycles, fused rings, metals, halogens (He→Bi)
|
|
21
|
+
|
|
22
|
+
### Quantum Chemistry (EHT)
|
|
23
|
+
- **Extended Hückel Theory** — Wolfsberg-Helmholtz Hamiltonian, Löwdin orthogonalization, HOMO/LUMO gaps
|
|
24
|
+
- **Mulliken & Löwdin population analysis** — atomic orbital contributions per atom
|
|
25
|
+
- **Molecular dipole moment** — bond dipoles + lone-pair contributions in Debye
|
|
26
|
+
- **Volumetric orbital grids** — STO-3G basis, chunked evaluation for large molecules, marching cubes isosurfaces
|
|
27
|
+
- **Density of States** — total DOS + per-atom PDOS with Gaussian smearing, JSON export, MSE metric
|
|
28
|
+
|
|
29
|
+
### Electrostatics & Surface
|
|
30
|
+
- **Electrostatic Potential (ESP)** — Coulomb grid from Mulliken charges, color mapping (red/white/blue), `.cube` export
|
|
31
|
+
- **Parallel ESP** — rayon-accelerated grid computation (`parallel` feature)
|
|
32
|
+
- **Solvent-Accessible Surface Area (SASA)** — Shrake-Rupley algorithm, Fibonacci sphere, Bondi radii, parallelized per-atom evaluation
|
|
33
|
+
- **Gasteiger-Marsili partial charges** — 6-iteration electronegativity equalization
|
|
34
|
+
|
|
35
|
+
### Parallel Computation
|
|
36
|
+
- **Automatic rayon thread pool** — all compute functions (DOS, ESP SASA, population, dipole, etc.) parallelized with work-stealing queue
|
|
37
|
+
- **Zero-configuration** — no API changes needed; parallelization enabled by default via `parallel` feature
|
|
38
|
+
- **Intra-library parallelism** — grid point loops, per-atom evaluation, force field term accumulation all use `par_iter()`
|
|
39
|
+
- **CPU-aware workload balancing** — handles small molecules (sequential) and large molecules (parallel) automatically
|
|
40
|
+
|
|
41
|
+
### Force Fields
|
|
42
|
+
- **UFF** — Universal Force Field for 50+ element types (including transition metals Ti–Zn, Pd, Pt, Au)
|
|
43
|
+
- **MMFF94** — Merck force field (stretch, bend, torsion, van der Waals, electrostatics via 14-7 potential)
|
|
44
|
+
- **BFGS / L-BFGS minimizers** — dense BFGS for small molecules, L-BFGS for large systems
|
|
45
|
+
|
|
46
|
+
### Molecular Alignment
|
|
47
|
+
- **Kabsch alignment** — SVD-based optimal rotation, minimizes RMSD
|
|
48
|
+
- **Quaternion alignment** — Coutsias 2004 4×4 eigenproblem (faster for large molecules)
|
|
49
|
+
- **RMSD computation** — after optimal superposition
|
|
50
|
+
|
|
51
|
+
### Materials
|
|
52
|
+
- **Periodic unit cells** — lattice parameters (a, b, c, α, β, γ) to Cartesian tensor
|
|
53
|
+
- **Secondary Building Units (SBUs)** — node/linker topology with coordination sites
|
|
54
|
+
- **Framework assembly** — MOF-type crystal structure generation from SBUs + topology
|
|
55
|
+
|
|
56
|
+
### Platform
|
|
57
|
+
- **Multi-platform** — Rust lib, Python (PyO3), TypeScript/JS (WASM), CLI (Linux/macOS/Windows)
|
|
58
|
+
- **Zero runtime dependencies** — pure Rust, no C++ toolchain needed
|
|
59
|
+
- **SMILES + SMARTS** — full parser and substructure matcher; 60+ bracket elements
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## Quick Start
|
|
64
|
+
|
|
65
|
+
### Rust
|
|
66
|
+
|
|
67
|
+
```toml
|
|
68
|
+
[dependencies]
|
|
69
|
+
sci-form = "0.2"
|
|
70
|
+
# For parallel batch + ESP:
|
|
71
|
+
sci-form = { version = "0.2", features = ["parallel"] }
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
```rust
|
|
75
|
+
use sci_form::{embed, compute_charges, compute_esp, compute_dos, compute_population};
|
|
76
|
+
|
|
77
|
+
// 3D conformer
|
|
78
|
+
let result = sci_form::embed("CCO", 42);
|
|
79
|
+
println!("Atoms: {}, Time: {:.1}ms", result.num_atoms, result.time_ms);
|
|
80
|
+
|
|
81
|
+
// Gasteiger–Marsili charges
|
|
82
|
+
let charges = sci_form::compute_charges("CCO").unwrap();
|
|
83
|
+
println!("Charges: {:?}", charges.charges);
|
|
84
|
+
|
|
85
|
+
// EHT → population analysis
|
|
86
|
+
let mol = sci_form::parse("CCO").unwrap();
|
|
87
|
+
let elements: Vec<u8> = /* ... */ vec![8, 6, 6, 1, 1, 1, 1, 1, 1];
|
|
88
|
+
let positions: Vec<[f64; 3]> = /* ... from result.coords */ vec![];
|
|
89
|
+
let pop = sci_form::compute_population(&elements, &positions).unwrap();
|
|
90
|
+
println!("HOMO: {:.3} eV", pop.homo_energy);
|
|
91
|
+
|
|
92
|
+
// ESP grid
|
|
93
|
+
let esp = sci_form::compute_esp(&elements, &positions, 0.5, 3.0).unwrap();
|
|
94
|
+
|
|
95
|
+
// DOS / PDOS
|
|
96
|
+
let dos = sci_form::compute_dos(&elements, &positions, 0.2, -20.0, 5.0, 200).unwrap();
|
|
97
|
+
println!("HOMO–LUMO gap: {:.3} eV", dos.homo_lumo_gap.unwrap_or(0.0));
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
→ [Full Rust API reference](https://jigonzalez930209.github.io/sci-form/api/rust) · [Guide](https://jigonzalez930209.github.io/sci-form/guide/rust)
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
### Python
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
pip install sciforma
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
import sci_form
|
|
112
|
+
|
|
113
|
+
# 3D conformer
|
|
114
|
+
result = sci_form.embed("CCO")
|
|
115
|
+
print(f"Atoms: {result.num_atoms}, Time: {result.time_ms:.1f}ms")
|
|
116
|
+
|
|
117
|
+
# Batch
|
|
118
|
+
results = sci_form.embed_batch(["CCO", "c1ccccc1", "CC(=O)O"])
|
|
119
|
+
|
|
120
|
+
# Gasteiger charges
|
|
121
|
+
charges = sci_form.compute_charges("CCO")
|
|
122
|
+
print(charges["charges"]) # per-atom charges
|
|
123
|
+
|
|
124
|
+
# EHT + population analysis
|
|
125
|
+
elements = [8, 6, 6, 1, 1, 1, 1, 1, 1]
|
|
126
|
+
positions = [[0.0, 0.0, 0.0], ...] # from result.coords
|
|
127
|
+
pop = sci_form.compute_population(elements, positions)
|
|
128
|
+
print(f"HOMO: {pop['homo_energy']:.3f} eV")
|
|
129
|
+
|
|
130
|
+
# DOS / PDOS
|
|
131
|
+
dos = sci_form.compute_dos(elements, positions, sigma=0.2, e_min=-20.0, e_max=5.0, n_points=200)
|
|
132
|
+
print(f"Gap: {dos['homo_lumo_gap']:.3f} eV")
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
→ [Full Python API reference](https://jigonzalez930209.github.io/sci-form/api/python) · [Guide](https://jigonzalez930209.github.io/sci-form/guide/python)
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
### TypeScript / JavaScript (WASM)
|
|
140
|
+
|
|
141
|
+
```bash
|
|
142
|
+
npm install sci-form-wasm
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
```typescript
|
|
146
|
+
import init, {
|
|
147
|
+
embed, embed_coords_typed,
|
|
148
|
+
compute_esp_grid_typed, compute_esp_grid_info,
|
|
149
|
+
eht_calculate, eht_orbital_mesh, eht_orbital_grid_typed,
|
|
150
|
+
compute_charges, compute_dos
|
|
151
|
+
} from 'sci-form-wasm';
|
|
152
|
+
|
|
153
|
+
await init();
|
|
154
|
+
|
|
155
|
+
// Conformer as JSON
|
|
156
|
+
const result = JSON.parse(embed('CCO', 42));
|
|
157
|
+
console.log(result.num_atoms);
|
|
158
|
+
|
|
159
|
+
// Typed-array conformer (faster, no JSON overhead)
|
|
160
|
+
const coords: Float64Array = embed_coords_typed('CCO', 42);
|
|
161
|
+
|
|
162
|
+
// EHT calculation
|
|
163
|
+
const eht = JSON.parse(eht_calculate('[6,8,6,1,1,1,1,1,1]', coords.toString(), 1.75));
|
|
164
|
+
console.log(`HOMO: ${eht.homo_energy} eV, LUMO: ${eht.lumo_energy} eV`);
|
|
165
|
+
|
|
166
|
+
// Orbital isosurface mesh
|
|
167
|
+
const mesh = JSON.parse(eht_orbital_mesh('[6,8,6,1,1,1,1,1,1]', coords.toString(), 1.75, 0, 0.02));
|
|
168
|
+
// mesh.vertices, mesh.normals, mesh.indices
|
|
169
|
+
|
|
170
|
+
// ESP grid (typed array)
|
|
171
|
+
const espData: Float64Array = compute_esp_grid_typed('CCO', 42, 0.5, 3.0);
|
|
172
|
+
const espInfo = JSON.parse(compute_esp_grid_info('CCO', 42, 0.5, 3.0));
|
|
173
|
+
console.log(`Grid: ${espInfo.nx}×${espInfo.ny}×${espInfo.nz}`);
|
|
174
|
+
|
|
175
|
+
// DOS
|
|
176
|
+
const dos = JSON.parse(compute_dos('[6,8,6,1,1,1,1,1,1]', coords.toString(), 0.2, -20.0, 5.0, 200));
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
→ [Full TypeScript API reference](https://jigonzalez930209.github.io/sci-form/api/typescript) · [Guide](https://jigonzalez930209.github.io/sci-form/guide/typescript)
|
|
180
|
+
|
|
181
|
+
---
|
|
182
|
+
|
|
183
|
+
### CLI
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
cargo install sci-form-cli
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
# Single molecule
|
|
191
|
+
sci-form embed "CCO" --format xyz
|
|
192
|
+
|
|
193
|
+
# Batch processing
|
|
194
|
+
sci-form batch -i molecules.smi -o output.sdf --format sdf --threads 8
|
|
195
|
+
|
|
196
|
+
# Parse only (no 3D)
|
|
197
|
+
sci-form parse "c1ccccc1"
|
|
198
|
+
|
|
199
|
+
# Gasteiger charges
|
|
200
|
+
sci-form charges "CCO"
|
|
201
|
+
|
|
202
|
+
# UFF energy
|
|
203
|
+
sci-form energy "CCO" --coords coords.json
|
|
204
|
+
|
|
205
|
+
# Version / features
|
|
206
|
+
sci-form info
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
Prebuilt binaries available at [GitHub Releases](https://github.com/jigonzalez930209/sci-form/releases):
|
|
210
|
+
|
|
211
|
+
| Platform | File |
|
|
212
|
+
|----------|------|
|
|
213
|
+
| Linux x86_64 | `sci-form-linux-x86_64` |
|
|
214
|
+
| Linux aarch64 | `sci-form-linux-aarch64` |
|
|
215
|
+
| macOS x86_64 | `sci-form-macos-x86_64` |
|
|
216
|
+
| macOS Apple Silicon | `sci-form-macos-aarch64` |
|
|
217
|
+
| Windows x86_64 | `sci-form-windows-x86_64.exe` |
|
|
218
|
+
|
|
219
|
+
→ [Full CLI reference](https://jigonzalez930209.github.io/sci-form/api/cli) · [Guide](https://jigonzalez930209.github.io/sci-form/guide/cli)
|
|
220
|
+
|
|
221
|
+
---
|
|
222
|
+
|
|
223
|
+
## Benchmark Results
|
|
224
|
+
|
|
225
|
+
### Conformer Generation — Diverse Molecules (131 molecules, all functional groups)
|
|
226
|
+
|
|
227
|
+
| Metric | Value |
|
|
228
|
+
|--------|-------|
|
|
229
|
+
| Parse success | 100% |
|
|
230
|
+
| Embed success | 97.7% |
|
|
231
|
+
| Geometry quality | 97.7% |
|
|
232
|
+
| Throughput | 60 mol/s |
|
|
233
|
+
|
|
234
|
+
### RDKit Comparison — Heavy-atom pairwise-distance RMSD
|
|
235
|
+
|
|
236
|
+
| Metric | Value |
|
|
237
|
+
|--------|-------|
|
|
238
|
+
| Average RMSD | 0.064 Å |
|
|
239
|
+
| Median RMSD | 0.011 Å |
|
|
240
|
+
| < 0.5 Å | 98.4% |
|
|
241
|
+
| < 0.3 Å | 94.4% |
|
|
242
|
+
|
|
243
|
+
### GDB-20 Ensemble (2000 molecules × 10 seeds vs 21 RDKit seeds)
|
|
244
|
+
|
|
245
|
+
| Metric | All-atom | Heavy-atom |
|
|
246
|
+
|--------|----------|------------|
|
|
247
|
+
| Avg RMSD | 0.035 Å | 0.018 Å |
|
|
248
|
+
| > 0.5 Å | 0.95% | **0.00%** |
|
|
249
|
+
|
|
250
|
+
---
|
|
251
|
+
|
|
252
|
+
## Module Overview
|
|
253
|
+
|
|
254
|
+
| Module | Description |
|
|
255
|
+
|--------|-------------|
|
|
256
|
+
| `sci_form::embed` | ETKDGv2 3D conformer generation from SMILES |
|
|
257
|
+
| `sci_form::embed_batch` | Parallel batch conformer generation (rayon) |
|
|
258
|
+
| `sci_form::parse` | SMILES → molecular graph |
|
|
259
|
+
| `sci_form::compute_charges` | Gasteiger-Marsili partial charges |
|
|
260
|
+
| `sci_form::compute_sasa` | Solvent-accessible surface area (SASA) |
|
|
261
|
+
| `sci_form::compute_population` | Mulliken & Löwdin population analysis (EHT) |
|
|
262
|
+
| `sci_form::compute_dipole` | Molecular dipole moment in Debye (EHT) |
|
|
263
|
+
| `sci_form::compute_esp` | Electrostatic potential grid (Mulliken charges) |
|
|
264
|
+
| `sci_form::compute_dos` | Density of states + PDOS (EHT orbital energies) |
|
|
265
|
+
| `sci_form::compute_rmsd` | RMSD after Kabsch alignment |
|
|
266
|
+
| `sci_form::compute_uff_energy` | UFF force field energy evaluation |
|
|
267
|
+
| `sci_form::create_unit_cell` | Periodic unit cell from lattice parameters |
|
|
268
|
+
| `sci_form::assemble_framework` | MOF-type framework assembly from SBUs |
|
|
269
|
+
|
|
270
|
+
### Sub-modules
|
|
271
|
+
|
|
272
|
+
| Module Path | Key API |
|
|
273
|
+
|-------------|---------|
|
|
274
|
+
| `sci_form::eht` | `solve_eht()`, `EhtResult`, `evaluate_orbital_on_grid_chunked()`, `marching_cubes()` |
|
|
275
|
+
| `sci_form::esp` | `compute_esp_grid_parallel()`, `esp_color_map()`, `esp_grid_to_colors()`, `export_cube()`, `read_cube()` |
|
|
276
|
+
| `sci_form::dos` | `compute_dos()`, `compute_pdos()`, `dos_mse()`, `export_dos_json()` |
|
|
277
|
+
| `sci_form::alignment` | `align_coordinates()`, `align_quaternion()`, `compute_rmsd()` |
|
|
278
|
+
| `sci_form::forcefield` | `build_uff_force_field()`, `Mmff94Builder::build()` |
|
|
279
|
+
| `sci_form::charges::gasteiger` | `gasteiger_marsili_charges()` |
|
|
280
|
+
| `sci_form::surface::sasa` | `compute_sasa()` |
|
|
281
|
+
| `sci_form::materials` | `UnitCell`, `Sbu`, `Topology`, `assemble_framework()` |
|
|
282
|
+
| `sci_form::transport` | `pack_batch_arrow()`, `ChunkedIterator`, `WorkerTask` |
|
|
283
|
+
|
|
284
|
+
---
|
|
285
|
+
|
|
286
|
+
## The Conformer Pipeline
|
|
287
|
+
|
|
288
|
+
sci-form implements ETKDGv2 (Experimental Torsion Knowledge Distance Geometry):
|
|
289
|
+
|
|
290
|
+
1. **SMILES Parsing** → Molecular graph with atoms, bonds, hybridization
|
|
291
|
+
2. **Bounds Matrix** → 1-2, 1-3, 1-4, and VdW distance bounds from topology
|
|
292
|
+
3. **Triangle Smoothing** → Floyd-Warshall triangle inequality enforcement
|
|
293
|
+
4. **Distance Picking** → Random distances from smoothed bounds (MinstdRand)
|
|
294
|
+
5. **Metric Matrix Embedding** → Eigendecomposition → 4D coordinates
|
|
295
|
+
6. **Bounds Force Field** → BFGS minimization in 4D to satisfy distance constraints
|
|
296
|
+
7. **Projection to 3D** → Drop lowest-variance dimension
|
|
297
|
+
8. **ETKDG 3D Refinement** → Force field with CSD torsion preferences (846 patterns)
|
|
298
|
+
9. **Validation** → Tetrahedral centers, planarity, double-bond geometry
|
|
299
|
+
|
|
300
|
+
See the [algorithm documentation](https://jigonzalez930209.github.io/sci-form/algorithm/overview) for mathematical derivations and diagrams.
|
|
301
|
+
|
|
302
|
+
---
|
|
303
|
+
|
|
304
|
+
## Building from Source
|
|
305
|
+
|
|
306
|
+
```bash
|
|
307
|
+
# Library + CLI
|
|
308
|
+
cargo build --release
|
|
309
|
+
|
|
310
|
+
# Python bindings
|
|
311
|
+
cd crates/python && pip install maturin && maturin develop --release
|
|
312
|
+
|
|
313
|
+
# WASM bindings
|
|
314
|
+
cd crates/wasm && wasm-pack build --target web --release
|
|
315
|
+
|
|
316
|
+
# With parallel feature
|
|
317
|
+
cargo build --release --features parallel
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
---
|
|
321
|
+
|
|
322
|
+
## Testing
|
|
323
|
+
|
|
324
|
+
```bash
|
|
325
|
+
# All unit tests
|
|
326
|
+
cargo test --lib
|
|
327
|
+
|
|
328
|
+
# Integration — diverse molecules (97.7% pass rate)
|
|
329
|
+
cargo test --release --test test_diverse_molecules -- --nocapture
|
|
330
|
+
|
|
331
|
+
# Integration — gradient correctness
|
|
332
|
+
cargo test --release --test test_gradient_check -- --nocapture
|
|
333
|
+
|
|
334
|
+
# Lint & format
|
|
335
|
+
cargo fmt --all -- --check
|
|
336
|
+
cargo clippy --all-targets -- -D warnings
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
---
|
|
340
|
+
|
|
341
|
+
## Releasing a New Version
|
|
342
|
+
|
|
343
|
+
Use the provided bump script. It updates all version strings, commits, tags, and pushes:
|
|
344
|
+
|
|
345
|
+
```bash
|
|
346
|
+
# Auto-increment patch (0.1.7 → 0.1.8)
|
|
347
|
+
./scripts/bump_version.sh
|
|
348
|
+
|
|
349
|
+
# Set a specific version
|
|
350
|
+
./scripts/bump_version.sh 0.2.0
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
This updates versions in:
|
|
354
|
+
- `Cargo.toml` (root lib)
|
|
355
|
+
- `crates/cli/Cargo.toml`
|
|
356
|
+
- `crates/python/Cargo.toml`
|
|
357
|
+
- `crates/wasm/Cargo.toml`
|
|
358
|
+
- `crates/python/pyproject.toml`
|
|
359
|
+
- `crates/wasm/pkg/package.json`
|
|
360
|
+
- `pkg/package.json` & `pkg-node/package.json`
|
|
361
|
+
|
|
362
|
+
Then creates a `vX.Y.Z` git tag, which triggers the [release workflow](.github/workflows/release.yml) to publish to **crates.io**, **PyPI**, and **npm** automatically.
|
|
363
|
+
|
|
364
|
+
**Required repository secrets:**
|
|
365
|
+
|
|
366
|
+
| Secret | Used for |
|
|
367
|
+
|--------|----------|
|
|
368
|
+
| `CARGO_REGISTRY_TOKEN` | Publishing to crates.io |
|
|
369
|
+
| `PYPI_API_TOKEN` | Publishing to PyPI (`sciforma`) |
|
|
370
|
+
| `NPM_TOKEN` | Publishing to npm (`sci-form-wasm`) — must be a **Granular Automation token** |
|
|
371
|
+
|
|
372
|
+
---
|
|
373
|
+
|
|
374
|
+
## License
|
|
375
|
+
|
|
376
|
+
MIT
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "sci-form-wasm",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"description": "WASM/TypeScript bindings for high-performance 3D molecular conformer generation",
|
|
5
|
-
"version": "0.4.
|
|
5
|
+
"version": "0.4.3",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
@@ -11,11 +11,14 @@
|
|
|
11
11
|
"files": [
|
|
12
12
|
"sci_form_wasm_bg.wasm",
|
|
13
13
|
"sci_form_wasm.js",
|
|
14
|
-
"sci_form_wasm.d.ts"
|
|
14
|
+
"sci_form_wasm.d.ts",
|
|
15
|
+
"snippets",
|
|
16
|
+
"README.md"
|
|
15
17
|
],
|
|
16
18
|
"main": "sci_form_wasm.js",
|
|
17
19
|
"types": "sci_form_wasm.d.ts",
|
|
18
20
|
"sideEffects": [
|
|
19
21
|
"./snippets/*"
|
|
20
|
-
]
|
|
21
|
-
|
|
22
|
+
],
|
|
23
|
+
"readme": "README.md"
|
|
24
|
+
}
|
package/sci_form_wasm_bg.wasm
CHANGED
|
Binary file
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright 2022 Google Inc. All Rights Reserved.
|
|
3
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
* you may not use this file except in compliance with the License.
|
|
5
|
+
* You may obtain a copy of the License at
|
|
6
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
8
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
9
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
10
|
+
* See the License for the specific language governing permissions and
|
|
11
|
+
* limitations under the License.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
// Note: we use `wasm_bindgen_worker_`-prefixed message types to make sure
|
|
15
|
+
// we can handle bundling into other files, which might happen to have their
|
|
16
|
+
// own `postMessage`/`onmessage` communication channels.
|
|
17
|
+
//
|
|
18
|
+
// If we didn't take that into the account, we could send much simpler signals
|
|
19
|
+
// like just `0` or whatever, but the code would be less resilient.
|
|
20
|
+
|
|
21
|
+
function waitForMsgType(target, type) {
|
|
22
|
+
return new Promise(resolve => {
|
|
23
|
+
target.addEventListener('message', function onMsg({ data }) {
|
|
24
|
+
if (data?.type !== type) return;
|
|
25
|
+
target.removeEventListener('message', onMsg);
|
|
26
|
+
resolve(data);
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
waitForMsgType(self, 'wasm_bindgen_worker_init').then(async ({ init, receiver }) => {
|
|
32
|
+
// # Note 1
|
|
33
|
+
// Our JS should have been generated in
|
|
34
|
+
// `[out-dir]/snippets/wasm-bindgen-rayon-[hash]/workerHelpers.js`,
|
|
35
|
+
// resolve the main module via `../../..`.
|
|
36
|
+
//
|
|
37
|
+
// This might need updating if the generated structure changes on wasm-bindgen
|
|
38
|
+
// side ever in the future, but works well with bundlers today. The whole
|
|
39
|
+
// point of this crate, after all, is to abstract away unstable features
|
|
40
|
+
// and temporary bugs so that you don't need to deal with them in your code.
|
|
41
|
+
//
|
|
42
|
+
// # Note 2
|
|
43
|
+
// This could be a regular import, but then some bundlers complain about
|
|
44
|
+
// circular deps.
|
|
45
|
+
//
|
|
46
|
+
// Dynamic import could be cheap if this file was inlined into the parent,
|
|
47
|
+
// which would require us just using `../../..` in `new Worker` below,
|
|
48
|
+
// but that doesn't work because wasm-pack unconditionally adds
|
|
49
|
+
// "sideEffects":false (see below).
|
|
50
|
+
//
|
|
51
|
+
// OTOH, even though it can't be inlined, it should be still reasonably
|
|
52
|
+
// cheap since the requested file is already in cache (it was loaded by
|
|
53
|
+
// the main thread).
|
|
54
|
+
const pkg = await import('../../..');
|
|
55
|
+
await pkg.default(init);
|
|
56
|
+
postMessage({ type: 'wasm_bindgen_worker_ready' });
|
|
57
|
+
pkg.wbg_rayon_start_worker(receiver);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
// Note: this is never used, but necessary to prevent a bug in Firefox
|
|
61
|
+
// (https://bugzilla.mozilla.org/show_bug.cgi?id=1702191) where it collects
|
|
62
|
+
// Web Workers that have a shared WebAssembly memory with the main thread,
|
|
63
|
+
// but are not explicitly rooted via a `Worker` instance.
|
|
64
|
+
//
|
|
65
|
+
// By storing them in a variable, we can keep `Worker` objects around and
|
|
66
|
+
// prevent them from getting GC-d.
|
|
67
|
+
let _workers;
|
|
68
|
+
|
|
69
|
+
export async function startWorkers(module, memory, builder) {
|
|
70
|
+
if (builder.numThreads() === 0) {
|
|
71
|
+
throw new Error(`num_threads must be > 0.`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const workerInit = {
|
|
75
|
+
type: 'wasm_bindgen_worker_init',
|
|
76
|
+
init: { module_or_path: module, memory },
|
|
77
|
+
receiver: builder.receiver()
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
_workers = await Promise.all(
|
|
81
|
+
Array.from({ length: builder.numThreads() }, async () => {
|
|
82
|
+
// Self-spawn into a new Worker.
|
|
83
|
+
//
|
|
84
|
+
// TODO: while `new URL('...', import.meta.url) becomes a semi-standard
|
|
85
|
+
// way to get asset URLs relative to the module across various bundlers
|
|
86
|
+
// and browser, ideally we should switch to `import.meta.resolve`
|
|
87
|
+
// once it becomes a standard.
|
|
88
|
+
//
|
|
89
|
+
// Note: we could use `../../..` as the URL here to inline workerHelpers.js
|
|
90
|
+
// into the parent entry instead of creating another split point -
|
|
91
|
+
// this would be preferable from optimization perspective -
|
|
92
|
+
// however, Webpack then eliminates all message handler code
|
|
93
|
+
// because wasm-pack produces "sideEffects":false in package.json
|
|
94
|
+
// unconditionally.
|
|
95
|
+
//
|
|
96
|
+
// The only way to work around that is to have side effect code
|
|
97
|
+
// in an entry point such as Worker file itself.
|
|
98
|
+
const worker = new Worker(new URL('./workerHelpers.js', import.meta.url), {
|
|
99
|
+
type: 'module'
|
|
100
|
+
});
|
|
101
|
+
worker.postMessage(workerInit);
|
|
102
|
+
await waitForMsgType(worker, 'wasm_bindgen_worker_ready');
|
|
103
|
+
return worker;
|
|
104
|
+
})
|
|
105
|
+
);
|
|
106
|
+
builder.build();
|
|
107
|
+
}
|