In this post, I will introduce how to install openbabel package and use it through python.

Installation

Before you install the openbabel, you need to make sure that you have: (1) Eigen package and (2) SWIG.

Prerequists

Eigen

You can download the Eigen package through this command: git clone https://gitlab.com/libeigen/eigen.git. Then you can use cd eigen to go into the folder, you will find something like this:

Then the procedure is in below:

Step 1. mkdir build
Step 2. cd build
Step 3. cmake ..
Step 4. make -j4 (or jusr make)
Step 5. make install

Then you will install the Eigen package, which will be used in openbabel.

SWIG

The SWIG package can be installed by using the brew: brew install swig

Install openbabel with python binding

The Github Repository of openbabel is:

Open Babel
Interconverting chemical data since 2001. Open Babel has 10 repositories available. Follow their code on GitHub.
Github repository for Open Babel

Then we can download it by using:

git clone https://github.com/openbabel/openbabel.git

Once we have downloaded all the code, then we should go into the openbabel folder. You should see something like this:

Then you should build a new folder named build: mkdir build. Then go into it: cd build.

Then you can type this command:

cmake -DRUN_SWIG=ON -DPYTHON_BINDINGS=ON ..

The -DPYTHON_BINDINGS=ON means you want to use python bindings, so that you can import openbabel in python.

After the cmake, you can do the following steps:

  • Step 1: make -j4
  • Step 2: make test (optional)
  • Step 3: sudo make install

Once you have finished the above steps, then you need to export the location where the openbabel package is installed to PYTHONPATH, add this line into your ~/.bashrc:

export PYTHONPATH=$PYTHONPATH:your/location/in/here/openbabel

Then use source ~/.bashrc to make the change happen.

After everything is finished, then you can use openbabel in Python.

Usage of openbabel in python

In below is a short tutorial that can show you how to use openbabel in Python: (convert SMILES to cif file)

from openbabel import openbabel
from ase.io import read, write
import numpy as np

ft = 'xyz'
f = open('babel.'+ft, 'w')

gen3d = openbabel.OBOp.FindType('gen3D')
mol = openbabel.OBMol()

obConversion = openbabel.OBConversion()
obConversion.SetInAndOutFormats('smi', ft)
obConversion.ReadString(mol, '[N+](=O)([O-])[O-]')

gen3d.Do(mol, '--best')

print(mol.NumAtoms())

outMDL = obConversion.WriteString(mol)
f.write(outMDL)
f.close()

atoms = read('babel.'+ft)

a = 20
r_origin = np.array([a/2,a/2,a/2]) - atoms[0].position
print("r_origin is: {}".format(r_origin))
atoms.cell = [a, a, a]
atoms.pbc = [True, True, True]
for atom in atoms:
    atom.position += r_origin 
print(atom.position)
print(atoms)
write('babel.cif', atoms) 

If you want to create the molecules, MolView is a great tool. You can draw the structure yourself, and it will output the SMILES for you.