Developer:Cpp Tutorial

From Open Babel
Revision as of 12:58, 26 June 2007 by Baoilleach (Talk | contribs) (mol.h not obmol.h)

Jump to: navigation, search

This tutorial is aimed at developers looking to use Open Babel as a core chemistry library. It will focus on the object-oriented application programmers' interface (API). There is also documentation on the full API. Although Open Babel is written in C++, it also has bindings to Perl and Python programming languages. See the developer tutorial for more on using those programming languages.

Please feel free to comment on or improve this tutorial by e-mailing to openbabel-devel

Output Molecular Weight for a Multi-Molecule SDF File

Let's say we want to print out the molecular weights of every molecule in an SD file. Why? Well, we might want to plot a histogram of the distribution, or see whether the average of the distribution is significantly different (in the statistical sense) compared to another SD file.

#include <iostream>

#include <openbabel/obconversion.h>
#include <openbabel/mol.h>

int main(int argc,char **argv)
  OBConversion obconversion;
  OBMol mol;

  bool notatend = obconversion.ReadFile(&mol,"../xsaa.sdf");
  while (notatend)
    std::cout << "Molecular Weight: " << mol.GetMolWt() << std::endl;
    notatend = obconversion.Read(&mol);


Properties from SMARTS Matches

Let's say that we want to get the average bond length or dihedral angle over particular types of atoms in a large molecule. So we'll use SMARTS to match a set of atoms and loop through the matches. The following example does this for sulfur-carbon-carbon-sulfur dihedral angles in a polymer and the carbon-carbon bond lengths between the monomer units:

  OBMol obMol;
  OBBond *b1;
  OBConversion obConversion;
  OBFormat *inFormat;
  OBSmartsPattern smarts;

  string filename;
  vector< vector <int> > maplist;
  vector< vector <int> >::iterator matches;
  double dihedral, bondLength;

  for (int i = 1; i < argc; i++)
      filename = argv[i];
      inFormat = obConversion.FormatFromExt(filename.c_str());
      obConversion.ReadFile(&obMol, filename);
      if (smarts.Match(obMol))
	  dihedral = 0.0;
          bondLength = 0.0;
	  maplist = smarts.GetUMapList();
	  for (matches = maplist.begin(); matches != maplist.end(); matches++)
	      dihedral += fabs(obMol.GetTorsion((*matches)[0],
              b1 = obMol.GetBond((*matches)[1], (*matches)[2]);
              bondLength += b1->GetLength();
	  cout << filename << ": Average Dihedral " << dihedral / maplist.size()
	       << " Average Bond Length " << bondLength / maplist.size()
	       << " over " << maplist.size() <<  " matches\n";