
# coding: utf-8

# In[354]:

#!/usr/bin/env python

# generation of up to N strained local energy minima
# from 2D input (smi) to 3D output (sdf)
# see Ebejer et. al.
# "Freely Available Conformer Generation Methods: How Good Are They?"
# JCIM, 2012, DOI: 10.1021/ci2004658 for technical details

# Modified from GitHub script "smi2sdf3d" Francois BERENGER
# by Katrina Lexa 27/09/2017


from __future__ import print_function

import sys
from contextlib import closing

import rdkit
from rdkit import Chem
from rdkit.Chem import AllChem
from multiprocessing import Process, Value
import unittest
import sys, os


# In[355]:

# nb. conformers to generate prior to energy minimization
# as an empirical function of the molecule's flexibility
def how_many_conformers(mol):
    nb_rot_bonds = AllChem.CalcNumRotatableBonds(mol)
    if nb_rot_bonds <= 7:
        return 50
    elif nb_rot_bonds <= 12:
        return 200
    return 300  # This is more


# In[356]:

# keep only conformers which are far enough from the reference conformer
# (the one of lowest energy)
def rmsd_filter(mol, ref_conf, conf_energies, rmsd_threshold):
    refConfId = ref_conf.GetId()
    return [(e, curr_conf) for e, curr_conf in conf_energies
            if AllChem.GetBestRMS(mol, mol, refConfId, curr_conf.GetId()) \
            > rmsd_threshold]
# P. Gedeck: the GetBestRMS code is pretty slow if there are
#            a lot of CH3 groups. You can get a considerable speedup
#            by ignoring hydrogens. However, that is less trivial


# In[357]:

#if len(sys.argv) != 4:
#    print("usage: %s N input.smi output.sdf" % sys.argv[0])
#    sys.exit(1)

def main():
    n_confs = 25
    input_sdf = '~/test-in.sdf'
    output_sdf = '~/test-out.sdf'
    nprocs = 1 # for parallelization
    # to prune too similar conformers
    rmsd_threshold = 0.35 # Angstrom
    with closing(Chem.SDWriter(output_sdf)) as writer:
        suppl = Chem.ForwardSDMolSupplier(input_sdf, sanitize=True, removeHs=False)
        for mol in suppl:
            if mol is None:
                print("skipping mol", file=sys.stderr)
                continue
            name = mol.GetProp("_Name")
            n = how_many_conformers(mol)
            print("init pool size for %s: %d" % (name, n))
            mol_H = Chem.AddHs(mol)
            res = Chem.Mol(mol_H)
            res.RemoveAllConformers()
            print("generating starting conformers ...")
            conf_energies = []
            print("FF minimization ...")
            for cid in AllChem.EmbedMultipleConfs(mol_H, n):
                ff = AllChem.UFFGetMoleculeForceField(mol_H, confId=cid)
                atoms = mol_H.GetAtoms()
                ### add positional constraint on all atoms in input compound
                for atom in atoms:
                    ff.UFFAddPositionConstraint(atom.GetIdx(), 0.1, 1000)
                ### add fixed point so input conformation is close to minimized conformations
                ff.AddFixedPoint(atoms[1].GetIdx())
                #print("E before: %f" % ff.CalcEnergy())
                ff.Minimize()
                energy = ff.CalcEnergy()
                #print("E after: %f" % energy)
                conformer = mol_H.GetConformer(cid)
                #print("cid: %d e: %f" % (cid, energy))
                conf_energies.append((energy, conformer))
            # sort by increasing E
            conf_energies = sorted(conf_energies, key=lambda x: x[0])
            # output non neighbor conformers
            kept = []
            print("RMSD pruning ...")
            while len(kept) < n_confs and len(conf_energies) > 0:
                (e, conf) = conf_energies.pop(0)
                kept.append((e, conf))
                cid = res.AddConformer(conf, assignId=True)
                name_cid = "%s_%04d" % (name, cid)
                res.SetProp("_Name", name_cid)
                # add conf energy as property to output sdf
                res.SetProp('Energy', '{0:.2f}'.format(e))
                # write this one out so that user can see some progress
                writer.write(res, confId=cid)
                # remove neighbors
                conf_energies = rmsd_filter(mol_H, conf, conf_energies, rmsd_threshold)
            print("kept %d confs for %s" % (len(kept), name))

if __name__ == '__main__':
    main()

