Download libs/adaptive/clustering.py from QPromaQ/Docking_project: direct link, hf CLI and curl.
- Browser
- Download file 1.56 kB
-
https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/libs/adaptive/clustering.py
- Command line
-
hf download hf://datasets/QPromaQ/Docking_project/libs/adaptive/clustering.py
-
curl -L -o clustering.py https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/libs/adaptive/clustering.py
1.56 kB
| from __future__ import annotations | |
| from typing import Dict, Iterable, List, Sequence | |
| import numpy as np | |
| from rdkit import DataStructs | |
| from rdkit.Chem import rdchem | |
| from rdkit.ML.Cluster import Butina | |
| def _np_to_explicit_bitvect(fp: np.ndarray) -> DataStructs.ExplicitBitVect: | |
| bitvect = DataStructs.ExplicitBitVect(fp.shape[0]) | |
| on_bits = np.where(fp > 0)[0] | |
| for idx in on_bits: | |
| bitvect.SetBit(int(idx)) | |
| return bitvect | |
| def cluster_ligands_butina( | |
| ligand_ids: Sequence[str], | |
| fingerprints: Sequence[np.ndarray], | |
| cutoff: float = 0.35, | |
| ) -> Dict[str, int]: | |
| """Cluster ligands with Butina on Tanimoto distance over Morgan fingerprints.""" | |
| if not ligand_ids: | |
| return {} | |
| if len(ligand_ids) != len(fingerprints): | |
| raise ValueError("ligand_ids and fingerprints must have same length") | |
| fp_bv = [_np_to_explicit_bitvect(np.asarray(fp, dtype=int)) for fp in fingerprints] | |
| dists: List[float] = [] | |
| for i in range(1, len(fp_bv)): | |
| sims = DataStructs.BulkTanimotoSimilarity(fp_bv[i], fp_bv[:i]) | |
| dists.extend([1.0 - x for x in sims]) | |
| clusters = Butina.ClusterData(dists, len(fp_bv), cutoff, isDistData=True) | |
| mapping: Dict[str, int] = {} | |
| for c_idx, cluster in enumerate(clusters): | |
| for member in cluster: | |
| mapping[ligand_ids[member]] = c_idx | |
| # Ensure all ligands map to a cluster, even edge cases. | |
| for idx, ligand_id in enumerate(ligand_ids): | |
| mapping.setdefault(ligand_id, max(mapping.values(), default=-1) + idx + 1) | |
| return mapping | |