Coverage for SynRBL/SynMCSImputer/utils.py: 72%
54 statements
« prev ^ index » next coverage.py v7.4.3, created at 2024-04-11 11:17 +0200
« prev ^ index » next coverage.py v7.4.3, created at 2024-04-11 11:17 +0200
1import rdkit.Chem.rdmolfiles as rdmolfiles
2import rdkit.Chem.rdchem as rdchem
3import rdkit.Chem.rdmolops as rdmolops
6class AtomTracker:
7 """
8 A class to track atoms through the merge process.
9 """
11 def __init__(self, indices):
12 """
13 A class to track atoms through the merge process. After instantiation
14 call the add_atoms method to initialize the tracker with the atom
15 objects.
17 Arguments:
18 indices (list[int]): A list of atom indices to track.
19 """
20 self.__track_dict = {}
21 if indices is not None:
22 for idx in indices:
23 self.__track_dict[str(idx)] = {}
25 def add_atoms(self, mol, offset=0):
26 """
27 Add atom objects to the tracker. This is a necessary initialization
28 step.
30 Arguments:
31 mol (rdkit.Chem.Mol): The molecule in which to track atoms.
32 offset (int, optional): The atom index offset.
33 """
34 atoms = mol.GetAtoms()
35 for k in self.__track_dict.keys():
36 self.__track_dict[k]["atom"] = atoms[int(k) + offset]
38 def to_dict(self):
39 """
40 Convert the tracker into a mapping dictionary.
42 Returns:
43 dict: A dictionary where keys are the old indices and the values
44 represent the atom indices in the new molecule.
45 """
46 sealed_dict = {}
47 for k in self.__track_dict.keys():
48 sealed_dict[k] = self.__track_dict[k]["atom"].GetIdx()
49 return sealed_dict
52def is_carbon_balanced(reaction_smiles):
53 def _cnt_C(mol):
54 return len([a for a in mol.GetAtoms() if a.GetSymbol() == "C"])
56 smiles_token = reaction_smiles.split(">>")
57 reactant_smiles = smiles_token[0]
58 product_smiles = smiles_token[1]
59 reactant = rdmolfiles.MolFromSmiles(reactant_smiles)
60 product = rdmolfiles.MolFromSmiles(product_smiles)
61 reactant_Cs = _cnt_C(reactant)
62 product_Cs = _cnt_C(product)
63 return reactant_Cs == product_Cs
66class InvalidAtomDict(Exception):
67 """
68 Exception if the atom dictionary is invalid.
69 """
71 def __init__(self, expected, actual, index, smiles):
72 """
73 Exception if the atom dictionary is invalid.
75 Arguments:
76 expected (str): The expected atom at the given index.
77 actual (str): The actual atom at the index.
78 index (int): The atom index in the molecule.
79 smiles (str): The SMILES representation of the molecule.
80 """
81 super().__init__(
82 (
83 "Atom dict is invalid for molecule '{}'. "
84 + "Expected atom '{}' at index {} but found '{}'."
85 ).format(smiles, expected, index, actual)
86 )
89def check_atom_dict(mol, atom_dict):
90 """
91 Check if the atom dict matches the actual molecule. If the atom dictionary
92 is not valid a InvalidAtomDict exception is raised.
94 Arguments:
95 mol (rdkit.Chem.Mol): The molecule on which the atom dictionary is
96 checked.
97 atom_dict (dict, list[dict]): The atom dictionary or a list of atom
98 dictionaries to check on the molecule.
99 """
100 if isinstance(atom_dict, list):
101 for e in atom_dict:
102 check_atom_dict(mol, e)
103 elif isinstance(atom_dict, dict):
104 sym, idx = next(iter(atom_dict.items()))
105 actual_sym = mol.GetAtomWithIdx(idx).GetSymbol()
106 if actual_sym != sym:
107 raise InvalidAtomDict(sym, actual_sym, idx, rdmolfiles.MolToSmiles(mol))
108 else:
109 raise ValueError("atom_dict must be either a list or a dict.")
112def merge_two_mols(mol1, mol2, idx1, idx2, bond_type, mol1_track=None, mol2_track=None):
113 """
114 Merge two molecules. How the molecules are merge is defined by merge rules.
116 Arguments:
117 mol1 (rdkit.Chem.Mol): First molecule to merge.
118 mol2 (rdkit.Chem.Mol): Second molecule to merge.
119 idx1 (int): Atom index in mol1 where the new bond is formed.
120 idx2 (int): Atom index in mol2 where the new bond is formed.
121 mol1_track (list[int], optional): A list of atom indices in mol1 that
122 should be tracked during merging. The index mapping is part of the
123 result with key 'aam1'.
124 mol2_track (list[int], optional): A list of atom indices in mol2 that
125 should be tracked during merging. The index mapping is part of the
126 result with key 'aam2'.
128 Returns:
129 dict: A dictionary with the merged molecule at key 'mol' and optional
130 atom index mappings at 'aam1' and 'aam2'.
131 """
132 mol1_tracker = AtomTracker(mol1_track)
133 mol2_tracker = AtomTracker(mol2_track)
135 mol = rdchem.RWMol(rdmolops.CombineMols(mol1, mol2))
137 mol2_offset = len(mol1.GetAtoms())
138 mol1_tracker.add_atoms(mol)
139 mol2_tracker.add_atoms(mol, offset=mol2_offset)
141 atom1 = mol.GetAtoms()[idx1]
142 atom2 = mol.GetAtoms()[mol2_offset + idx2]
144 if bond_type is not None:
145 mol.AddBond(atom1.GetIdx(), atom2.GetIdx(), order=bond_type)
147 return {
148 "mol": mol,
149 "aam1": mol1_tracker.to_dict(),
150 "aam2": mol2_tracker.to_dict(),
151 }