fpembed 0.1.0__tar.gz
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.
- fpembed-0.1.0/LICENSE +21 -0
- fpembed-0.1.0/PKG-INFO +20 -0
- fpembed-0.1.0/README.md +374 -0
- fpembed-0.1.0/pyproject.toml +40 -0
- fpembed-0.1.0/setup.cfg +4 -0
- fpembed-0.1.0/src/fpembed/__init__.py +32 -0
- fpembed-0.1.0/src/fpembed/compression.py +154 -0
- fpembed-0.1.0/src/fpembed/compression_blockwise.py +105 -0
- fpembed-0.1.0/src/fpembed/compression_projection.py +181 -0
- fpembed-0.1.0/src/fpembed/generator.py +348 -0
- fpembed-0.1.0/src/fpembed/hashing.py +48 -0
- fpembed-0.1.0/src/fpembed/py.typed +1 -0
- fpembed-0.1.0/src/fpembed/smiles_utils.py +63 -0
- fpembed-0.1.0/src/fpembed.egg-info/PKG-INFO +20 -0
- fpembed-0.1.0/src/fpembed.egg-info/SOURCES.txt +25 -0
- fpembed-0.1.0/src/fpembed.egg-info/dependency_links.txt +1 -0
- fpembed-0.1.0/src/fpembed.egg-info/requires.txt +13 -0
- fpembed-0.1.0/src/fpembed.egg-info/top_level.txt +1 -0
- fpembed-0.1.0/tests/test_cache.py +357 -0
- fpembed-0.1.0/tests/test_compression.py +249 -0
- fpembed-0.1.0/tests/test_compression_blockwise.py +128 -0
- fpembed-0.1.0/tests/test_compression_projection.py +197 -0
- fpembed-0.1.0/tests/test_fingerprints.py +509 -0
- fpembed-0.1.0/tests/test_generator.py +579 -0
- fpembed-0.1.0/tests/test_hashing.py +146 -0
- fpembed-0.1.0/tests/test_properties.py +371 -0
- fpembed-0.1.0/tests/test_smiles_utils.py +122 -0
fpembed-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mikhail Markovskii
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
fpembed-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fpembed
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Generalized fingerprint embedding library
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: rdkit==2026.3.1
|
|
9
|
+
Requires-Dist: numpy==2.2.6
|
|
10
|
+
Requires-Dist: selfies==1.0.2
|
|
11
|
+
Requires-Dist: scikit-fingerprints==2.0.0
|
|
12
|
+
Provides-Extra: app
|
|
13
|
+
Requires-Dist: nicegui>=3.8.0; extra == "app"
|
|
14
|
+
Requires-Dist: optuna>=3.1.0; extra == "app"
|
|
15
|
+
Requires-Dist: pyyaml>=6.0; extra == "app"
|
|
16
|
+
Requires-Dist: altair>=5.0; extra == "app"
|
|
17
|
+
Requires-Dist: pandas>=1.5.2; extra == "app"
|
|
18
|
+
Requires-Dist: scikit-learn>=1.2.0; extra == "app"
|
|
19
|
+
Requires-Dist: tqdm>=4.64.1; extra == "app"
|
|
20
|
+
Dynamic: license-file
|
fpembed-0.1.0/README.md
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
# FPembed - Generalized Molecular Fingerprint Embeddings
|
|
2
|
+
|
|
3
|
+
A lightweight Python package for generating compressed molecular fingerprint embeddings, backed by [scikit-fingerprints](https://github.com/scikit-fingerprints/scikit-fingerprints). Supports six binary fingerprint types through a single unified class.
|
|
4
|
+
|
|
5
|
+
FPembed compresses standard molecular fingerprints using weighted binary masking, producing compact float vectors suitable for machine-learning models. The package accepts SMILES, SELFIES, and RDKit Mol objects as input.
|
|
6
|
+
|
|
7
|
+
The concept of compressing molecular fingerprints via weighted binary masking was originally introduced for Morgan fingerprints in the eMFP paper:
|
|
8
|
+
|
|
9
|
+
> Nuñez-Andrade, E. A., Vidal-Daza, I., Gomez-Bombarelli, R., Ryan, J. W., & Martin-Martinez, F. J. (2025).
|
|
10
|
+
> Embedded Morgan Fingerprints for more efficient molecular property predictions with machine learning.
|
|
11
|
+
> *ChemRxiv* (preprint). https://doi.org/10.26434/chemrxiv-2025-6hfp8
|
|
12
|
+
|
|
13
|
+
```bibtex
|
|
14
|
+
@article{nunez2025emfp,
|
|
15
|
+
author = {Nu{\~n}ez-Andrade, Emilio A. and Vidal-Daza, Isaac and Gomez-Bombarelli, Rafael and Ryan, James W. and Martin-Martinez, Francisco J.},
|
|
16
|
+
title = {Embedded {Morgan} Fingerprints for more efficient molecular property predictions with machine learning},
|
|
17
|
+
journal = {ChemRxiv},
|
|
18
|
+
year = {2025},
|
|
19
|
+
doi = {10.26434/chemrxiv-2025-6hfp8},
|
|
20
|
+
note = {Preprint}
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Original concept repository: [MMLabCodes/eMFP](https://github.com/MMLabCodes/eMFP)
|
|
25
|
+
|
|
26
|
+
## Supported Fingerprint Types
|
|
27
|
+
|
|
28
|
+
| Type | `fp_type` | Type-specific params |
|
|
29
|
+
|------|-----------|---------------------|
|
|
30
|
+
| Extended Connectivity (ECFP) | `ecfp` | `radius` (default 2) |
|
|
31
|
+
| Atom Pair | `atom_pair` | `min_distance` (1), `max_distance` (30) |
|
|
32
|
+
| Topological Torsion | `topological_torsion` | `torsion_atom_count` (4) |
|
|
33
|
+
| RDKit | `rdkit` | `min_path` (1), `max_path` (7) |
|
|
34
|
+
| Layered | `layered` | `min_path` (1), `max_path` (7) |
|
|
35
|
+
| Pattern | `pattern` | (none) |
|
|
36
|
+
|
|
37
|
+
## Compression Methods
|
|
38
|
+
|
|
39
|
+
FPembed supports six compression methods, selectable via the `method` parameter on `EmbeddedFingerprintGenerator`. The default is `geometric`.
|
|
40
|
+
|
|
41
|
+
### Method Reference
|
|
42
|
+
|
|
43
|
+
| Method (`method` value) | Category | `method_params` | Dynamic Range / Distance Preservation | Complexity |
|
|
44
|
+
|-------------------------|----------|-----------------|---------------------------------------|------------|
|
|
45
|
+
| `geometric` | block-wise | `interleave` (bool) | 65,536:1 dynamic range | O(L) |
|
|
46
|
+
| `linear` | block-wise | `interleave` (bool) | S:1 dynamic range | O(L) |
|
|
47
|
+
| `log` | block-wise | `interleave` (bool) | ~4.1:1 dynamic range | O(L) |
|
|
48
|
+
| `uniform` | block-wise | `interleave` (bool) | 1:1 (mean pooling) | O(L) |
|
|
49
|
+
| `hadamard` | global | `seed` (int) | orthogonal projection | O(L log L) |
|
|
50
|
+
| `random_projection` | global | `seed` (int) + `sparse` (bool) | JL distance preservation | O(L·D) |
|
|
51
|
+
|
|
52
|
+
### The `method` Parameter
|
|
53
|
+
|
|
54
|
+
Pass `method` to the Generator constructor to select a compression strategy.
|
|
55
|
+
|
|
56
|
+
### Method-Specific Parameters (`method_params`)
|
|
57
|
+
|
|
58
|
+
- **Block-wise methods** (`geometric`, `linear`, `log`, `uniform`): accept `interleave` (bool, default `False`). When `True`, bits are assigned to blocks by stride (`bit[i] -> block[i % n_blocks]`) instead of contiguous partitioning, breaking hash clustering artifacts.
|
|
59
|
+
- **`hadamard`**: accepts `seed` (int, default `42`). Controls the random sign flips applied before the Fast Walsh-Hadamard Transform.
|
|
60
|
+
- **`random_projection`**: accepts `seed` (int, default `42`) and `sparse` (bool, default `False`). The `sparse` option uses the Achlioptas variant with approximately 2/3 zero entries for faster computation at comparable quality.
|
|
61
|
+
|
|
62
|
+
Seed-based methods (`hadamard`, `random_projection`) are fully deterministic given the same seed and NumPy version. The default seed is `42`.
|
|
63
|
+
|
|
64
|
+
### Code Examples
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from fpembed import EmbeddedFingerprintGenerator
|
|
68
|
+
|
|
69
|
+
# Geometric (default)
|
|
70
|
+
gen = EmbeddedFingerprintGenerator(fp_type="ecfp", fp_size=2048, compression=16, fp_params={"radius": 2})
|
|
71
|
+
|
|
72
|
+
# Linear weights
|
|
73
|
+
gen = EmbeddedFingerprintGenerator(fp_type="ecfp", fp_size=2048, compression=16, fp_params={"radius": 2}, method="linear")
|
|
74
|
+
|
|
75
|
+
# Logarithmic weights
|
|
76
|
+
gen = EmbeddedFingerprintGenerator(fp_type="ecfp", fp_size=2048, compression=16, fp_params={"radius": 2}, method="log")
|
|
77
|
+
|
|
78
|
+
# Uniform weights (mean pooling)
|
|
79
|
+
gen = EmbeddedFingerprintGenerator(fp_type="ecfp", fp_size=2048, compression=16, fp_params={"radius": 2}, method="uniform")
|
|
80
|
+
|
|
81
|
+
# Hadamard (SRHT)
|
|
82
|
+
gen = EmbeddedFingerprintGenerator(fp_type="ecfp", fp_size=2048, compression=16, fp_params={"radius": 2}, method="hadamard")
|
|
83
|
+
|
|
84
|
+
# Random projection
|
|
85
|
+
gen = EmbeddedFingerprintGenerator(fp_type="ecfp", fp_size=2048, compression=16, fp_params={"radius": 2}, method="random_projection")
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Bit-interleaving with a block-wise method:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
gen = EmbeddedFingerprintGenerator(
|
|
92
|
+
fp_type="ecfp", fp_size=2048, compression=16,
|
|
93
|
+
fp_params={"radius": 2}, method="linear",
|
|
94
|
+
method_params={"interleave": True}
|
|
95
|
+
)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Standalone `compress_fingerprint` with a non-default method:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from fpembed import compress_fingerprint
|
|
102
|
+
import numpy as np
|
|
103
|
+
|
|
104
|
+
fp = np.random.randint(0, 2, size=2048).astype(np.float64)
|
|
105
|
+
emb = compress_fingerprint(fp, size=16, method="hadamard", method_params={"seed": 42})
|
|
106
|
+
print(emb.shape) # (1, 128)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Choosing a Method
|
|
110
|
+
|
|
111
|
+
Block-wise methods (`geometric`, `linear`, `log`, `uniform`) are fast (O(L)) and simple - use them when speed matters or compression ratios are modest. Among these, `geometric` preserves the most dynamic range while `uniform` treats all bits equally (mean pooling). Global projection methods (`hadamard`, `random_projection`) mix information across all input bits, which helps retain more information at high compression ratios. `hadamard` is efficient (O(L log L)) and requires power-of-2 fingerprint sizes; `random_projection` offers the strongest theoretical distance-preservation guarantees (Johnson-Lindenstrauss lemma) at the cost of O(L·D) complexity.
|
|
112
|
+
|
|
113
|
+
### Performance Characteristics
|
|
114
|
+
|
|
115
|
+
All methods produce the same output dimensionality (D = L / compression) but differ in speed and memory:
|
|
116
|
+
|
|
117
|
+
| Method | Speed | Precomputed Memory | Best For |
|
|
118
|
+
|--------|------------------------------------------|--------------------------------------|----------|
|
|
119
|
+
| Block-wise (all four) | Fastest - single vectorized einsum, O(L) | Negligible (C-length weight vector) | Default choice; large batches |
|
|
120
|
+
| Random projection | Fast - BLAS matmul, O(L·D) | DxL matrix (~2 MB for L=2048, D=128) | Best theoretical guarantees (JL lemma) |
|
|
121
|
+
| Hadamard (SRHT) | Slowest - pure-Python FWHT, O(L log L) | L-length sign vector (~16 KB) | Small-scale experiments; future optimization |
|
|
122
|
+
|
|
123
|
+
Block-wise methods are ~2–5x faster than random projection and orders of magnitude faster than Hadamard in practice. Random projection's memory cost grows quadratically with fingerprint size.
|
|
124
|
+
|
|
125
|
+
## Why Use Embedded Fingerprints?
|
|
126
|
+
|
|
127
|
+
Predictive accuracy is one axis of comparison between raw and embedded fingerprints - and the gap can be narrow, especially on large datasets where raw fingerprints have enough data to exploit all 2048 bits directly. However, accuracy is not the only metric that matters. Embedded fingerprints offer substantial, guaranteed advantages on every operational dimension: storage, speed, memory, and sample efficiency.
|
|
128
|
+
|
|
129
|
+
The core argument is not "embedded fingerprints are always more accurate" but rather "embedded fingerprints achieve comparable accuracy at a fraction of the computational cost."
|
|
130
|
+
|
|
131
|
+
### Storage Size
|
|
132
|
+
|
|
133
|
+
This is the most clear-cut advantage. The compression ratio is deterministic and independent of dataset, model, or method:
|
|
134
|
+
|
|
135
|
+
| Representation | Per-molecule (L=2048) | Per-molecule (L=4096) | 100K molecules (L=2048) |
|
|
136
|
+
|---|---|---|---|
|
|
137
|
+
| Raw binary FP (float64) | 16 KB | 32 KB | ~1.6 GB |
|
|
138
|
+
| Embedded, C=16 (float64) | 1 KB | 2 KB | ~100 MB |
|
|
139
|
+
| Embedded, C=32 (float64) | 512 B | 1 KB | ~50 MB |
|
|
140
|
+
|
|
141
|
+
A 16x reduction at C=16 applies unconditionally - it does not depend on the dataset, the ML model, or the compression method chosen. This matters for storing precomputed fingerprints on disk or in a database, transmitting embeddings over a network, loading datasets into memory for training, and caching repeated lookups via the built-in LRU cache.
|
|
142
|
+
|
|
143
|
+
### ML Training and Inference Speed
|
|
144
|
+
|
|
145
|
+
The downstream ML model operates on the feature vector. Fewer features means faster training and prediction:
|
|
146
|
+
|
|
147
|
+
- **Tree-based models (Random Forest, XGBoost)**: Feature splitting cost is proportional to the number of features. Going from 2048 to 128 features means each tree split considers ~16x fewer candidates. For hyperparameter searches (e.g., Optuna with hundreds of trials), this compounds into significant wall-clock savings.
|
|
148
|
+
- **Neural networks**: The first dense layer's weight matrix shrinks from `(2048 x hidden)` to `(128 x hidden)` - 16x fewer parameters and 16x fewer multiply-adds per forward pass.
|
|
149
|
+
- **Distance-based methods (k-NN, similarity search)**: Pairwise distance computation is O(N² x D). Reducing D from 2048 to 128 gives a direct 16x speedup.
|
|
150
|
+
|
|
151
|
+
### Memory During ML Training
|
|
152
|
+
|
|
153
|
+
During model training, the feature matrix for N=100K molecules occupies `(100000, 2048)` float64 = ~1.6 GB for raw fingerprints, versus `(100000, 128)` = ~100 MB for embedded. Tree-based models create internal copies and histograms proportional to feature count. GPU-based models benefit from smaller input tensors that allow larger batch sizes and better hardware utilization.
|
|
154
|
+
|
|
155
|
+
### Compression Overhead
|
|
156
|
+
|
|
157
|
+
The compression step itself is negligible for block-wise methods (~1 ms per 1000 molecules). The total pipeline cost is:
|
|
158
|
+
|
|
159
|
+
- **Raw**: `skfp generation time`
|
|
160
|
+
- **Embedded**: `skfp generation time + ~1 ms per 1000 molecules` (block-wise)
|
|
161
|
+
|
|
162
|
+
The downstream ML speedup from 128 vs 2048 features far exceeds this overhead.
|
|
163
|
+
|
|
164
|
+
### Sample Efficiency
|
|
165
|
+
|
|
166
|
+
High-dimensional spaces (2048 binary features) suffer from the curse of dimensionality - distances become less meaningful and models need exponentially more data to fill the space. Compressing to 128 dense, information-rich features acts as a form of regularization. Empirically, embedded fingerprints reach good predictive performance with fewer training samples than raw fingerprints. This is particularly valuable when labeled molecular data is scarce or expensive to obtain.
|
|
167
|
+
|
|
168
|
+
### Summary of Advantages
|
|
169
|
+
|
|
170
|
+
| Metric | Raw FP (L=2048) | Embedded FP (D=128) | Advantage |
|
|
171
|
+
|---|-------------------------|---------------------------------|-----------------------|
|
|
172
|
+
| Feature matrix memory (100K mols) | ~1.6 GB | ~100 MB | 16x smaller |
|
|
173
|
+
| Per-molecule storage | 16 KB | 1 KB | 16x smaller |
|
|
174
|
+
| Tree model training speed | Baseline | ~16x fewer split candidates | Faster |
|
|
175
|
+
| Neural net first-layer params | 2048 x H | 128 x H | 16x fewer |
|
|
176
|
+
| Pairwise distance computation | O(N² x 2048) | O(N² x 128) | 16x faster |
|
|
177
|
+
| Small-dataset accuracy | Baseline | Often superior (regularization) | Better generalization |
|
|
178
|
+
| Large-dataset accuracy | Slightly higher ceiling | Comparable | Marginal tradeoff |
|
|
179
|
+
|
|
180
|
+
The choice between raw and embedded fingerprints is a classic accuracy-vs-efficiency tradeoff. Embedded fingerprints sacrifice a small amount of information for dramatic improvements in storage, speed, and memory - making them the practical default for most molecular ML workflows.
|
|
181
|
+
|
|
182
|
+
## Project Structure
|
|
183
|
+
|
|
184
|
+
```
|
|
185
|
+
fpembed/
|
|
186
|
+
├── src/fpembed/ # pip-distributable package
|
|
187
|
+
│ ├── __init__.py
|
|
188
|
+
│ ├── generator.py # EmbeddedFingerprintGenerator
|
|
189
|
+
│ ├── compression.py # compress_fingerprint (orchestrator)
|
|
190
|
+
│ ├── compression_blockwise.py # block-wise weight schemes
|
|
191
|
+
│ ├── compression_projection.py # Hadamard SRHT + random projection
|
|
192
|
+
│ ├── smiles_utils.py # parse_smiles, canonicalize_smiles
|
|
193
|
+
│ ├── hashing.py # fp_params_hash
|
|
194
|
+
│ └── py.typed # PEP 561 marker
|
|
195
|
+
├── examples/
|
|
196
|
+
│ ├── quickstart.ipynb # usage notebook
|
|
197
|
+
│ ├── datasets/ # molecular datasets (RedDB, NFA, QM9)
|
|
198
|
+
│ └── nicegui_app/ # NiceGUI demo application
|
|
199
|
+
├── pyproject.toml
|
|
200
|
+
├── environment.yml
|
|
201
|
+
└── README.md
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
## Installation
|
|
205
|
+
|
|
206
|
+
Install the core package (rdkit, numpy, selfies, scikit-fingerprints):
|
|
207
|
+
|
|
208
|
+
```bash
|
|
209
|
+
pip install fpembed
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
Install with demo app dependencies (nicegui, optuna, pandas, scikit-learn, etc.):
|
|
213
|
+
|
|
214
|
+
```bash
|
|
215
|
+
pip install fpembed[app]
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
For development (editable install):
|
|
219
|
+
|
|
220
|
+
```bash
|
|
221
|
+
pip install -e .
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
### Conda Environment
|
|
225
|
+
|
|
226
|
+
A full conda environment is provided for reproducibility:
|
|
227
|
+
|
|
228
|
+
```bash
|
|
229
|
+
conda env create -f environment.yml
|
|
230
|
+
conda activate fpembed
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
This installs all dependencies and the `fpembed` package in editable mode.
|
|
234
|
+
|
|
235
|
+
## Quick Start
|
|
236
|
+
|
|
237
|
+
### Single Molecule (SMILES)
|
|
238
|
+
|
|
239
|
+
```python
|
|
240
|
+
from fpembed import EmbeddedFingerprintGenerator
|
|
241
|
+
|
|
242
|
+
gen = EmbeddedFingerprintGenerator(
|
|
243
|
+
fp_type="ecfp", fp_size=2048, compression=16, fp_params={"radius": 2}
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
# Generate compressed fingerprint from SMILES
|
|
247
|
+
emb = gen.GetFingerprintFromSmiles("CCO")
|
|
248
|
+
print(emb.shape) # (128,)
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
### Different Fingerprint Types
|
|
252
|
+
|
|
253
|
+
```python
|
|
254
|
+
# Atom Pair fingerprint
|
|
255
|
+
gen_ap = EmbeddedFingerprintGenerator(
|
|
256
|
+
fp_type="atom_pair", fp_size=2048, compression=16,
|
|
257
|
+
fp_params={"min_distance": 1, "max_distance": 30}
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
# Topological Torsion fingerprint
|
|
261
|
+
gen_tt = EmbeddedFingerprintGenerator(
|
|
262
|
+
fp_type="topological_torsion", fp_size=2048, compression=16,
|
|
263
|
+
fp_params={"torsion_atom_count": 4}
|
|
264
|
+
)
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### Single Molecule (SELFIES)
|
|
268
|
+
|
|
269
|
+
```python
|
|
270
|
+
emb = gen.GetFingerprintFromSelfies("[C][C][O]")
|
|
271
|
+
print(emb.shape) # (128,)
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
### Batch Processing
|
|
275
|
+
|
|
276
|
+
```python
|
|
277
|
+
smiles_list = ["CCO", "c1ccccc1", "CC(=O)O", "invalid_smiles"]
|
|
278
|
+
|
|
279
|
+
embeddings, invalid_indices = gen.GetFingerprintsFromSmiles(smiles_list)
|
|
280
|
+
print(embeddings.shape) # (3, 128) - 3 valid molecules
|
|
281
|
+
print(invalid_indices) # [3] - index of invalid SMILES
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
### Raw Fingerprint (No Compression)
|
|
285
|
+
|
|
286
|
+
```python
|
|
287
|
+
gen_raw = EmbeddedFingerprintGenerator(
|
|
288
|
+
fp_type="ecfp", fp_size=2048, compression=None, fp_params={"radius": 2}
|
|
289
|
+
)
|
|
290
|
+
fp = gen_raw.GetFingerprintFromSmiles("CCO")
|
|
291
|
+
print(fp.shape) # (2048,)
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
### Standalone Compression Function
|
|
295
|
+
|
|
296
|
+
```python
|
|
297
|
+
import numpy as np
|
|
298
|
+
from fpembed import compress_fingerprint
|
|
299
|
+
|
|
300
|
+
fp = np.random.randint(0, 2, size=2048).astype(np.float64)
|
|
301
|
+
emb = compress_fingerprint(fp, size=16)
|
|
302
|
+
print(emb.shape) # (1, 128)
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
### Parameter Hashing
|
|
306
|
+
|
|
307
|
+
```python
|
|
308
|
+
from fpembed import fp_params_hash
|
|
309
|
+
|
|
310
|
+
h = fp_params_hash("ecfp", {"radius": 2})
|
|
311
|
+
print(h) # 16-char hex string, stable across sessions
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
### Caching for Repeated Lookups
|
|
315
|
+
|
|
316
|
+
```python
|
|
317
|
+
gen = EmbeddedFingerprintGenerator(
|
|
318
|
+
fp_type="ecfp", fp_size=2048, compression=16,
|
|
319
|
+
fp_params={"radius": 2}, cache_size=1024
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
# First call computes and caches
|
|
323
|
+
emb = gen.GetFingerprintFromSmiles("CCO")
|
|
324
|
+
|
|
325
|
+
# Second call returns cached result
|
|
326
|
+
emb2 = gen.GetFingerprintFromSmiles("CCO")
|
|
327
|
+
|
|
328
|
+
print(gen.cache_info()) # CacheInfo(hits=1, misses=1, maxsize=1024, currsize=1)
|
|
329
|
+
gen.clear_cache()
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
## Running the Demo App
|
|
333
|
+
|
|
334
|
+
The NiceGUI demo app provides an interactive UI for optimizing fingerprint embeddings. The examples are not included in the `pip install fpembed` package - clone the repository to access them.
|
|
335
|
+
|
|
336
|
+
**Warning**: the demo app uses a cache to speed up the calculations. Please provide at least 100 GB of free disk space before the evaluation. The obsolete cache file `examples/nicegui_app/cache.db` can be deleted manually afterward.
|
|
337
|
+
|
|
338
|
+
```bash
|
|
339
|
+
git clone https://github.com/Sciencealone/fpembed.git
|
|
340
|
+
cd fpembed
|
|
341
|
+
|
|
342
|
+
# Install the core package with app dependencies
|
|
343
|
+
pip install fpembed[app]
|
|
344
|
+
|
|
345
|
+
# Or install pinned versions from requirements.txt
|
|
346
|
+
pip install -r requirements.txt
|
|
347
|
+
|
|
348
|
+
# Run the NiceGUI app
|
|
349
|
+
cd examples/nicegui_app
|
|
350
|
+
python app.py
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
A Jupyter notebook with quick-start examples is also available at `examples/quickstart.ipynb`.
|
|
354
|
+
|
|
355
|
+
## Datasets
|
|
356
|
+
|
|
357
|
+
The following datasets are included in `examples/datasets/` (obtained from their original sources):
|
|
358
|
+
|
|
359
|
+
| Dataset | DOI |
|
|
360
|
+
|---|---|
|
|
361
|
+
| RedDB Database | https://doi.org/10.1038/s41597-022-01832-2 |
|
|
362
|
+
| Non-Fullerene Acceptors Database | https://doi.org/10.1016/j.joule.2017.10.006 |
|
|
363
|
+
| QM9 Database | https://doi.org/10.1038/sdata.2014.22 |
|
|
364
|
+
|
|
365
|
+
## License
|
|
366
|
+
|
|
367
|
+
This project is licensed under the terms of the MIT open source license. Please refer to the [LICENSE](LICENSE) for the full terms.
|
|
368
|
+
|
|
369
|
+
## AI disclosure
|
|
370
|
+
|
|
371
|
+
AI usage during project development is declared in [aidecl.yaml](aidecl.yaml) following the [AI Declaration Format](https://ai-declaration.org/).
|
|
372
|
+
|
|
373
|
+
## Support
|
|
374
|
+
This project is provided as-is, and may be updated over time. If you have questions, please open an issue.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "fpembed"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Generalized fingerprint embedding library"
|
|
9
|
+
requires-python = ">=3.9"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"rdkit==2026.3.1",
|
|
12
|
+
"numpy==2.2.6",
|
|
13
|
+
"selfies==1.0.2",
|
|
14
|
+
"scikit-fingerprints==2.0.0",
|
|
15
|
+
]
|
|
16
|
+
license = "MIT"
|
|
17
|
+
license-files = ["LICENSE*"]
|
|
18
|
+
|
|
19
|
+
[project.optional-dependencies]
|
|
20
|
+
app = [
|
|
21
|
+
"nicegui>=3.8.0",
|
|
22
|
+
"optuna>=3.1.0",
|
|
23
|
+
"pyyaml>=6.0",
|
|
24
|
+
"altair>=5.0",
|
|
25
|
+
"pandas>=1.5.2",
|
|
26
|
+
"scikit-learn>=1.2.0",
|
|
27
|
+
"tqdm>=4.64.1",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[tool.setuptools.packages.find]
|
|
31
|
+
where = ["src"]
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.package-data]
|
|
34
|
+
fpembed = ["py.typed"]
|
|
35
|
+
|
|
36
|
+
[tool.pytest.ini_options]
|
|
37
|
+
markers = [
|
|
38
|
+
"fast: marks tests as fast (< 5 seconds)",
|
|
39
|
+
"slow: marks tests as slow (property-based, 5-60 seconds)",
|
|
40
|
+
]
|
fpembed-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""FPembed — Generalized fingerprint embedding library backed by scikit-fingerprints.
|
|
2
|
+
|
|
3
|
+
Provides :class:`EmbeddedFingerprintGenerator` for generating compressed
|
|
4
|
+
molecular fingerprints from SMILES, SELFIES, or RDKit Mol objects, plus
|
|
5
|
+
the standalone :func:`compress_fingerprint` compression function and
|
|
6
|
+
lightweight SMILES helpers.
|
|
7
|
+
|
|
8
|
+
Example:
|
|
9
|
+
>>> from fpembed import EmbeddedFingerprintGenerator
|
|
10
|
+
>>> gen = EmbeddedFingerprintGenerator(
|
|
11
|
+
... fp_type="ecfp", fp_size=2048, compression=16, fp_params={"radius": 2}
|
|
12
|
+
... )
|
|
13
|
+
>>> emb = gen.GetFingerprintFromSmiles("CCO")
|
|
14
|
+
>>> emb.shape
|
|
15
|
+
(128,)
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from fpembed.generator import EmbeddedFingerprintGenerator
|
|
19
|
+
from fpembed.compression import compress_fingerprint
|
|
20
|
+
from fpembed.smiles_utils import parse_smiles, canonicalize_smiles
|
|
21
|
+
from fpembed.hashing import fp_params_hash
|
|
22
|
+
|
|
23
|
+
__version__ = "0.1.0"
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"EmbeddedFingerprintGenerator",
|
|
27
|
+
"compress_fingerprint",
|
|
28
|
+
"parse_smiles",
|
|
29
|
+
"canonicalize_smiles",
|
|
30
|
+
"fp_params_hash",
|
|
31
|
+
"__version__",
|
|
32
|
+
]
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Fingerprint compression orchestrator.
|
|
2
|
+
|
|
3
|
+
Routes ``compress_fingerprint()`` calls to the appropriate sub-module
|
|
4
|
+
based on the ``method`` parameter. Supports block-wise weight schemes
|
|
5
|
+
(geometric, linear, log, uniform) and global projection methods
|
|
6
|
+
(hadamard, random_projection).
|
|
7
|
+
|
|
8
|
+
The default behavior (``method="geometric"``, no ``method_params``)
|
|
9
|
+
produces output identical to the original implementation.
|
|
10
|
+
|
|
11
|
+
Public API
|
|
12
|
+
----------
|
|
13
|
+
compress_fingerprint : Compress a fingerprint array.
|
|
14
|
+
_is_power_of_two : Check whether an integer is a power of two.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
import numpy.typing as npt
|
|
23
|
+
|
|
24
|
+
from fpembed.compression_blockwise import compress_blockwise
|
|
25
|
+
from fpembed.compression_projection import (
|
|
26
|
+
build_rp_matrix,
|
|
27
|
+
build_srht_signs,
|
|
28
|
+
compress_hadamard,
|
|
29
|
+
compress_random_projection,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
_BLOCKWISE_METHODS = {"geometric", "linear", "log", "uniform"}
|
|
33
|
+
_PROJECTION_METHODS = {"hadamard", "random_projection"}
|
|
34
|
+
_ALL_METHODS = _BLOCKWISE_METHODS | _PROJECTION_METHODS
|
|
35
|
+
|
|
36
|
+
_VALID_PARAMS: dict[str, set[str]] = {
|
|
37
|
+
"geometric": {"interleave"},
|
|
38
|
+
"linear": {"interleave"},
|
|
39
|
+
"log": {"interleave"},
|
|
40
|
+
"uniform": {"interleave"},
|
|
41
|
+
"hadamard": {"seed"},
|
|
42
|
+
"random_projection": {"seed", "sparse"},
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
_DEFAULT_SEED = 42
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _validate_method_params(method: str, method_params: dict) -> None:
|
|
49
|
+
"""Validate method_params keys and value types for the given method."""
|
|
50
|
+
valid_keys = _VALID_PARAMS[method]
|
|
51
|
+
unrecognized = set(method_params) - valid_keys
|
|
52
|
+
if unrecognized:
|
|
53
|
+
raise ValueError(
|
|
54
|
+
f"Unrecognized method_params keys {unrecognized} for method "
|
|
55
|
+
f"'{method}'. Valid keys: {valid_keys}"
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
if "seed" in method_params:
|
|
59
|
+
seed = method_params["seed"]
|
|
60
|
+
if not isinstance(seed, int) or isinstance(seed, bool) or seed < 0:
|
|
61
|
+
raise ValueError(
|
|
62
|
+
f"seed must be a non-negative integer, got {seed!r}"
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
if "sparse" in method_params:
|
|
66
|
+
sparse = method_params["sparse"]
|
|
67
|
+
if not isinstance(sparse, bool):
|
|
68
|
+
raise ValueError(
|
|
69
|
+
f"sparse must be a boolean, got {type(sparse).__name__}"
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
if "interleave" in method_params:
|
|
73
|
+
interleave = method_params["interleave"]
|
|
74
|
+
if not isinstance(interleave, bool):
|
|
75
|
+
raise ValueError(
|
|
76
|
+
f"interleave must be a boolean, got {type(interleave).__name__}"
|
|
77
|
+
)
|
|
78
|
+
if interleave and method in _PROJECTION_METHODS:
|
|
79
|
+
raise ValueError(
|
|
80
|
+
f"interleave is not applicable to method '{method}'"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def compress_fingerprint(
|
|
85
|
+
vector: npt.NDArray[Any],
|
|
86
|
+
size: int,
|
|
87
|
+
*,
|
|
88
|
+
method: str = "geometric",
|
|
89
|
+
method_params: dict | None = None,
|
|
90
|
+
) -> npt.NDArray[np.float64]:
|
|
91
|
+
"""Compress a binary fingerprint into a dense float embedding.
|
|
92
|
+
|
|
93
|
+
Parameters
|
|
94
|
+
----------
|
|
95
|
+
vector : ndarray
|
|
96
|
+
Input fingerprint — ``(L,)`` or ``(N, L)``.
|
|
97
|
+
size : int
|
|
98
|
+
Compression factor.
|
|
99
|
+
method : str
|
|
100
|
+
Compression method name.
|
|
101
|
+
method_params : dict or None
|
|
102
|
+
Method-specific parameters.
|
|
103
|
+
|
|
104
|
+
Returns
|
|
105
|
+
-------
|
|
106
|
+
ndarray of float64
|
|
107
|
+
Compressed embedding.
|
|
108
|
+
|
|
109
|
+
Raises
|
|
110
|
+
------
|
|
111
|
+
ValueError
|
|
112
|
+
If *size* is invalid, *method* is unsupported, or *method_params*
|
|
113
|
+
contains invalid keys/values.
|
|
114
|
+
"""
|
|
115
|
+
if not isinstance(size, int) or size <= 0:
|
|
116
|
+
raise ValueError(
|
|
117
|
+
"Size must be a positive integer. Try size = 16, or size = 32"
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
if method not in _ALL_METHODS:
|
|
121
|
+
raise ValueError(
|
|
122
|
+
f"Unsupported method '{method}'. "
|
|
123
|
+
f"Supported: {', '.join(sorted(_ALL_METHODS))}"
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
if method_params is None:
|
|
127
|
+
method_params = {}
|
|
128
|
+
|
|
129
|
+
_validate_method_params(method, method_params)
|
|
130
|
+
|
|
131
|
+
# Block-wise methods
|
|
132
|
+
if method in _BLOCKWISE_METHODS:
|
|
133
|
+
interleave = method_params.get("interleave", False)
|
|
134
|
+
return compress_blockwise(vector, size, scheme=method, interleave=interleave)
|
|
135
|
+
|
|
136
|
+
# Projection methods
|
|
137
|
+
fp_len = vector.shape[-1] if vector.ndim > 1 else vector.shape[0]
|
|
138
|
+
output_dim = fp_len // size
|
|
139
|
+
|
|
140
|
+
if method == "hadamard":
|
|
141
|
+
seed = method_params.get("seed", _DEFAULT_SEED)
|
|
142
|
+
signs = build_srht_signs(fp_len, seed)
|
|
143
|
+
return compress_hadamard(vector, size, signs)
|
|
144
|
+
|
|
145
|
+
# method == "random_projection"
|
|
146
|
+
seed = method_params.get("seed", _DEFAULT_SEED)
|
|
147
|
+
sparse = method_params.get("sparse", False)
|
|
148
|
+
matrix = build_rp_matrix(fp_len, output_dim, seed, sparse)
|
|
149
|
+
return compress_random_projection(vector, matrix)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _is_power_of_two(n: int) -> bool:
|
|
153
|
+
"""Return True if *n* is a positive power of two."""
|
|
154
|
+
return n > 0 and (n & (n - 1)) == 0
|