Saturday, June 18, 2011

Open-source Cheminformatics (computational chemistry) libraries

I’ve needed to generate images (jpeg/png) of existing molecules/compounds and have been looking for available java-based chem. libraries to use. I finally decided to test out JOELib and CDK. First of all here is a sample of the respective outputs:

JOELib outputCDK output

Kind of obvious which one I will choose, but I thought it would be nice to post the code of how these two were setup. The notable reader will notice that in one I use the SDF file/format and in the other the SMILES. This is just how I coded this, but both work with either/or.

First the JOELib code:


Molecule mol2 = new BasicConformerMolecule();
ByteArrayInputStream inStream = new ByteArrayInputStream(BYTES FROM MY SDF FILE);
BasicReader in = new BasicReader(inStream, "SDF");
in.readNext(mol2);
in.close();

Mol2Image viewer = Mol2Image.instance();
BufferedImage img = viewer.mol2image(mol2);
ImageIO.write(img, "png", new File("molecule_joe.png"));

Now the CDK code:


int WIDTH = 200;
int HEIGHT = 200;

// the draw area and the image should be the same size
Rectangle drawArea = new Rectangle(WIDTH, HEIGHT);
Image image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance());
IMolecule molecule = sp.parseSmiles(MY SMILES STRING);
StructureDiagramGenerator sdg = new StructureDiagramGenerator();
sdg.setMolecule(molecule);
sdg.generateCoordinates();
molecule = sdg.getMolecule();

// generators make the image elements
List generators = new ArrayList();
generators.add(new BasicBondGenerator());
generators.add(new BasicAtomGenerator());

// the renderer needs to have a toolkit-specific font manager
Renderer renderer = new Renderer(generators, new AWTFontManager());

// the call to 'setup' only needs to be done on the first paint
renderer.setup(molecule, drawArea);

// paint the background
Graphics2D g2 = (Graphics2D)image.getGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, WIDTH, HEIGHT);

// the paint method also needs a toolkit-specific renderer
renderer.paintMolecule(molecule, new AWTDrawVisitor(g2), drawArea, true);

ImageIO.write((RenderedImage)image, "PNG", new File("molecule_cdk.png"));