File size: 1,563 Bytes
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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