[Python] Why does ReplaceSubstructs() always replace the last C atom?

Discussão em 'Python' iniciado por Stack, Julho 29, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use ReplaceSubstructs() function to combine two SMILES string together by replacing a carbon (C) atom in the first molucule with second molecule. However, no matter what c_options I pick, the RDKit always replace the first or last C atom, and the indices of the atoms also seem to get shuffled.

    Here is my code:

    from rdkit import Chem

    def combine_smile(smile1, smile2, c_options=1):
    mol1 = Chem.MolFromSmiles(smile1) mol2 = Chem.MolFromSmiles(smile2)
    if mol1 is None or mol2 is None:
    raise ValueError("One or both SMILES strings are invalid.")

    index_mol1 = mol_with_atom_index(mol1)

    combined_mol = Chem.ReplaceSubstructs(index_mol1, Chem.MolFromSmarts("[CH3]"), mol2)[c_options]
    combined_smiles = Chem.MolToSmiles(combined_mol)

    print(combined_smiles)

    def mol_with_atom_index( mol ):
    atoms = mol.GetNumAtoms() for idx in range( atoms ): mol.GetAtomWithIdx( idx ).SetProp( 'molAtomMapNumber', str( mol.GetAtomWithIdx( idx ).GetIdx() ) )
    return mol

    if name == "main":
    mol1_smiles = "CC(C)(C)Cl"
    mol2_smiles = "CN(C)C"

    combine_smile(mol1_smiles, mol2_smiles)


    Output:

    CN(C)C[C:1]([CH3:2])([CH3:3])[Cl:4] # for c_options=0
    CN(C)C[C:1]([CH3:0])([CH3:3])[Cl:4] # for c_options=1
    CN(C)C[C:1]([CH3:0])([CH3:2])[Cl:4] # for c_options=2


    Desired Output:

    CN(C)C[C:1]([CH3:2])([CH3:3])[Cl:4] # for c_options=0
    [CH3:0][C:1](CN(C)C)([CH3:3])[Cl:4] # for c_options=1
    [CH3:0][C:1]([CH3:2])(CN(C)C)[Cl:4] # for c_options=2

    Continue reading...

Compartilhe esta Página