Skip to content

Instantly share code, notes, and snippets.

@johnmay
Created March 16, 2021 20:27
Show Gist options
  • Save johnmay/ddbf002d28bd190fb5a4d8cc20566dfc to your computer and use it in GitHub Desktop.
Save johnmay/ddbf002d28bd190fb5a4d8cc20566dfc to your computer and use it in GitHub Desktop.
CDK SMARTS Expr API
IChemObjectBuilder bldr = SilentChemObjectBuilder.getInstance();
IAtomContainer mol = new QueryAtomContainer(bldr);
if (!Smarts.parse(mol, "[C,N;H0,H1+]-*", Smarts.FLAVOR_LOOSE)) {
System.err.println("ERROR - " + Smarts.getLastErrorMesg());
System.err.println(Smarts.getLastErrorLocation());
return;
}
QueryAtom qatom1 = (QueryAtom) mol.getAtom(0); // instanceof for safety
Expr expr = qatom1.getExpression();
System.err.println(expr); // AND(OR(ALIPHATIC_ELEMENT=6,ALIPHATIC_ELEMENT=7),OR(TOTAL_H_COUNT=0,AND(TOTAL_H_COUNT=1,FORMAL_CHARGE=1)))
if (expr.type() == Expr.Type.AND) {
System.err.println("left=" + expr.left());
System.err.println("rght=" + expr.right());
}
if (expr.type() == Expr.Type.ALIPHATIC_ELEMENT) {
System.err.println("Aliphatic Element=" + expr.value());
}
// you can also build up expressions using the API and write them out as SMARTS
Expr expr2 = new Expr(Expr.Type.ELEMENT, 17).and(new Expr(Expr.Type.DEGREE, 3));
System.err.println(Smarts.generateAtom(expr2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment