20.5 Calculating Molecular Weight of a Compound

The following example demonstrates how to use OEChem's periodic table functions to perform the common task of determining the molecular weight of a compound. Average molecular weight is commonly used in filtering (Lipinski's Rules) and as a descriptor in QSAR. The use of inaccurate values for molecular weight in these applications may help explain their limited success.

#include "oechem.h"
#include <iostream>

using namespace OEChem;
using namespace OESystem;
using namespace std;

double CalculateMolecularWeight(const OEMolBase &mol,bool isotopic=false)
{
  OEIter<OEAtomBase> atom;
  unsigned int elemno = 0;
  unsigned int isotope = 0;
  unsigned int impH = 0;
  double result = 0.0;

  if(isotopic)
  {
    for (atom=mol.GetAtoms(); atom; ++atom)
    {
      elemno = atom->GetAtomicNum();
      isotope = atom->GetIsotope();
      impH += atom->GetImplicitHCount();
      if ((elemno!=0) && (isotope!=0) && OEIsCommonIsotope(elemno,isotope))
      {
        result += OEGetIsotopicWeight(elemno,isotope);
      }
      else result += OEGetAverageWeight(elemno);
    }
  }
  else //non-isotopic
  {
    for(atom = mol.GetAtoms();atom; ++atom)
    {
      elemno = atom->GetAtomicNum();
      impH += atom->GetImplicitHCount();
      result += OEGetAverageWeight(elemno);
    }
  }
  result += (impH * OEGetAverageWeight(1));
  return result;
}

int main()
{
  oemolistream ims;

  OEIter<OEMolBase> mol;
  for (mol = ims.GetMolBases();mol;++mol)
  {
    cerr << mol->GetTitle() << "  mw= "
         << CalculateMolecularWeight(mol,true) << endl;
  }
  return 0;
}