Skip to content

Instantly share code, notes, and snippets.

@johnmay
Created October 11, 2018 18:17
Show Gist options
  • Save johnmay/12797a89f4186bc7da881f1f4a706671 to your computer and use it in GitHub Desktop.
Save johnmay/12797a89f4186bc7da881f1f4a706671 to your computer and use it in GitHub Desktop.
Align CDK molecule to substructure
public static void alignMoleculeToSubstructure(IAtomContainer mol,
IAtomContainer sub,
boolean fixBonds) throws CDKException {
Pattern substructurePattern = Pattern.findSubstructure(sub);
Mappings mappings = substructurePattern.matchAll(mol);
Set<IAtom> fixedAtoms = new HashSet<IAtom>();
Set<IBond> fixedBonds = new HashSet<IBond>();
for (Map<IChemObject, IChemObject> map : mappings.toAtomBondMap()) {
GeometryUtil.scaleMolecule(sub,
1.5/GeometryUtil.getBondLengthMedian(sub));
for (IChemObject substructureObject : map.keySet()) {
IChemObject targetObject = map.get(substructureObject);
if (targetObject instanceof IAtom) {
//set the target atom's position to that of the substructure atom and add it to the fixed atom list
IAtom targetAtom = (IAtom) targetObject;
IAtom substructureAtom = (IAtom) substructureObject;
targetAtom.setPoint2d(new Point2d(substructureAtom.getPoint2d()));
fixedAtoms.add(targetAtom);
} else if (fixBonds) {
//only check bonds if needed
if (targetObject instanceof IBond) {
//add the target bond to the fixed bond list
IBond targetBond = (IBond) substructureObject;
fixedBonds.add(targetBond);
}
}
}
//only align to the first matching substructure
break;
}
//generate coordinates for the molecule
StructureDiagramGenerator sdg = new StructureDiagramGenerator();
sdg.setMolecule(mol, false, fixedAtoms, fixedBonds);
sdg.generateCoordinates();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment