Coverage Report

Created: 2026-12-01 06:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openbabel/src/rotor.cpp
Line
Count
Source
1
/**********************************************************************
2
rotor.cpp - Rotate dihedral angles according to rotor rules.
3
4
Copyright (C) 1998-2000 by OpenEye Scientific Software, Inc.
5
Some portions Copyright (C) 2001-2006 by Geoffrey R. Hutchison
6
7
This file is part of the Open Babel project.
8
For more information, see <http://openbabel.org/>
9
10
This program is free software; you can redistribute it and/or modify
11
it under the terms of the GNU General Public License as published by
12
the Free Software Foundation version 2 of the License.
13
14
This program is distributed in the hope that it will be useful,
15
but WITHOUT ANY WARRANTY; without even the implied warranty of
16
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
GNU General Public License for more details.
18
***********************************************************************/
19
20
#include <openbabel/babelconfig.h>
21
22
#include <openbabel/mol.h>
23
#include <openbabel/bond.h>
24
#include <openbabel/ring.h>
25
#include <openbabel/obiter.h>
26
#include <openbabel/oberror.h>
27
#include <openbabel/rotor.h>
28
#include <openbabel/graphsym.h>
29
#include <openbabel/elements.h>
30
31
#include <set>
32
#include <cassert>
33
34
// private data headers with default parameters
35
#include "torlib.h"
36
37
#ifndef M_PI
38
#define M_PI 3.14159265358979323846
39
#endif
40
41
42
using namespace std;
43
namespace OpenBabel
44
{
45
46
  //! Default step resolution for a dihedral angle (in degrees)
47
0
#define OB_DEFAULT_DELTA 15.0
48
  static bool GetDFFVector(OBMol&,vector<int>&,OBBitVec&);
49
  static bool CompareRotor(const pair<OBBond*,int>&,const pair<OBBond*,int>&);
50
51
52
  //**************************************
53
  //**** OBRotorList Member Functions ****
54
  //**************************************
55
56
  bool OBRotorList::Setup(OBMol &mol, bool sampleRingBonds)
57
0
  {
58
0
    Clear();
59
    // find the rotatable bonds
60
0
    FindRotors(mol, sampleRingBonds);
61
0
    if (!Size())
62
0
      return(false);
63
64
    // set the atoms that should be evaluated when this rotor changes
65
0
    SetEvalAtoms(mol);
66
0
    AssignTorVals(mol);
67
68
0
    OBRotor *rotor;
69
0
    vector<OBRotor*>::iterator i;
70
0
    for (rotor = BeginRotor(i);rotor;rotor = NextRotor(i))
71
0
      if (!rotor->Size())
72
0
        {
73
0
          int ref[4];
74
0
          rotor->GetDihedralAtoms(ref);
75
0
          char buffer[BUFF_SIZE];
76
0
          snprintf(buffer, BUFF_SIZE, "The rotor has no associated torsion values -> %d %d %d %d",
77
0
      ref[0],ref[1],ref[2],ref[3]);
78
0
          obErrorLog.ThrowError(__FUNCTION__, buffer, obDebug);
79
0
        }
80
81
    // Reduce the number of torsions to be checked through symmetry considerations
82
0
    if (_removesym)
83
0
      RemoveSymVals(mol);
84
85
0
    return(true);
86
0
  }
87
88
  bool OBRotorList::FindRotors(OBMol &mol, bool sampleRingBonds)
89
0
  {
90
    // Find ring atoms & bonds
91
    // This function will set OBBond::IsRotor().
92
0
    mol.FindRingAtomsAndBonds();
93
94
0
    obErrorLog.ThrowError(__FUNCTION__,
95
0
                          "Ran OpenBabel::FindRotors", obAuditMsg);
96
97
    //
98
    // Score the bonds using the graph theoretical distance (GTD).
99
    // The GTD is the distance from atom i to every other atom j.
100
    // Atoms on the "inside" of the molecule will have a lower GTD
101
    // value than atoms on the "outside"
102
    //
103
    // The scoring will rank "inside" bonds first.
104
    //
105
0
    vector<int> gtd;
106
0
    mol.GetGTDVector(gtd);
107
    // compute the scores
108
0
    vector<OBBond*>::iterator i;
109
0
    vector<pair<OBBond*,int> > vtmp;
110
0
    for (OBBond *bond = mol.BeginBond(i);bond;bond = mol.NextBond(i)) {
111
      // check if the bond is "rotatable"
112
0
      if (bond->IsRotor(sampleRingBonds)) {
113
        // check if the bond is fixed (using deprecated fixed atoms or new fixed bonds)
114
0
        if ((!_fixedatoms.IsEmpty() || HasFixedBonds()) && IsFixedBond(bond))
115
0
          continue;
116
117
0
        if (bond->IsInRing()) {
118
          //otherwise mark that we have them and add it to the pile
119
0
          _ringRotors = true;
120
0
        }
121
122
0
        int score = gtd[bond->GetBeginAtomIdx()-1] + gtd[bond->GetEndAtomIdx()-1];
123
        // compute the GTD bond score as sum of atom GTD scores
124
0
        vtmp.push_back(pair<OBBond*,int> (bond,score));
125
0
      }
126
0
    }
127
128
    // sort the rotatable bonds by GTD score
129
0
    sort(vtmp.begin(),vtmp.end(),CompareRotor);
130
131
    // create rotors for the bonds
132
0
    int count = 0;
133
0
    vector<pair<OBBond*,int> >::iterator j;
134
0
    for (j = vtmp.begin(); j != vtmp.end(); ++j, ++count) {
135
0
      OBRotor *rotor = new OBRotor;
136
0
      rotor->SetBond((*j).first);
137
0
      rotor->SetIdx(count);
138
0
      _rotor.push_back(rotor);
139
0
    }
140
141
0
    return true;
142
0
  }
143
144
  bool OBRotorList::IsFixedBond(OBBond *bond)
145
0
  {
146
0
    if (_fixedatoms.IsEmpty() && _fixedbonds.IsEmpty())
147
0
      return false;
148
149
    // new fixed bonds
150
0
    if (!_fixedbonds.IsEmpty()) {
151
0
      return _fixedbonds.BitIsSet(bond->GetIdx());
152
0
    }
153
154
0
    if (_fixedatoms.IsEmpty())
155
0
      return false;
156
157
    // deprecated fixed atoms
158
0
    OBAtom *a1,*a2,*a3;
159
0
    vector<OBBond*>::iterator i;
160
161
0
    a1 = bond->GetBeginAtom();
162
0
    a2 = bond->GetEndAtom();
163
0
    if (!_fixedatoms[a1->GetIdx()] || !_fixedatoms[a2->GetIdx()])
164
0
      return(false);
165
166
0
    bool isfixed=false;
167
0
    for (a3 = a1->BeginNbrAtom(i);a3;a3 = a1->NextNbrAtom(i))
168
0
      if (a3 != a2 && _fixedatoms[a3->GetIdx()])
169
0
        {
170
0
          isfixed = true;
171
0
          break;
172
0
        }
173
174
0
    if (!isfixed)
175
0
      return(false);
176
177
0
    isfixed = false;
178
0
    for (a3 = a2->BeginNbrAtom(i);a3;a3 = a2->NextNbrAtom(i))
179
0
      if (a3 != a1 && _fixedatoms[a3->GetIdx()])
180
0
        {
181
0
          isfixed = true;
182
0
          break;
183
0
        }
184
185
0
    return(isfixed);
186
0
  }
187
188
  bool GetDFFVector(OBMol &mol,vector<int> &dffv,OBBitVec &bv)
189
0
  {
190
0
    dffv.clear();
191
0
    dffv.resize(mol.NumAtoms());
192
193
0
    int dffcount,natom;
194
0
    OBBitVec used,curr,next;
195
0
    OBAtom *atom,*atom1;
196
0
    OBBond *bond;
197
0
    vector<OBAtom*>::iterator i;
198
0
    vector<OBBond*>::iterator j;
199
200
0
    next.Clear();
201
202
0
    for (atom = mol.BeginAtom(i);atom;atom = mol.NextAtom(i))
203
0
      {
204
0
        if (bv[atom->GetIdx()])
205
0
          {
206
0
            dffv[atom->GetIdx()-1] = 0;
207
0
            continue;
208
0
          }
209
210
0
        dffcount = 0;
211
0
        used.Clear();
212
0
        curr.Clear();
213
0
        used.SetBitOn(atom->GetIdx());
214
0
        curr.SetBitOn(atom->GetIdx());
215
216
0
        while (!curr.IsEmpty() && (bv&curr).IsEmpty())
217
0
          {
218
0
            next.Clear();
219
0
            for (natom = curr.NextBit(-1);natom != curr.EndBit();natom = curr.NextBit(natom))
220
0
              {
221
0
                atom1 = mol.GetAtom(natom);
222
0
                for (bond = atom1->BeginBond(j);bond;bond = atom1->NextBond(j))
223
0
                  if (!used.BitIsSet(bond->GetNbrAtomIdx(atom1)) &&
224
0
                      !curr.BitIsSet(bond->GetNbrAtomIdx(atom1)))
225
0
                      if (bond->GetNbrAtom(atom1)->GetAtomicNum() != OBElements::Hydrogen)
226
0
                      next.SetBitOn(bond->GetNbrAtomIdx(atom1));
227
0
              }
228
229
0
            used |= next;
230
0
            curr = next;
231
0
            dffcount++;
232
0
          }
233
234
0
        dffv[atom->GetIdx()-1] = dffcount;
235
0
      }
236
237
0
    return(true);
238
0
  }
239
240
  void OBRotorList::RemoveSymVals(OBMol &mol)
241
0
  {
242
0
    OBGraphSym gs(&mol);
243
0
    vector<unsigned int> sym_classes;
244
0
    gs.GetSymmetry(sym_classes);
245
246
0
    OBRotor *rotor;
247
0
    vector<OBRotor*>::iterator i;
248
0
    std::set<unsigned int> syms;
249
0
    for (rotor = BeginRotor(i);rotor;rotor = NextRotor(i)) {
250
0
      OBBond* bond = rotor->GetBond();
251
0
      OBAtom* end = bond->GetEndAtom();
252
0
      OBAtom* begin = bond->GetBeginAtom();
253
0
      int N_fold_symmetry = 1;
254
0
      for (int here=0; here <= 1; ++here) { // Try each side of the bond in turn
255
256
0
        OBAtom *this_side, *other_side;
257
0
        if (here == 0) {
258
0
          this_side = begin; other_side = end;
259
0
        }
260
0
        else {
261
0
          this_side = end; other_side = begin;
262
0
        }
263
264
0
        for (unsigned int hyb=2; hyb<=3; ++hyb) { // sp2 and sp3 carbons, with explicit Hs
265
0
          if (this_side->GetAtomicNum() == 6 && this_side->GetHyb() == hyb && this_side->GetExplicitDegree() == (hyb + 1) ) {
266
0
            syms.clear();
267
0
            FOR_NBORS_OF_ATOM(nbr, this_side) {
268
0
              if ( &(*nbr) == other_side ) continue;
269
0
              syms.insert(sym_classes[nbr->GetIdx() - 1]);
270
0
            }
271
0
            if (syms.size() == 1) // All of the rotated atoms have the same symmetry class
272
0
              N_fold_symmetry *= hyb;
273
0
                      }
274
0
                  }
275
0
              }
276
277
0
      if (N_fold_symmetry  > 1) {
278
0
        size_t old_size = rotor->Size();
279
0
        rotor->RemoveSymTorsionValues(N_fold_symmetry);
280
0
        if (!_quiet) {
281
0
          cout << "...." << N_fold_symmetry << "-fold symmetry at rotor between " <<
282
0
                 begin->GetIdx() << " and " << end->GetIdx();
283
0
          cout << " - reduced from " << old_size << " to " << rotor->Size() << endl;
284
0
                  }
285
0
              }
286
0
      }
287
0
  }
288
289
  bool OBRotorList::SetEvalAtoms(OBMol &mol)
290
0
  {
291
0
    int j;
292
0
    OBBond *bond;
293
0
    OBAtom *a1,*a2;
294
0
    OBRotor *rotor;
295
0
    vector<OBRotor*>::iterator i;
296
0
    OBBitVec eval,curr,next;
297
0
    vector<OBBond*>::iterator k;
298
299
0
    for (rotor = BeginRotor(i);rotor;rotor = NextRotor(i))
300
0
      {
301
0
        bond = rotor->GetBond();
302
0
        curr.Clear();
303
0
        eval.Clear();
304
0
        curr.SetBitOn(bond->GetBeginAtomIdx());
305
0
        curr.SetBitOn(bond->GetEndAtomIdx());
306
0
        eval |= curr;
307
308
        //follow all non-rotor bonds and add atoms to eval list
309
0
        for (;!curr.IsEmpty();)
310
0
          {
311
0
            next.Clear();
312
0
            for (j = curr.NextBit(0);j != curr.EndBit();j = curr.NextBit(j))
313
0
              {
314
0
                a1 = mol.GetAtom(j);
315
0
                for (a2 = a1->BeginNbrAtom(k);a2;a2 = a1->NextNbrAtom(k))
316
0
                  if (!eval[a2->GetIdx()])
317
0
                    if (!((OBBond*)*k)->IsRotor(_ringRotors)||((!_fixedatoms.IsEmpty()||HasFixedBonds())&&IsFixedBond((OBBond*)*k)))
318
0
                      {
319
0
                        next.SetBitOn(a2->GetIdx());
320
0
                        eval.SetBitOn(a2->GetIdx());
321
0
                      }
322
0
              }
323
0
            curr = next;
324
0
          }
325
326
        //add atoms alpha to eval list
327
0
        next.Clear();
328
0
        for (j = eval.NextBit(0);j != eval.EndBit();j = eval.NextBit(j))
329
0
          {
330
0
            a1 = mol.GetAtom(j);
331
0
            for (a2 = a1->BeginNbrAtom(k);a2;a2 = a1->NextNbrAtom(k))
332
0
              next.SetBitOn(a2->GetIdx());
333
0
          }
334
0
        eval |= next;
335
0
        rotor->SetEvalAtoms(eval);
336
0
      }
337
338
0
    return(true);
339
0
  }
340
341
  bool OBRotorList::AssignTorVals(OBMol &mol)
342
0
  {
343
0
    vector<OBRotor*>::iterator i;
344
0
    for (i = _rotor.begin(); i != _rotor.end(); ++i) {
345
0
      OBRotor *rotor = *i;
346
0
      OBBond *bond = rotor->GetBond();
347
348
      // query the rotor database
349
0
      int ref[4];
350
0
      vector<double> angles;
351
0
      double delta;
352
0
      _rr.GetRotorIncrements(mol, bond, ref, angles, delta);
353
0
      rotor->SetTorsionValues(angles);
354
355
      // Find the smallest set of atoms to rotate. There are two candidate sets,
356
      // one on either side of the bond. If the first tried set size plus one is
357
      // larger than half of the number of atoms, the other set is smaller and the
358
      // rotor atom indexes are inverted (.i.e. a-b-c-d -> d-c-b-a).
359
0
      vector<int> atoms;
360
0
      vector<int>::iterator j;
361
      // find all atoms for which there is a path to ref[2] without goinf through ref[1]
362
0
      mol.FindChildren(atoms, ref[1], ref[2]);
363
0
      if (atoms.size() + 1 > mol.NumAtoms() / 2) {
364
0
        atoms.clear();
365
        // select the other smaller set
366
0
        mol.FindChildren(atoms, ref[2], ref[1]);
367
        // invert the rotor
368
0
        swap(ref[0],ref[3]);
369
0
        swap(ref[1],ref[2]);
370
0
      }
371
372
      // translate the rotate atom indexes to coordinate indexes (i.e. from 0, multiplied by 3)
373
0
      for (j = atoms.begin(); j != atoms.end(); ++j)
374
0
        *j = ((*j) - 1) * 3;
375
      // set the rotate atoms and dihedral atom indexes
376
0
      rotor->SetRotAtoms(atoms);
377
0
      rotor->SetDihedralAtoms(ref);
378
0
    }
379
380
0
    return true;
381
0
  }
382
383
  bool OBRotorList::SetRotAtoms(OBMol &mol)
384
0
  {
385
0
    OBRotor *rotor;
386
0
    vector<int> rotatoms;
387
0
    vector<OBRotor*>::iterator i;
388
389
0
    int ref[4];
390
0
    vector<int>::iterator j;
391
0
    for (rotor = BeginRotor(i);rotor;rotor = NextRotor(i))
392
0
      {
393
0
        rotor->GetDihedralAtoms(ref);
394
395
0
        mol.FindChildren(rotatoms,ref[1],ref[2]);
396
0
        if (rotatoms.size()+1 > mol.NumAtoms()/2)
397
0
          {
398
0
            rotatoms.clear();
399
0
            mol.FindChildren(rotatoms,ref[2],ref[1]);
400
0
            swap(ref[0],ref[3]);
401
0
            swap(ref[1],ref[2]);
402
0
          }
403
404
0
        for (j = rotatoms.begin();j != rotatoms.end();++j)
405
0
          *j = ((*j)-1)*3;
406
0
        rotor->SetRotAtoms(rotatoms);
407
0
        rotor->SetDihedralAtoms(ref);
408
0
      }
409
410
0
    return(true);
411
0
  }
412
413
  void OBRotorList::SetRotAtomsByFix(OBMol &mol)
414
0
  {
415
0
    int ref[4];
416
0
    OBRotor *rotor;
417
0
    vector<int> rotatoms;
418
0
    vector<int>::iterator j;
419
0
    vector<OBRotor*>::iterator i;
420
421
0
    GetDFFVector(mol,_dffv,_fixedatoms);
422
423
0
    for (rotor = BeginRotor(i);rotor;rotor = NextRotor(i))
424
0
      {
425
0
        rotatoms.clear();
426
0
        rotor->GetDihedralAtoms(ref);
427
428
0
        if (_fixedatoms[ref[1]] && _fixedatoms[ref[2]])
429
0
          {
430
0
            if (!_fixedatoms[ref[0]])
431
0
              {
432
0
                swap(ref[0],ref[3]);
433
0
                swap(ref[1],ref[2]);
434
0
                mol.FindChildren(rotatoms,ref[1],ref[2]);
435
0
                for (j = rotatoms.begin();j != rotatoms.end();++j)
436
0
                  *j = ((*j)-1)*3;
437
0
                rotor->SetRotAtoms(rotatoms);
438
0
                rotor->SetDihedralAtoms(ref);
439
0
              }
440
0
          }
441
0
        else
442
0
          if (_dffv[ref[1]-1] > _dffv[ref[2]-1])
443
0
            {
444
0
              swap(ref[0],ref[3]);
445
0
              swap(ref[1],ref[2]);
446
0
              mol.FindChildren(rotatoms,ref[1],ref[2]);
447
0
              for (j = rotatoms.begin();j != rotatoms.end();++j)
448
0
                *j = ((*j)-1)*3;
449
0
              rotor->SetRotAtoms(rotatoms);
450
0
              rotor->SetDihedralAtoms(ref);
451
0
            }
452
0
      }
453
0
  }
454
455
  OBRotorList::OBRotorList()
456
0
  {
457
0
    _rotor.clear();
458
0
    _quiet = true;
459
0
    _removesym = true;
460
0
    _ringRotors = false;
461
0
  }
462
463
  OBRotorList::~OBRotorList()
464
0
  {
465
0
    vector<OBRotor*>::iterator i;
466
0
    for (i = _rotor.begin();i != _rotor.end();++i)
467
0
      delete *i;
468
0
  }
469
470
  void OBRotorList::Clear()
471
0
  {
472
0
    vector<OBRotor*>::iterator i;
473
0
    for (i = _rotor.begin();i != _rotor.end();++i)
474
0
      delete *i;
475
0
    _rotor.clear();
476
0
    _ringRotors = false;
477
    //_fix.Clear();
478
0
  }
479
480
  bool CompareRotor(const pair<OBBond*,int> &a,const pair<OBBond*,int> &b)
481
0
  {
482
    //return(a.second > b.second); //outside->in
483
0
    return(a.second < b.second);   //inside->out
484
0
  }
485
486
  //**********************************
487
  //**** OBRotor Member Functions ****
488
  //**********************************
489
490
  OBRotor::OBRotor()
491
0
  {
492
0
  }
493
494
  void OBRotor::SetRings()
495
0
  {
496
0
    _rings.clear();
497
0
    if (_bond == nullptr)
498
0
      return; // nothing to do
499
500
0
    vector<OBRing*> rlist;
501
0
    vector<OBRing*>::iterator i;
502
503
0
    OBMol *mol = _bond->GetParent();
504
505
0
    if (mol == nullptr)
506
0
      return; // nothing to do
507
508
0
    rlist = mol->GetSSSR();
509
0
    for (i = rlist.begin();i != rlist.end();++i) {
510
0
      if ((*i)->IsMember(_bond))
511
0
        _rings.push_back(*i);
512
0
    }
513
0
  }
514
515
  double OBRotor::CalcTorsion(double *c)
516
0
  {
517
0
    double v1x,v1y,v1z,v2x,v2y,v2z,v3x,v3y,v3z;
518
0
    double c1x,c1y,c1z,c2x,c2y,c2z,c3x,c3y,c3z;
519
0
    double c1mag,c2mag,ang,costheta;
520
521
    //
522
    //calculate the torsion angle
523
    //
524
0
    v1x = c[_torsion[0]] -  c[_torsion[1]];
525
0
    v1y = c[_torsion[0]+1] - c[_torsion[1]+1];
526
0
    v1z = c[_torsion[0]+2] - c[_torsion[1]+2];
527
0
    v2x = c[_torsion[1]] - c[_torsion[2]];
528
0
    v2y = c[_torsion[1]+1] - c[_torsion[2]+1];
529
0
    v2z = c[_torsion[1]+2] - c[_torsion[2]+2];
530
0
    v3x = c[_torsion[2]]   - c[_torsion[3]];
531
0
    v3y = c[_torsion[2]+1] - c[_torsion[3]+1];
532
0
    v3z = c[_torsion[2]+2] - c[_torsion[3]+2];
533
534
0
    c1x = v1y*v2z - v1z*v2y;
535
0
    c2x = v2y*v3z - v2z*v3y;
536
0
    c1y = -v1x*v2z + v1z*v2x;
537
0
    c2y = -v2x*v3z + v2z*v3x;
538
0
    c1z = v1x*v2y - v1y*v2x;
539
0
    c2z = v2x*v3y - v2y*v3x;
540
0
    c3x = c1y*c2z - c1z*c2y;
541
0
    c3y = -c1x*c2z + c1z*c2x;
542
0
    c3z = c1x*c2y - c1y*c2x;
543
544
0
    c1mag = SQUARE(c1x)+SQUARE(c1y)+SQUARE(c1z);
545
0
    c2mag = SQUARE(c2x)+SQUARE(c2y)+SQUARE(c2z);
546
0
    if (c1mag*c2mag < 0.01)
547
0
      costheta = 1.0; //avoid div by zero error
548
0
    else
549
0
      costheta = (c1x*c2x + c1y*c2y + c1z*c2z)/(sqrt(c1mag*c2mag));
550
551
0
    if (costheta < -0.9999999)
552
0
      costheta = -0.9999999;
553
0
    if (costheta >  0.9999999)
554
0
      costheta =  0.9999999;
555
556
0
    if ((v2x*c3x + v2y*c3y + v2z*c3z) > 0.0)
557
0
      ang = -acos(costheta);
558
0
    else
559
0
      ang = acos(costheta);
560
561
0
    return(ang);
562
0
  }
563
564
  double OBRotor::CalcBondLength(double *c)
565
0
  {
566
    // compute the difference
567
0
    double dx, dy, dz;
568
0
    dx = c[_torsion[1]  ] - c[_torsion[2]  ];
569
0
    dy = c[_torsion[1]+1] - c[_torsion[2]+1];
570
0
    dz = c[_torsion[1]+2] - c[_torsion[2]+2];
571
    // compute the length
572
0
    return sqrt(SQUARE(dx) + SQUARE(dy) + SQUARE(dz));
573
0
  }
574
575
576
  void OBRotor::SetRotor(double *c,int idx,int prev)
577
0
  {
578
0
    double ang,sn,cs,t,dx,dy,dz,mag;
579
580
0
    if (prev == -1)
581
0
      ang = _torsionAngles[idx] - CalcTorsion(c);
582
0
    else
583
0
      ang = _torsionAngles[idx] - _torsionAngles[prev];
584
585
0
    sn = sin(ang);
586
0
    cs = cos(ang);
587
0
    t = 1 - cs;
588
589
0
    dx = c[_torsion[1]]   - c[_torsion[2]];
590
0
    dy = c[_torsion[1]+1] - c[_torsion[2]+1];
591
0
    dz = c[_torsion[1]+2] - c[_torsion[2]+2];
592
0
    mag = sqrt(SQUARE(dx) + SQUARE(dy) + SQUARE(dz));
593
594
0
    Set(c,sn,cs,t,1.0/mag);
595
0
  }
596
597
  // used in combination with Set(double *coordinates, int idx)
598
  void OBRotor::Precompute(double *coordinates)
599
0
  {
600
0
    _imag = 1.0 / CalcBondLength(coordinates);
601
0
    _refang = CalcTorsion(coordinates);
602
0
  }
603
604
  // used in combination with Precompute(double *coordinates)
605
  void OBRotor::Set(double *coordinates, int idx)
606
0
  {
607
0
    double ang,sn,cs,t;
608
609
    // compute the rotation angle
610
0
    ang = _torsionAngles[idx] - _refang;
611
    // compute some values for the rotation matrix
612
0
    sn = sin(ang);
613
0
    cs = cos(ang);
614
0
    t = 1 - cs;
615
616
0
    double x,y,z,tx,ty,tz,m[9];
617
618
    // compute the bond vector
619
0
    x = coordinates[_torsion[1]]   - coordinates[_torsion[2]];
620
0
    y = coordinates[_torsion[1]+1] - coordinates[_torsion[2]+1];
621
0
    z = coordinates[_torsion[1]+2] - coordinates[_torsion[2]+2];
622
623
    // normalize the bond vector
624
0
    x *= _imag;
625
0
    y *= _imag;
626
0
    z *= _imag;
627
628
    // set up the rotation matrix
629
0
    tx = t*x;
630
0
    ty = t*y;
631
0
    tz = t*z;
632
0
    m[0]= tx*x + cs;
633
0
    m[1] = tx*y + sn*z;
634
0
    m[2] = tx*z - sn*y;
635
0
    m[3] = tx*y - sn*z;
636
0
    m[4] = ty*y + cs;
637
0
    m[5] = ty*z + sn*x;
638
0
    m[6] = tx*z + sn*y;
639
0
    m[7] = ty*z - sn*x;
640
0
    m[8] = tz*z + cs;
641
642
    //
643
    //now the matrix is set - time to rotate the atoms
644
    //
645
0
    tx = coordinates[_torsion[1]];
646
0
    ty = coordinates[_torsion[1]+1];
647
0
    tz = coordinates[_torsion[1]+2];
648
0
    unsigned int i, j;
649
0
    for (i = 0; i < _rotatoms.size(); ++i)
650
0
      {
651
0
        j = _rotatoms[i];
652
0
        coordinates[j] -= tx;
653
0
        coordinates[j+1] -= ty;
654
0
        coordinates[j+2]-= tz;
655
0
        x = coordinates[j]*m[0] + coordinates[j+1]*m[1] + coordinates[j+2]*m[2];
656
0
        y = coordinates[j]*m[3] + coordinates[j+1]*m[4] + coordinates[j+2]*m[5];
657
0
        z = coordinates[j]*m[6] + coordinates[j+1]*m[7] + coordinates[j+2]*m[8];
658
0
        coordinates[j] = x+tx;
659
0
        coordinates[j+1] = y+ty;
660
0
        coordinates[j+2] = z+tz;
661
0
      }
662
0
  }
663
664
  // used in combination with Set
665
  void OBRotor::Precalc(vector<double*> &cv)
666
0
  {
667
0
    double *c,ang;
668
0
    vector<double*>::iterator i;
669
0
    vector<double>::iterator j;
670
0
    vector<double> cs,sn,t;
671
0
    for (i = cv.begin();i != cv.end();++i)
672
0
      {
673
0
        c = *i;
674
0
        cs.clear();
675
0
        sn.clear();
676
0
        t.clear();
677
0
        ang = CalcTorsion(c);
678
679
0
        for (j = _torsionAngles.begin();j != _torsionAngles.end();++j)
680
0
          {
681
0
            cs.push_back(cos(*j-ang));
682
0
            sn.push_back(sin(*j-ang));
683
0
            t.push_back(1 - cos(*j-ang));
684
0
          }
685
686
0
        _cs.push_back(cs);
687
0
        _sn.push_back(sn);
688
0
        _t.push_back(t);
689
0
        _invmag.push_back(1.0/CalcBondLength(c));
690
0
      }
691
0
  }
692
693
694
  void OBRotor::Set(double *c,double sn,double cs,double t,double invmag)
695
0
  {
696
0
    double x,y,z,tx,ty,tz,m[9];
697
698
0
    x = c[_torsion[1]]   - c[_torsion[2]];
699
0
    y = c[_torsion[1]+1] - c[_torsion[2]+1];
700
0
    z = c[_torsion[1]+2] - c[_torsion[2]+2];
701
702
    //normalize the rotation vector
703
704
0
    x *= invmag;
705
0
    y *= invmag;
706
0
    z *= invmag;
707
708
    //set up the rotation matrix
709
0
    tx = t*x;
710
0
    ty = t*y;
711
0
    tz = t*z;
712
0
    m[0]= tx*x + cs;
713
0
    m[1] = tx*y + sn*z;
714
0
    m[2] = tx*z - sn*y;
715
0
    m[3] = tx*y - sn*z;
716
0
    m[4] = ty*y + cs;
717
0
    m[5] = ty*z + sn*x;
718
0
    m[6] = tx*z + sn*y;
719
0
    m[7] = ty*z - sn*x;
720
0
    m[8] = tz*z + cs;
721
722
    //
723
    //now the matrix is set - time to rotate the atoms
724
    //
725
0
    tx = c[_torsion[1]];
726
0
    ty = c[_torsion[1]+1];
727
0
    tz = c[_torsion[1]+2];
728
0
    unsigned int i, j;
729
0
    for (i = 0; i < _rotatoms.size(); ++i)
730
0
      {
731
0
        j = _rotatoms[i];
732
0
        c[j] -= tx;
733
0
        c[j+1] -= ty;
734
0
        c[j+2]-= tz;
735
0
        x = c[j]*m[0] + c[j+1]*m[1] + c[j+2]*m[2];
736
0
        y = c[j]*m[3] + c[j+1]*m[4] + c[j+2]*m[5];
737
0
        z = c[j]*m[6] + c[j+1]*m[7] + c[j+2]*m[8];
738
0
        c[j] = x+tx;
739
0
        c[j+1] = y+ty;
740
0
        c[j+2] = z+tz;
741
0
      }
742
0
  }
743
744
  //! Remove all torsions angles between 0 and 360/fold
745
  void OBRotor::RemoveSymTorsionValues(int fold)
746
0
  {
747
0
    vector<double>::iterator i;
748
0
    vector<double> tv;
749
0
    if (_torsionAngles.size() == 1)
750
0
      return;
751
752
0
    for (i = _torsionAngles.begin();i != _torsionAngles.end();++i)
753
0
      if (*i >= 0.0 && *i < 2.0*M_PI / fold)
754
0
            tv.push_back(*i);
755
756
0
    if (tv.empty())
757
0
      return;
758
0
    _torsionAngles = tv;
759
0
  }
760
761
  void OBRotor::SetDihedralAtoms(std::vector<int> &ref)
762
0
  {
763
0
    if (ref.size() != 4)
764
0
      return;
765
    // copy indexes starting from 1
766
0
    _ref.resize(4);
767
0
    for (int i = 0;i < 4;++i)
768
0
      _ref[i] = ref[i];
769
0
    _torsion.resize(4);
770
    // convert the indexes (start from 0, multiplied by 3) for easy access to coordinates
771
0
    _torsion[0] = (ref[0]-1)*3;
772
0
    _torsion[1] = (ref[1]-1)*3;
773
0
    _torsion[2] = (ref[2]-1)*3;
774
0
    _torsion[3] = (ref[3]-1)*3;
775
0
  }
776
777
  void OBRotor::SetDihedralAtoms(int ref[4])
778
0
  {
779
    // copy indexes starting from 1
780
0
    _ref.resize(4);
781
0
    for (int i = 0;i < 4;++i)
782
0
      _ref[i] = ref[i];
783
0
    _torsion.resize(4);
784
    // convert the indexes (start from 0, multiplied by 3) for easy access to coordinates
785
0
    _torsion[0] = (ref[0]-1)*3;
786
0
    _torsion[1] = (ref[1]-1)*3;
787
0
    _torsion[2] = (ref[2]-1)*3;
788
0
    _torsion[3] = (ref[3]-1)*3;
789
0
  }
790
791
  void OBRotor::SetRotAtoms(vector<int> &vi)
792
0
  {
793
0
    _rotatoms = vi;
794
0
  }
795
796
  //***************************************
797
  //**** OBRotorRules Member functions ****
798
  //***************************************
799
  OBRotorRules::OBRotorRules()
800
0
  {
801
0
    _quiet=false;
802
0
    _init = false;
803
0
    _dir = BABEL_DATADIR;
804
0
    _envvar = "BABEL_DATADIR";
805
0
    _filename = "torlib.txt";
806
0
    _subdir = "data";
807
0
    _dataptr = TorsionDefaults;
808
0
  }
809
810
  void OBRotorRules::ParseLine(const char *buffer)
811
0
  {
812
0
    int i;
813
0
    int ref[4];
814
0
    double delta;
815
0
    vector<double> vals;
816
0
    vector<string> vs;
817
0
    vector<string>::iterator j;
818
0
    char temp_buffer[BUFF_SIZE];
819
820
0
    if (buffer[0] == '#')
821
0
      return;
822
0
    tokenize(vs,buffer);
823
0
    if (vs.empty())
824
0
      return;
825
826
0
    if (EQn(buffer,"SP3-SP3",7))
827
0
      {
828
0
        _sp3sp3.clear();
829
        //        assert (vs.size() > 1);
830
0
        for (j = vs.begin(),++j;j != vs.end();++j)
831
0
          _sp3sp3.push_back(DEG_TO_RAD*atof(j->c_str()));
832
0
        return;
833
0
      }
834
835
0
    if (EQn(buffer,"SP3-SP2",7))
836
0
      {
837
0
        _sp3sp2.clear();
838
        //        assert(vs.size() > 1);
839
0
        for (j = vs.begin(),++j;j != vs.end();++j)
840
0
          _sp3sp2.push_back(DEG_TO_RAD*atof(j->c_str()));
841
0
        return;
842
0
      }
843
844
0
    if (EQn(buffer,"SP2-SP2",7))
845
0
      {
846
0
        _sp2sp2.clear();
847
        //        assert(vs.size() > 1);
848
0
        for (j = vs.begin(),++j;j != vs.end();++j)
849
0
          _sp2sp2.push_back(DEG_TO_RAD*atof(j->c_str()));
850
0
        return;
851
0
      }
852
853
0
    if (vs.size() > 5)
854
0
      {
855
0
        strncpy(temp_buffer,vs[0].c_str(), sizeof(temp_buffer) - 1);
856
0
        temp_buffer[sizeof(temp_buffer) - 1] = '\0';
857
        //reference atoms
858
0
        for (i = 0;i < 4;++i)
859
0
          ref[i] = atoi(vs[i+1].c_str())-1;
860
        //possible torsions
861
0
        vals.clear();
862
0
        delta = OB_DEFAULT_DELTA;
863
0
        for (i = 5;(unsigned)i < vs.size();++i)
864
0
          {
865
0
            if (i == (signed)(vs.size()-2) && vs[i] == "Delta")
866
0
              {
867
0
                delta = atof(vs[i+1].c_str());
868
0
                i += 2;
869
0
              }
870
0
            else
871
0
              vals.push_back(DEG_TO_RAD*atof(vs[i].c_str()));
872
0
          }
873
874
0
        if (vals.empty())
875
0
          {
876
0
            string err = "The following rule has no associated torsions: ";
877
0
            err += vs[0];
878
0
            obErrorLog.ThrowError(__FUNCTION__, err, obDebug);
879
0
          }
880
0
        OBRotorRule *rr = new OBRotorRule (temp_buffer,ref,vals,delta);
881
0
        if (rr->IsValid())
882
0
          _vr.push_back(rr);
883
0
        else
884
0
          delete rr;
885
0
      }
886
887
0
  }
888
889
  void OBRotorRules::GetRotorIncrements(OBMol &mol,OBBond *bond,
890
                                        int ref[4],vector<double> &vals,double &delta)
891
0
  {
892
0
    if (!_init)
893
0
      Init();
894
895
0
    vals.clear();
896
0
    vector<pair<int,int> > vpr;
897
0
    vpr.push_back(pair<int,int> (0,bond->GetBeginAtomIdx()));
898
0
    vpr.push_back(pair<int,int> (0,bond->GetEndAtomIdx()));
899
900
0
    delta = OB_DEFAULT_DELTA;
901
902
0
    int j;
903
0
    OBSmartsPattern *sp;
904
0
    vector<vector<int> > map;
905
0
    vector<OBRotorRule*>::iterator i;
906
0
    for (i = _vr.begin();i != _vr.end();++i)
907
0
      {
908
0
        sp = (*i)->GetSmartsPattern();
909
0
        (*i)->GetReferenceAtoms(ref);
910
0
        vpr[0].first = ref[1];
911
0
        vpr[1].first = ref[2];
912
913
0
        if (!sp->RestrictedMatch(mol,vpr,true))
914
0
          {
915
0
            swap(vpr[0].first,vpr[1].first);
916
0
            if (!sp->RestrictedMatch(mol,vpr,true))
917
0
              continue;
918
0
          }
919
920
0
        map = sp->GetMapList();
921
0
        for (j = 0;j < 4;++j)
922
0
          ref[j] = map[0][ref[j]];
923
0
        vals = (*i)->GetTorsionVals();
924
0
        delta = (*i)->GetDelta();
925
926
0
        OBAtom *a1,*a2,*a3,*a4,*r;
927
0
        a1 = mol.GetAtom(ref[0]);
928
0
        a4 = mol.GetAtom(ref[3]);
929
0
        if (a1->GetAtomicNum() == OBElements::Hydrogen && a4->GetAtomicNum() == OBElements::Hydrogen)
930
0
          continue; //don't allow hydrogens at both ends
931
0
        if (a1->GetAtomicNum() == OBElements::Hydrogen || a4->GetAtomicNum() == OBElements::Hydrogen) //need a heavy atom reference - can use hydrogen
932
0
          {
933
0
            bool swapped = false;
934
0
            a2 = mol.GetAtom(ref[1]);
935
0
            a3 = mol.GetAtom(ref[2]);
936
0
            if (a4->GetAtomicNum() == OBElements::Hydrogen)
937
0
              {
938
0
                swap(a1,a4);
939
0
                swap(a2,a3);
940
0
                swapped = true;
941
0
              }
942
943
0
            vector<OBBond*>::iterator k;
944
0
            for (r = a2->BeginNbrAtom(k);r;r = a2->NextNbrAtom(k))
945
0
              if (r->GetAtomicNum() != OBElements::Hydrogen && r != a3)
946
0
                break;
947
948
0
            if (!r)
949
0
              continue; //unable to find reference heavy atom
950
            //      cerr << "r = " << r->GetIdx() << endl;
951
952
0
            double t1 = mol.GetTorsion(a1,a2,a3,a4);
953
0
            double t2 = mol.GetTorsion(r,a2,a3,a4);
954
0
            double diff = t2 - t1;
955
0
            if (diff > 180.0)
956
0
              diff -= 360.0;
957
0
            if (diff < -180.0)
958
0
              diff += 360.0;
959
0
            diff *= DEG_TO_RAD;
960
961
0
            vector<double>::iterator m;
962
0
            for (m = vals.begin();m != vals.end();++m)
963
0
              {
964
0
                *m += diff;
965
0
                if (*m < M_PI)
966
0
                  *m += 2.0*M_PI;
967
0
                if (*m > M_PI)
968
0
                  *m -= 2.0*M_PI;
969
0
              }
970
971
0
            if (swapped)
972
0
              ref[3] = r->GetIdx();
973
0
            else
974
0
              ref[0] = r->GetIdx();
975
976
            /*
977
              mol.SetTorsion(r,a2,a3,a4,vals[0]);
978
              cerr << "test = " << (vals[0]-diff)*RAD_TO_DEG << ' ';
979
              cerr << mol.GetTorsion(a1,a2,a3,a4) <<  ' ';
980
              cerr << mol.GetTorsion(r,a2,a3,a4) << endl;
981
            */
982
0
          }
983
984
0
        char buffer[BUFF_SIZE];
985
0
        if (!_quiet)
986
0
          {
987
0
            snprintf(buffer,BUFF_SIZE,"%3d%3d%3d%3d %s",
988
0
                     ref[0],ref[1],ref[2],ref[3],
989
0
                     ((*i)->GetSmartsString()).c_str());
990
0
            obErrorLog.ThrowError(__FUNCTION__, buffer, obDebug);
991
0
          }
992
0
        return;
993
0
      }
994
995
    //***didn't match any rules - assign based on hybridization***
996
0
    OBAtom *a1,*a2,*a3,*a4;
997
0
    a2 = bond->GetBeginAtom();
998
0
    a3 = bond->GetEndAtom();
999
0
    vector<OBBond*>::iterator k;
1000
1001
0
    for (a1 = a2->BeginNbrAtom(k);a1;a1 = a2->NextNbrAtom(k))
1002
0
      if (a1->GetAtomicNum() != OBElements::Hydrogen && a1 != a3)
1003
0
        break;
1004
0
    for (a4 = a3->BeginNbrAtom(k);a4;a4 = a3->NextNbrAtom(k))
1005
0
      if (a4->GetAtomicNum() != OBElements::Hydrogen && a4 != a2)
1006
0
        break;
1007
1008
0
    ref[0] = a1->GetIdx();
1009
0
    ref[1] = a2->GetIdx();
1010
0
    ref[2] = a3->GetIdx();
1011
0
    ref[3] = a4->GetIdx();
1012
1013
0
    if (a2->GetHyb() == 3 && a3->GetHyb() == 3) //sp3-sp3
1014
0
      {
1015
0
        vals = _sp3sp3;
1016
1017
0
        if (!_quiet)
1018
0
          {
1019
0
            char buffer[BUFF_SIZE];
1020
0
            snprintf(buffer,BUFF_SIZE,"%3d%3d%3d%3d %s",
1021
0
                     ref[0],ref[1],ref[2],ref[3],"sp3-sp3");
1022
0
            obErrorLog.ThrowError(__FUNCTION__, buffer, obDebug);
1023
0
          }
1024
0
      }
1025
0
    else
1026
0
      if (a2->GetHyb() == 2 && a3->GetHyb() == 2) //sp2-sp2
1027
0
        {
1028
0
          vals = _sp2sp2;
1029
1030
0
          if (!_quiet)
1031
0
            {
1032
0
              char buffer[BUFF_SIZE];
1033
0
              snprintf(buffer,BUFF_SIZE,"%3d%3d%3d%3d %s",
1034
0
                       ref[0],ref[1],ref[2],ref[3],"sp2-sp2");
1035
0
              obErrorLog.ThrowError(__FUNCTION__, buffer, obDebug);
1036
0
            }
1037
0
        }
1038
0
      else //must be sp2-sp3
1039
0
        {
1040
0
          vals = _sp3sp2;
1041
1042
0
          if (!_quiet)
1043
0
            {
1044
0
              char buffer[BUFF_SIZE];
1045
0
              snprintf(buffer,BUFF_SIZE,"%3d%3d%3d%3d %s",
1046
0
                       ref[0],ref[1],ref[2],ref[3],"sp2-sp3");
1047
0
              obErrorLog.ThrowError(__FUNCTION__, buffer, obDebug);
1048
0
            }
1049
0
        }
1050
0
  }
1051
1052
  OBRotorRules::~OBRotorRules()
1053
0
  {
1054
0
    vector<OBRotorRule*>::iterator i;
1055
0
    for (i = _vr.begin();i != _vr.end();++i)
1056
0
      delete (*i);
1057
0
  }
1058
1059
#undef OB_DEFAULT_DELTA
1060
}
1061
1062
//! \file rotor.cpp
1063
//! \brief Rotate dihedral angles according to rotor rules.