File: obrms.cpp

package info (click to toggle)
openbabel 3.1.1%2Bdfsg-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 259,620 kB
  • sloc: cpp: 361,957; python: 11,640; ansic: 6,470; perl: 6,010; pascal: 793; php: 529; sh: 226; xml: 97; ruby: 64; makefile: 45; java: 23
file content (386 lines) | stat: -rw-r--r-- 9,896 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/**********************************************************************
 obrms = Returns the rms between two chemically identical structures
 Derived from obfit.
 *
 This file is part of the Open Babel project.
 For more information, see <http://openbabel.org/>
 
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation version 2 of the License.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 ***********************************************************************/

/*
 Require a fixed molecule and a set of molecules to compare against.
 example of command line:
 obrms ref.sdf test.sdf
 */

#undef _GLIBCXX_DEBUG /* unless you have boost libraries built with this, you do _not_ want this defined */
// used to set import/export for Cygwin DLLs
#ifdef WIN32
#define USING_OBDLL
#endif
#include <cstdlib>
#include <openbabel/babelconfig.h>
#include <openbabel/mol.h>
#include <openbabel/parsmart.h>
#include <openbabel/obconversion.h>
#include <openbabel/query.h>
#include <openbabel/isomorphism.h>
#include <openbabel/shared_ptr.h>
#include <openbabel/obutil.h>

#include "getopt.h"

#include <sstream>

using namespace std;
using namespace OpenBabel;

class AtomDistanceSorter
{
	vector3 ref;
	public:
	AtomDistanceSorter(OBAtom *r) :
			ref(r->GetVector())
	{

	}
	bool operator()(OBAtom *l, OBAtom *r) const
			{
		double ld = ref.distSq(l->GetVector());
		double rd = ref.distSq(r->GetVector());

		return ld < rd;
	}
};
/* class to perform graph matching between two molecules.
 * Is initialized with the reference molecule.
 * Will figure out the atom correspondences and compute the rmsd between the
 * ref mol and a provided test mol.
 */
class Matcher
{
	const OBMol *ref;
	obsharedptr<OBQuery> query;
	obsharedptr<OBIsomorphismMapper> mapper;

	class MapRMSDFunctor: public OBIsomorphismMapper::Functor
	{
	private:
		const OBMol *ref;
		OBMol& test;
		double bestRMSD;
		bool minimize;
		public:
		//will modify t if min is true
		MapRMSDFunctor(const OBMol* r, OBMol& t, bool min = false) :
				ref(r), test(t), bestRMSD(HUGE_VAL), minimize(min)
		{
		}

		bool operator()(OBIsomorphismMapper::Mapping &map)
		{
			unsigned N = map.size();
			double *refcoord = (double*)alloca(sizeof(double)*N * 3);
			double *testcoord = (double*)alloca(sizeof(double)*N * 3);

			for (unsigned i = 0; i < N; i++)
			{
				//obmol indices are 1-indexed while the mapper is zero indexed
				const OBAtom *ratom = ref->GetAtom(map[i].first + 1);
				const OBAtom *tatom = test.GetAtom(map[i].second + 1);
				assert(ratom && tatom);

				for (unsigned c = 0; c < 3; c++)
				{
					refcoord[3 * i + c] = ratom->GetVector()[c];
					testcoord[3 * i + c] = tatom->GetVector()[c];
				}
			}

			if (minimize)
			{
				double rmatrix[3][3] =
						{ 0 };

				double rave[3] =
						{ 0, 0, 0 };
				double tave[3] =
						{ 0, 0, 0 };
				//center
				for (unsigned i = 0; i < N; i++)
				{
					for (unsigned c = 0; c < 3; c++)
					{
						rave[c] += refcoord[3 * i + c];
						tave[c] += testcoord[3 * i + c];
					}
				}

				for (unsigned c = 0; c < 3; c++)
				{
					rave[c] /= N;
					tave[c] /= N;
				}

				for (unsigned i = 0; i < N; i++)
				{
					for (unsigned c = 0; c < 3; c++)
					{
						refcoord[3 * i + c] -= rave[c];
						testcoord[3 * i + c] -= tave[c];
					}
				}

				qtrfit(refcoord, testcoord, N, rmatrix);
				rotate_coords(testcoord, rmatrix, N); 

				for (unsigned i = 0; i < N; i++)
				{
					//with minimize on, change coordinates
					OBAtom *tatom = test.GetAtom(map[i].second + 1);
					tatom->SetVector(testcoord[3*i]+rave[0], testcoord[3*i+1]+rave[1], testcoord[3*i+2]+rave[2]);
				}
			}

			double rmsd = calc_rms(refcoord, testcoord, N);

			if (rmsd < bestRMSD)
				bestRMSD = rmsd;
			// check all possible mappings
			return false;
		}

		double getRMSD() const
		{
			return bestRMSD;
		}
	};

public:
	Matcher(OBMol& mol) : ref(&mol)
	{
		query = obsharedptr<OBQuery>(CompileMoleculeQuery(&mol));
		mapper = obsharedptr<OBIsomorphismMapper>(OBIsomorphismMapper::GetInstance(query.get()));
	}


	//computes a correspondence between the ref mol and test (exhaustively)
	//and returns the rmsd; returns infinity if unmatchable
	double computeRMSD(OBMol& test, bool minimize = false)
	{
		MapRMSDFunctor funct(ref, test, minimize);

		mapper->MapGeneric(funct, &test);
		return funct.getRMSD();
	}
};

//preprocess molecule into a standardized state for heavy atom rmsd computation
static void processMol(OBMol& mol)
{
	//isomorphismmapper wants isomorphic atoms to have the same aromatic and ring state,
	//but these proporties aren't reliable enough to be trusted in evaluating molecules
	//should be considered the same based solely on connectivity

	mol.DeleteHydrogens(); //heavy atom rmsd
	for (OBAtomIterator aitr = mol.BeginAtoms(); aitr != mol.EndAtoms(); aitr++)
	{
		OBAtom *a = *aitr;
		a->SetAromatic(false);
		a->SetInRing();
	}
	for (OBBondIterator bitr = mol.BeginBonds(); bitr != mol.EndBonds(); bitr++)
	{
		OBBond *b = *bitr;
		b->SetAromatic(false);
		b->SetBondOrder(1);
		b->SetInRing();
	}
	//avoid recomputations
	mol.SetHybridizationPerceived();
	mol.SetRingAtomsAndBondsPerceived();
	mol.SetAromaticPerceived();
}
///////////////////////////////////////////////////////////////////////////////
//! \brief compute rms between chemically identical molecules
int main(int argc, char **argv)
{
	bool firstOnly = false;
	bool minimize = false;
	bool separate = false;
	bool help = false;
	bool docross = false;
	string fileRef;
	string fileTest;
	string fileOut;

	const char *helpmsg =
	 "obrms: Computes the heavy-atom RMSD of identical compound structures.\n"
	  "Usage: obrms reference_file [test_file]\n"
	  "Options:\n"
    "\t -o, --out        re-oriented test structure output\n"
	  "\t -f, --firstonly  use only the first structure in the reference file\n"
	  "\t -m, --minimize   compute minimum RMSD\n"
	  "\t -x, --cross      compute all n^2 RMSDs between molecules of reference file\n"
	  "\t -s, --separate   separate reference file into constituent molecules and report best RMSD\n"
	  "\t -h, --help       help message\n";
	struct option long_options[] = {
	    {"firstonly", no_argument, nullptr, 'f'},
	    {"minimize", no_argument, nullptr, 'm'},
	    {"cross", no_argument, nullptr, 'x'},
	    {"separate", no_argument, nullptr, 's'},
	    {"out", required_argument, nullptr, 'o'},
	    {"help", no_argument, nullptr, 'h'},
	    {nullptr, 0, nullptr, 0}
	};
	int option_index = 0;
	int c = 0;
	while ((c = getopt_long(argc, argv, "hfmxso:", long_options, &option_index) ) != -1) {
	  switch(c) {
	    case 'o':
	      fileOut = optarg;
	      break;
	    case 'f':
	      firstOnly = true;
	      break;
	    case 'm':
	      minimize = true;
	      break;
	    case 'x':
	      docross = true;
	      break;
	    case 's':
	      separate = true;
	      break;
	    case 'h':
	      cout << helpmsg;
	      exit(0);
	      break;
	    default:
	      cerr << "Unrecognized option: " << c << "\n";
	      exit(-1);
	  }
	}

	if(optind < argc) {
	  fileRef = argv[optind];
	  optind++;
	}
	if(optind < argc) {
	  fileTest = argv[optind];
	  optind++;
	}

	if(optind < argc) {
	  cerr << "Unrecognized argument: " << argv[optind];
	  exit(-1);
	}

	if(!docross && fileTest.size() == 0) {
    cerr << helpmsg;
	  cerr << "Command line parse error: test file is required but missing\n";
	  exit(-1);
	}

	//open mols
	OBConversion refconv(fileRef);

	OBConversion outconv;
	OBFormat *outFormat = outconv.FormatFromExt(fileOut);
	if(fileOut.size() > 0)
	{
		if(!outFormat || !outconv.SetInAndOutFormats(outFormat, outFormat))
		{
			cerr << "Do not understand output format!" << endl;
			exit(-1);
		}
	}

	std::ofstream out;
	if(fileOut.size() > 0)
	{
		out.open(fileOut.c_str());
	}


  //read reference
  OBMol molref;

	if(docross) {
	  //load in the entire reference file
    vector<OBMol> refmols;
    while (refconv.Read(&molref))
    {
       processMol(molref);
       refmols.push_back(molref);
    }

    for(unsigned i = 0, n = refmols.size() ; i < n; i++) {
      OBMol& ref = refmols[i];
      Matcher matcher(ref);
      cout << ref.GetTitle();
      for(unsigned j = 0; j < n; j++) {
        OBMol& moltest = refmols[j];
        double rmsd = matcher.computeRMSD(moltest, minimize);
        cout << ", " << rmsd;
      }
      cout << "\n";
    }

	} else {

	  //check comparison file
    while (refconv.Read(&molref))
    {
      vector<OBMol> refmols;
      if(separate) {
        refmols = molref.Separate();
      } else {
        refmols.push_back(molref);
      }

      vector<Matcher> matchers;
      for(unsigned i = 0, n = refmols.size(); i < n; i++) {
        processMol(refmols[i]);
        Matcher matcher(refmols[i]); // create the matcher
        matchers.push_back(matcher);
      }

      OBConversion testconv(fileTest);
      OBMol moltest;
      while (testconv.Read(&moltest))
      {
        if (moltest.Empty())
          break;

        processMol(moltest);

        double bestRMSD = HUGE_VAL;
        for(unsigned i = 0, n = matchers.size(); i < n; i++) {
          double rmsd = matchers[i].computeRMSD(moltest, minimize);
          if(rmsd < bestRMSD) bestRMSD = rmsd;
        }

        cout << "RMSD " << molref.GetTitle() << ":" <<  moltest.GetTitle() << " " << bestRMSD << "\n";

        if(out)
        {
          outconv.Write(&moltest, &out);
        }
        if (!firstOnly) //one test molecule will be read for each reference molecule
          break;
      }
      if(firstOnly) //done with first reference mol
        break;
    }
	}
	return (0);
}