From d601fa92288e7dbb738baa7a505092be400d69fb Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Thu, 5 Nov 2026 12:08:19 +0000 Subject: [PATCH 1/2] Speed up scoring of RDKit MCS mappings. --- src/BioSimSpace/Align/_align.py | 189 ++++++++--------- .../Sandpit/Exscientia/Align/_align.py | 193 +++++++++--------- 2 files changed, 192 insertions(+), 190 deletions(-) diff --git a/src/BioSimSpace/Align/_align.py b/src/BioSimSpace/Align/_align.py index 884ba3ef..c843f3aa 100644 --- a/src/BioSimSpace/Align/_align.py +++ b/src/BioSimSpace/Align/_align.py @@ -2984,8 +2984,7 @@ def _score_rdkit_mappings( mapping, scores : ([dict], list) The ranked mappings and corresponding scores. """ - from sire.legacy import Maths as _SireMaths - from sire.legacy import Mol as _SireMol + import numpy as _np from .. import _isVerbose from .._Exceptions import AlignmentError as _AlignmentError @@ -3035,109 +3034,111 @@ def _score_rdkit_mappings( # Initialise a list of to hold the score for each mapping. scores = [] + # Atomic coordinates, in Angstrom. + def _coords(molecule): + return _np.array( + [ + [v.x().value(), v.y().value(), v.z().value()] + for v in molecule.property("coordinates").to_vector() + ] + ) + + coords0 = _coords(molecule0) + coords1 = _coords(molecule1) + # Whether there was a GSL alignment error. is_gsl_error = False + # Most pairs of matches repeat a mapping, since equivalent atoms appear in + # every order, so skip duplicates with a set before doing any work on them. + if len(matches0) == 0 or len(matches1) == 0: + matches0 = matches1 = [] + is_swapped = False + outer = _np.asarray(matches0, dtype=_np.int32) + inner = _np.asarray(matches1, dtype=_np.int32) + seen = set() + + if is_swapped: + # The molecule0 indices come from the inner matches. Sort each of them. + inner_order = _np.argsort(inner, axis=1) + inner_sorted = _np.take_along_axis(inner, inner_order, axis=1) + inner_keys = [row.tobytes() for row in inner_sorted] + # Loop over all matches from mol0. - for x in range(len(matches0)): - match0 = matches0[x] + for x in range(len(outer)): + if is_swapped: + # Keys are the sorted molecule0 indices, followed by the molecule1 + # indices that they map to. + images = outer[x][inner_order] + keys = [d + i.tobytes() for d, i in zip(inner_keys, images)] + else: + order = _np.argsort(outer[x]) + domain = outer[x][order] + images = inner[:, order] + prefix = domain.tobytes() + keys = [prefix + i.tobytes() for i in images] # Loop over all matches from mol1. - for y in range(len(matches1)): - match1 = matches1[y] - - # Initialise the mapping for this match. - mapping = {} + for y, key in enumerate(keys): + # This mapping has already been seen. + if key in seen: + continue + seen.add(key) + + if is_swapped: + mapping = dict(zip(inner_sorted[y].tolist(), images[y].tolist())) + else: + mapping = dict(zip(domain.tolist(), images[y].tolist())) - # Loop over all atoms in the match. - for i, idx0 in enumerate(match0): - idx1 = match1[i] + # Check that the mapping contains the pre-match. + is_valid = True + for idx0, idx1 in prematch.items(): + if idx0 not in mapping or mapping[idx0] != idx1: + is_valid = False + break + if not is_valid: + continue - # Add to the mapping. - if is_swapped: - mapping[idx1] = idx0 + # If there is only a single atom in the mapping and one molecule + # has one atom, e.g. an ion, then skip the alignment. + if len(mapping) == 1: + mappings.append(mapping) + scores.append(0.0) + continue + + c0 = coords0[list(mapping.keys())] + c1 = coords1[list(mapping.values())] + + # Rigidly align molecule0 to molecule1 based on the mapping, using the + # Kabsch algorithm. + if scoring_function == "RMSDALIGN": + c0 = c0 - c0.mean(axis=0) + c1 = c1 - c1.mean(axis=0) + try: + u, _, vt = _np.linalg.svd(c0.T @ c1) + except _np.linalg.LinAlgError as e: + is_gsl_error = True + gsl_exception = e else: - mapping[idx0] = idx1 + d = _np.sign(_np.linalg.det(u @ vt)) + c0 = c0 @ (u @ _np.diag([1.0, 1.0, d]) @ vt) + # Flexibly align molecule0 to molecule1 based on the mapping. + elif scoring_function == "RMSDFLEXALIGN": + molecule0 = flexAlign( + _Molecule(molecule0), + _Molecule(molecule1), + mapping, + property_map0=property_map0, + property_map1=property_map1, + )._sire_object + c0 = _coords(molecule0)[list(mapping.keys())] - mapping = dict(sorted(mapping.items())) - sire_mapping = { - _SireMol.AtomIdx(idx0): _SireMol.AtomIdx(idx1) - for idx0, idx1 in mapping.items() - } + # Append the mapping to the list. + mappings.append(mapping) - # This is a new mapping: - if mapping not in mappings: - # Check that the mapping contains the pre-match. - is_valid = True - for idx0, idx1 in prematch.items(): - # Pre-match isn't found, return to top of loop. - if idx0 not in mapping or mapping[idx0] != idx1: - is_valid = False - break - - if is_valid: - # If there is only a single atom in the mapping and one molecule - # has one atom, e.g. an ion, then skip the alignment. - if len(mapping) == 1: - mappings.append(mapping) - scores.append(0.0) - else: - # Rigidly align molecule0 to molecule1 based on the mapping. - if scoring_function == "RMSDALIGN": - try: - molecule0 = ( - molecule0.move() - .align( - molecule1, - _SireMol.AtomResultMatcher(sire_mapping), - ) - .molecule() - ) - except Exception as e: - if ( - "Could not calculate the single value decomposition" - in str(e) - ): - is_gsl_error = True - gsl_exception = e - else: - msg = ( - "Failed to align molecules when scoring based on mapping: %r" - % mapping - ) - if _isVerbose(): - raise _AlignmentError(msg) from e - else: - raise _AlignmentError(msg) from None - # Flexibly align molecule0 to molecule1 based on the mapping. - elif scoring_function == "RMSDFLEXALIGN": - molecule0 = flexAlign( - _Molecule(molecule0), - _Molecule(molecule1), - mapping, - property_map0=property_map0, - property_map1=property_map1, - )._sire_object - - # Append the mapping to the list. - mappings.append(mapping) - - # We now compute the RMSD between the coordinates of the matched atoms - # in molecule0 and molecule1. - - # Initialise lists to hold the coordinates. - c0 = [] - c1 = [] - - # Loop over each atom index in the map. - for idx0, idx1 in sire_mapping.items(): - # Append the coordinates of the matched atom in molecule0. - c0.append(molecule0.atom(idx0).property("coordinates")) - # Append the coordinates of atom in molecule1 to which it maps. - c1.append(molecule1.atom(idx1).property("coordinates")) - - # Compute the RMSD between the two sets of coordinates. - scores.append(_SireMaths.getRMSD(c0, c1)) + # Compute the RMSD between the coordinates of the matched atoms in + # molecule0 and molecule1. + scores.append(float(_np.sqrt(((c0 - c1) ** 2).sum(axis=1).mean()))) # No mappings were found. if len(mappings) == 0: diff --git a/src/BioSimSpace/Sandpit/Exscientia/Align/_align.py b/src/BioSimSpace/Sandpit/Exscientia/Align/_align.py index 430df202..3d24c43d 100644 --- a/src/BioSimSpace/Sandpit/Exscientia/Align/_align.py +++ b/src/BioSimSpace/Sandpit/Exscientia/Align/_align.py @@ -2076,8 +2076,7 @@ def _score_rdkit_mappings( mapping, scores : ([dict], list) The ranked mappings and corresponding scores. """ - from sire.legacy import Maths as _SireMaths - from sire.legacy import Mol as _SireMol + import numpy as _np from .. import _isVerbose from .._Exceptions import AlignmentError as _AlignmentError @@ -2127,109 +2126,111 @@ def _score_rdkit_mappings( # Initialise a list of to hold the score for each mapping. scores = [] + # Atomic coordinates, in Angstrom. + def _coords(molecule): + return _np.array( + [ + [v.x().value(), v.y().value(), v.z().value()] + for v in molecule.property("coordinates").to_vector() + ] + ) + + coords0 = _coords(molecule0) + coords1 = _coords(molecule1) + # Whether there was a GSL alignment error. is_gsl_error = False + # Most pairs of matches repeat a mapping, since equivalent atoms appear in + # every order, so skip duplicates with a set before doing any work on them. + if len(matches0) == 0 or len(matches1) == 0: + matches0 = matches1 = [] + is_swapped = False + outer = _np.asarray(matches0, dtype=_np.int32) + inner = _np.asarray(matches1, dtype=_np.int32) + seen = set() + + if is_swapped: + # The molecule0 indices come from the inner matches. Sort each of them. + inner_order = _np.argsort(inner, axis=1) + inner_sorted = _np.take_along_axis(inner, inner_order, axis=1) + inner_keys = [row.tobytes() for row in inner_sorted] + # Loop over all matches from mol0. - for x in range(len(matches0)): - match0 = matches0[x] + for x in range(len(outer)): + if is_swapped: + # Keys are the sorted molecule0 indices, followed by the molecule1 + # indices that they map to. + images = outer[x][inner_order] + keys = [d + i.tobytes() for d, i in zip(inner_keys, images)] + else: + order = _np.argsort(outer[x]) + domain = outer[x][order] + images = inner[:, order] + prefix = domain.tobytes() + keys = [prefix + i.tobytes() for i in images] # Loop over all matches from mol1. - for y in range(len(matches1)): - match1 = matches1[y] - - # Initialise the mapping for this match. - mapping = {} + for y, key in enumerate(keys): + # This mapping has already been seen. + if key in seen: + continue + seen.add(key) + + if is_swapped: + mapping = dict(zip(inner_sorted[y].tolist(), images[y].tolist())) + else: + mapping = dict(zip(domain.tolist(), images[y].tolist())) - # Loop over all atoms in the match. - for i, idx0 in enumerate(match0): - idx1 = match1[i] + # Check that the mapping contains the pre-match. + is_valid = True + for idx0, idx1 in prematch.items(): + if idx0 not in mapping or mapping[idx0] != idx1: + is_valid = False + break + if not is_valid: + continue - # Add to the mapping. - if is_swapped: - mapping[idx1] = idx0 + # If there is only a single atom in the mapping and one molecule + # has one atom, e.g. an ion, then skip the alignment. + if len(mapping) == 1: + mappings.append(mapping) + scores.append(0.0) + continue + + c0 = coords0[list(mapping.keys())] + c1 = coords1[list(mapping.values())] + + # Rigidly align molecule0 to molecule1 based on the mapping, using the + # Kabsch algorithm. + if scoring_function == "RMSDALIGN": + c0 = c0 - c0.mean(axis=0) + c1 = c1 - c1.mean(axis=0) + try: + u, _, vt = _np.linalg.svd(c0.T @ c1) + except _np.linalg.LinAlgError as e: + is_gsl_error = True + gsl_exception = e else: - mapping[idx0] = idx1 - - mapping = dict(sorted(mapping.items())) - sire_mapping = { - _SireMol.AtomIdx(idx0): _SireMol.AtomIdx(idx1) - for idx0, idx1 in mapping.items() - } - - # This is a new mapping: - if mapping not in mappings: - # Check that the mapping contains the pre-match. - is_valid = True - for idx0, idx1 in prematch.items(): - # Pre-match isn't found, return to top of loop. - if idx0 not in mapping or mapping[idx0] != idx1: - is_valid = False - break - - if is_valid: - # If there is only a single atom in the mapping and one molecule - # has one atom, e.g. an ion, then skip the alignment. - if len(mapping) == 1: - mappings.append(mapping) - scores.append(0.0) - else: - # Rigidly align molecule0 to molecule1 based on the mapping. - if scoring_function == "RMSDALIGN": - try: - molecule0 = ( - molecule0.move() - .align( - molecule1, - _SireMol.AtomResultMatcher(sire_mapping), - ) - .molecule() - ) - except Exception as e: - if ( - "Could not calculate the single value decomposition" - in str(e) - ): - is_gsl_error = True - gsl_exception = e - else: - msg = ( - "Failed to align molecules when scoring based on mapping: %r" - % mapping - ) - if _isVerbose(): - raise _AlignmentError(msg) from e - else: - raise _AlignmentError(msg) from None - # Flexibly align molecule0 to molecule1 based on the mapping. - elif scoring_function == "RMSDFLEXALIGN": - molecule0 = flexAlign( - _Molecule(molecule0), - _Molecule(molecule1), - mapping, - property_map0=property_map0, - property_map1=property_map1, - )._sire_object - - # Append the mapping to the list. - mappings.append(mapping) - - # We now compute the RMSD between the coordinates of the matched atoms - # in molecule0 and molecule1. - - # Initialise lists to hold the coordinates. - c0 = [] - c1 = [] - - # Loop over each atom index in the map. - for idx0, idx1 in sire_mapping.items(): - # Append the coordinates of the matched atom in molecule0. - c0.append(molecule0.atom(idx0).property("coordinates")) - # Append the coordinates of atom in molecule1 to which it maps. - c1.append(molecule1.atom(idx1).property("coordinates")) - - # Compute the RMSD between the two sets of coordinates. - scores.append(_SireMaths.getRMSD(c0, c1)) + d = _np.sign(_np.linalg.det(u @ vt)) + c0 = c0 @ (u @ _np.diag([1.0, 1.0, d]) @ vt) + # Flexibly align molecule0 to molecule1 based on the mapping. + elif scoring_function == "RMSDFLEXALIGN": + molecule0 = flexAlign( + _Molecule(molecule0), + _Molecule(molecule1), + mapping, + property_map0=property_map0, + property_map1=property_map1, + )._sire_object + c0 = _coords(molecule0)[list(mapping.keys())] + + # Append the mapping to the list. + mappings.append(mapping) + + # Compute the RMSD between the coordinates of the matched atoms in + # molecule0 and molecule1. + scores.append(float(_np.sqrt(((c0 - c1) ** 2).sum(axis=1).mean()))) # No mappings were found. if len(mappings) == 0: From 491642f8dfba5899f204d428c89d866d8f7c6ee6 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Thu, 5 Nov 2026 12:23:48 +0000 Subject: [PATCH 2/2] Add brute-force regression test for RDKit mapping scoring. --- tests/Align/test_align.py | 96 ++++++++++++++++++++ tests/Sandpit/Exscientia/Align/test_align.py | 96 ++++++++++++++++++++ 2 files changed, 192 insertions(+) diff --git a/tests/Align/test_align.py b/tests/Align/test_align.py index 3f9850b7..eefb23d9 100644 --- a/tests/Align/test_align.py +++ b/tests/Align/test_align.py @@ -1689,3 +1689,99 @@ def test_network_links_file(network_ligands, tmp_path): assert (1, 4) in edges assert scores[edges.index((1, 4))] == pytest.approx(0.5) + + +@pytest.mark.parametrize( + "smiles0, smiles1", + [ + ("c1ccccc1", "Cc1ccccc1"), + ("Cc1ccccc1", "c1ccccc1"), + ("C1CCCCC1", "C1CCCC1"), + ("CCO", "CCCO"), + ("CC(C)(C)O", "CC(C)(C)C"), + ], +) +@pytest.mark.parametrize("scoring_function", ["RMSD", "RMSDALIGN"]) +@pytest.mark.parametrize("use_prematch", [False, True]) +def test_score_rdkit_mappings(smiles0, smiles1, scoring_function, use_prematch): + # Check the scored mappings against a brute-force reference: every unique + # mapping from every pair of substructure matches, each scored independently, + # using Horn's quaternion method for the aligned RMSD. + import numpy as np + from rdkit import Chem + from rdkit.Chem import rdFMCS + from sire.legacy.Maths import getRMSD + + from BioSimSpace.Align._align import _score_rdkit_mappings + + max_matches = 50 + + mol0 = BSS.Convert.smiles(smiles0) + mol1 = BSS.Convert.smiles(smiles1) + rdmol0 = BSS.Convert.toRDKit(mol0) + rdmol1 = BSS.Convert.toRDKit(mol1) + mcs = rdFMCS.FindMCS([rdmol0, rdmol1], **BSS.Align.defaultMCSOptions()) + smarts = Chem.MolFromSmarts(mcs.smartsString) + + matches0 = rdmol0.GetSubstructMatches( + smarts, uniquify=False, maxMatches=max_matches, useChirality=False + ) + matches1 = rdmol1.GetSubstructMatches( + smarts, uniquify=False, maxMatches=max_matches, useChirality=False + ) + expected = {tuple(sorted(zip(m0, m1))) for m0 in matches0 for m1 in matches1} + + prematch = {} + if use_prematch: + idx0, idx1 = sorted(expected)[0][0] + prematch = {idx0: idx1} + expected = {m for m in expected if (idx0, idx1) in m} + + mappings, scores = _score_rdkit_mappings( + mol0._sire_object, + mol1._sire_object, + rdmol0, + rdmol1, + smarts, + prematch, + scoring_function, + max_matches, + {}, + {}, + ) + + found = [tuple(sorted(mapping.items())) for mapping in mappings] + assert len(found) == len(set(found)) + assert set(found) == expected + + scores = [score.value() for score in scores] + assert scores == sorted(scores) + + def xyz(coords): + return np.array([[c.x().value(), c.y().value(), c.z().value()] for c in coords]) + + def aligned_rmsd(x, y): + x = x - x.mean(axis=0) + y = y - y.mean(axis=0) + (sxx, sxy, sxz), (syx, syy, syz), (szx, szy, szz) = x.T @ y + k = np.array( + [ + [sxx + syy + szz, syz - szy, szx - sxz, sxy - syx], + [syz - szy, sxx - syy - szz, sxy + syx, szx + sxz], + [szx - sxz, sxy + syx, -sxx + syy - szz, syz + szy], + [sxy - syx, szx + sxz, syz + szy, -sxx - syy + szz], + ] + ) + msd = ((x**2).sum() + (y**2).sum() - 2 * np.linalg.eigvalsh(k)[-1]) / len(x) + return np.sqrt(max(msd, 0.0)) + + sire0 = mol0._sire_object + sire1 = mol1._sire_object + for mapping, score in zip(mappings, scores): + c0 = [sire0.atom(AtomIdx(i)).property("coordinates") for i in mapping] + c1 = [sire1.atom(AtomIdx(j)).property("coordinates") for j in mapping.values()] + if scoring_function == "RMSDALIGN": + reference = aligned_rmsd(xyz(c0), xyz(c1)) + else: + reference = getRMSD(c0, c1) + assert score == pytest.approx(reference, abs=1e-6) diff --git a/tests/Sandpit/Exscientia/Align/test_align.py b/tests/Sandpit/Exscientia/Align/test_align.py index 05a59994..e7d9fdeb 100644 --- a/tests/Sandpit/Exscientia/Align/test_align.py +++ b/tests/Sandpit/Exscientia/Align/test_align.py @@ -1247,3 +1247,99 @@ def test_network_links_file(network_ligands, tmp_path): assert (1, 4) in edges assert scores[edges.index((1, 4))] == pytest.approx(0.5) + + +@pytest.mark.parametrize( + "smiles0, smiles1", + [ + ("c1ccccc1", "Cc1ccccc1"), + ("Cc1ccccc1", "c1ccccc1"), + ("C1CCCCC1", "C1CCCC1"), + ("CCO", "CCCO"), + ("CC(C)(C)O", "CC(C)(C)C"), + ], +) +@pytest.mark.parametrize("scoring_function", ["RMSD", "RMSDALIGN"]) +@pytest.mark.parametrize("use_prematch", [False, True]) +def test_score_rdkit_mappings(smiles0, smiles1, scoring_function, use_prematch): + # Check the scored mappings against a brute-force reference: every unique + # mapping from every pair of substructure matches, each scored independently, + # using Horn's quaternion method for the aligned RMSD. + import numpy as np + from rdkit import Chem + from rdkit.Chem import rdFMCS + from sire.legacy.Maths import getRMSD + + from BioSimSpace.Sandpit.Exscientia.Align._align import _score_rdkit_mappings + + max_matches = 50 + + mol0 = BSS.Convert.smiles(smiles0) + mol1 = BSS.Convert.smiles(smiles1) + rdmol0 = BSS.Convert.toRDKit(mol0) + rdmol1 = BSS.Convert.toRDKit(mol1) + mcs = rdFMCS.FindMCS([rdmol0, rdmol1], **BSS.Align.defaultMCSOptions()) + smarts = Chem.MolFromSmarts(mcs.smartsString) + + matches0 = rdmol0.GetSubstructMatches( + smarts, uniquify=False, maxMatches=max_matches, useChirality=False + ) + matches1 = rdmol1.GetSubstructMatches( + smarts, uniquify=False, maxMatches=max_matches, useChirality=False + ) + expected = {tuple(sorted(zip(m0, m1))) for m0 in matches0 for m1 in matches1} + + prematch = {} + if use_prematch: + idx0, idx1 = sorted(expected)[0][0] + prematch = {idx0: idx1} + expected = {m for m in expected if (idx0, idx1) in m} + + mappings, scores = _score_rdkit_mappings( + mol0._sire_object, + mol1._sire_object, + rdmol0, + rdmol1, + smarts, + prematch, + scoring_function, + max_matches, + {}, + {}, + ) + + found = [tuple(sorted(mapping.items())) for mapping in mappings] + assert len(found) == len(set(found)) + assert set(found) == expected + + scores = [score.value() for score in scores] + assert scores == sorted(scores) + + def xyz(coords): + return np.array([[c.x().value(), c.y().value(), c.z().value()] for c in coords]) + + def aligned_rmsd(x, y): + x = x - x.mean(axis=0) + y = y - y.mean(axis=0) + (sxx, sxy, sxz), (syx, syy, syz), (szx, szy, szz) = x.T @ y + k = np.array( + [ + [sxx + syy + szz, syz - szy, szx - sxz, sxy - syx], + [syz - szy, sxx - syy - szz, sxy + syx, szx + sxz], + [szx - sxz, sxy + syx, -sxx + syy - szz, syz + szy], + [sxy - syx, szx + sxz, syz + szy, -sxx - syy + szz], + ] + ) + msd = ((x**2).sum() + (y**2).sum() - 2 * np.linalg.eigvalsh(k)[-1]) / len(x) + return np.sqrt(max(msd, 0.0)) + + sire0 = mol0._sire_object + sire1 = mol1._sire_object + for mapping, score in zip(mappings, scores): + c0 = [sire0.atom(AtomIdx(i)).property("coordinates") for i in mapping] + c1 = [sire1.atom(AtomIdx(j)).property("coordinates") for j in mapping.values()] + if scoring_function == "RMSDALIGN": + reference = aligned_rmsd(xyz(c0), xyz(c1)) + else: + reference = getRMSD(c0, c1) + assert score == pytest.approx(reference, abs=1e-6)