File: Builder.cpp

package info (click to toggle)
rdkit 201809.1%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 123,688 kB
  • sloc: cpp: 230,509; python: 70,501; java: 6,329; ansic: 5,427; sql: 1,899; yacc: 1,739; lex: 1,243; makefile: 445; xml: 229; fortran: 183; sh: 123; cs: 93
file content (722 lines) | stat: -rw-r--r-- 26,892 bytes parent folder | download
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//  Copyright (C) 2004-2018 Greg Landrum and Rational Discovery LLC
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
#include <iostream>
#include <cmath>

#include <RDGeneral/Invariant.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/Substruct/SubstructMatch.h>

#include <ForceField/ForceField.h>
#include <ForceField/UFF/Params.h>
#include <ForceField/UFF/Contribs.h>

#include "AtomTyper.h"
#include "Builder.h"
namespace RDKit {
namespace UFF {
using namespace ForceFields::UFF;

namespace Tools {
// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addBonds(const ROMol &mol, const AtomicParamVect &params,
              ForceFields::ForceField *field) {
  PRECONDITION(mol.getNumAtoms() == params.size(), "bad parameters");
  PRECONDITION(field, "bad forcefield");

  for (ROMol::ConstBondIterator bi = mol.beginBonds(); bi != mol.endBonds();
       bi++) {
    int idx1 = (*bi)->getBeginAtomIdx();
    int idx2 = (*bi)->getEndAtomIdx();

    // FIX: recognize amide bonds here.

    if (params[idx1] && params[idx2]) {
      BondStretchContrib *contrib;
      contrib = new BondStretchContrib(field, idx1, idx2,
                                       (*bi)->getBondTypeAsDouble(),
                                       params[idx1], params[idx2]);
      field->contribs().push_back(ForceFields::ContribPtr(contrib));
    }
  }
}

unsigned int twoBitCellPos(unsigned int nAtoms, int i, int j) {
  if (j < i) std::swap(i, j);

  return i * (nAtoms - 1) + i * (1 - i) / 2 + j;
}

void setTwoBitCell(boost::shared_array<boost::uint8_t> &res, unsigned int pos,
                   boost::uint8_t value) {
  unsigned int twoBitPos = pos / 4;
  unsigned int shift = 2 * (pos % 4);
  boost::uint8_t twoBitMask = 3 << shift;
  res[twoBitPos] = ((res[twoBitPos] & (~twoBitMask)) | (value << shift));
}

boost::uint8_t getTwoBitCell(boost::shared_array<boost::uint8_t> &res,
                             unsigned int pos) {
  unsigned int twoBitPos = pos / 4;
  unsigned int shift = 2 * (pos % 4);
  boost::uint8_t twoBitMask = 3 << shift;

  return ((res[twoBitPos] & twoBitMask) >> shift);
}

// ------------------------------------------------------------------------
//
// the two-bit matrix returned by this contains:
//   0: if atoms i and j are directly connected
//   1: if atoms i and j are connected via an atom
//   2: if atoms i and j are in a 1,4 relationship
//   3: otherwise
//
//  NOTE: the caller is responsible for calling delete []
//  on the result
//
// ------------------------------------------------------------------------
boost::shared_array<boost::uint8_t> buildNeighborMatrix(const ROMol &mol) {
  const boost::uint8_t RELATION_1_X_INIT = RELATION_1_X | (RELATION_1_X << 2) |
                                           (RELATION_1_X << 4) |
                                           (RELATION_1_X << 6);
  unsigned int nAtoms = mol.getNumAtoms();
  unsigned nTwoBitCells = (nAtoms * (nAtoms + 1) - 1) / 8 + 1;
  boost::shared_array<boost::uint8_t> res(new boost::uint8_t[nTwoBitCells]);
  std::memset(res.get(), RELATION_1_X_INIT, nTwoBitCells);
  for (ROMol::ConstBondIterator bondi = mol.beginBonds();
       bondi != mol.endBonds(); ++bondi) {
    setTwoBitCell(res, twoBitCellPos(nAtoms, (*bondi)->getBeginAtomIdx(),
                                     (*bondi)->getEndAtomIdx()),
                  RELATION_1_2);
    unsigned int bondiBeginAtomIdx = (*bondi)->getBeginAtomIdx();
    unsigned int bondiEndAtomIdx = (*bondi)->getEndAtomIdx();
    for (ROMol::ConstBondIterator bondj = bondi; ++bondj != mol.endBonds();) {
      int idx1 = -1;
      int idx3 = -1;
      unsigned int bondjBeginAtomIdx = (*bondj)->getBeginAtomIdx();
      unsigned int bondjEndAtomIdx = (*bondj)->getEndAtomIdx();
      if (bondiBeginAtomIdx == bondjBeginAtomIdx) {
        idx1 = bondiEndAtomIdx;
        idx3 = bondjEndAtomIdx;
      } else if (bondiBeginAtomIdx == bondjEndAtomIdx) {
        idx1 = bondiEndAtomIdx;
        idx3 = bondjBeginAtomIdx;
      } else if (bondiEndAtomIdx == bondjBeginAtomIdx) {
        idx1 = bondiBeginAtomIdx;
        idx3 = bondjEndAtomIdx;
      } else if (bondiEndAtomIdx == bondjEndAtomIdx) {
        idx1 = bondiBeginAtomIdx;
        idx3 = bondjBeginAtomIdx;
      }
      if (idx1 > -1) {
        setTwoBitCell(res, twoBitCellPos(nAtoms, idx1, idx3), RELATION_1_3);
      }
    }
  }
  return res;
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addAngles(const ROMol &mol, const AtomicParamVect &params,
               ForceFields::ForceField *field) {
  PRECONDITION(mol.getNumAtoms() == params.size(), "bad parameters");
  PRECONDITION(field, "bad forcefield");
  ROMol::ADJ_ITER nbr1Idx;
  ROMol::ADJ_ITER end1Nbrs;
  ROMol::ADJ_ITER nbr2Idx;
  ROMol::ADJ_ITER end2Nbrs;
  RingInfo *rings = mol.getRingInfo();

  unsigned int nAtoms = mol.getNumAtoms();
  for (unsigned int j = 0; j < nAtoms; j++) {
    if (!params[j]) continue;
    const Atom *atomJ = mol.getAtomWithIdx(j);
    if (atomJ->getDegree() == 1) continue;
    boost::tie(nbr1Idx, end1Nbrs) = mol.getAtomNeighbors(atomJ);
    for (; nbr1Idx != end1Nbrs; nbr1Idx++) {
      const Atom *atomI = mol[*nbr1Idx];
      unsigned int i = atomI->getIdx();
      if (!params[i]) continue;
      boost::tie(nbr2Idx, end2Nbrs) = mol.getAtomNeighbors(atomJ);
      for (; nbr2Idx != end2Nbrs; nbr2Idx++) {
        if (nbr2Idx < (nbr1Idx + 1)) {
          continue;
        }
        const Atom *atomK = mol[*nbr2Idx];
        unsigned int k = atomK->getIdx();
        if (!params[k]) continue;
        // skip special cases:
        if (!(atomJ->getHybridization() == Atom::SP3D &&
              atomJ->getDegree() == 5)) {
          const Bond *b1 = mol.getBondBetweenAtoms(i, j);
          const Bond *b2 = mol.getBondBetweenAtoms(k, j);
          // FIX: recognize amide bonds here.
          AngleBendContrib *contrib;
          int order = 0;
          switch (atomJ->getHybridization()) {
            case Atom::SP:
              order = 1;
              break;
            case Atom::SP2:
              order = 3;
              // the following is a hack to get decent geometries
              // with 3- and 4-membered rings incorporating sp2 atoms
              // if the central atom is in a ring of size 3
              if (rings->isAtomInRingOfSize(j, 3)) {
                // if the central atom and one of the bonded atoms, but not the
                //  other one are inside a ring, then this angle is between a
                // ring substituent and a ring edge
                if ((rings->isAtomInRingOfSize(i, 3) &&
                     !rings->isAtomInRingOfSize(k, 3)) ||
                    (!rings->isAtomInRingOfSize(i, 3) &&
                     rings->isAtomInRingOfSize(k, 3))) {
                  order = 30;
                }
                // if all atoms are inside the ring, then this is one of ring
                // angles
                else if (rings->isAtomInRingOfSize(i, 3) &&
                         rings->isAtomInRingOfSize(k, 3)) {
                  order = 35;
                }
              }
              // if the central atom is in a ring of size 4
              else if (rings->isAtomInRingOfSize(j, 4)) {
                // if the central atom and one of the bonded atoms, but not the
                //  other one are inside a ring, then this angle is between a
                // ring substituent and a ring edge
                if ((rings->isAtomInRingOfSize(i, 4) &&
                     !rings->isAtomInRingOfSize(k, 4)) ||
                    (!rings->isAtomInRingOfSize(i, 4) &&
                     rings->isAtomInRingOfSize(k, 4))) {
                  order = 40;
                }
                // if all atoms are inside the ring, then this is one of ring
                // angles
                else if (rings->isAtomInRingOfSize(i, 4) &&
                         rings->isAtomInRingOfSize(k, 4)) {
                  order = 45;
                }
              }
              // end of the hack
              break;
            case Atom::SP3D2:
              order = 4;
              break;
            default:
              order = 0;
              break;
          }

          contrib =
              new AngleBendContrib(field, i, j, k, b1->getBondTypeAsDouble(),
                                   b2->getBondTypeAsDouble(), params[i],
                                   params[j], params[k], order);
          field->contribs().push_back(ForceFields::ContribPtr(contrib));
        }
      }
    }
  }
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addTrigonalBipyramidAngles(const Atom *atom, const ROMol &mol, int confId,
                                const AtomicParamVect &params,
                                ForceFields::ForceField *field) {
  PRECONDITION(atom, "bad atom");
  PRECONDITION(atom->getHybridization() == Atom::SP3D, "bad hybridization");
  PRECONDITION(atom->getDegree() == 5, "bad degree");
  PRECONDITION(mol.getNumAtoms() == params.size(), "bad parameters");
  PRECONDITION(field, "bad forcefield");

  const Bond *ax1 = nullptr, *ax2 = nullptr;
  const Bond *eq1 = nullptr, *eq2 = nullptr, *eq3 = nullptr;

  const Conformer &conf = mol.getConformer(confId);
  //------------------------------------------------------------
  // identify the axial and equatorial bonds:
  double mostNeg = 100.0;
  ROMol::OEDGE_ITER beg1, end1;
  boost::tie(beg1, end1) = mol.getAtomBonds(atom);
  unsigned int aid = atom->getIdx();
  while (beg1 != end1) {
    const Bond *bond1 = mol[*beg1];
    unsigned int oaid = bond1->getOtherAtomIdx(aid);
    RDGeom::Point3D v1 =
        conf.getAtomPos(aid).directionVector(conf.getAtomPos(oaid));

    ROMol::OEDGE_ITER beg2, end2;
    boost::tie(beg2, end2) = mol.getAtomBonds(atom);
    while (beg2 != end2) {
      const Bond *bond2 = mol[*beg2];
      if (bond2->getIdx() > bond1->getIdx()) {
        unsigned int oaid2 = bond2->getOtherAtomIdx(aid);
        RDGeom::Point3D v2 =
            conf.getAtomPos(aid).directionVector(conf.getAtomPos(oaid2));
        double dot = v1.dotProduct(v2);
        if (dot < mostNeg) {
          mostNeg = dot;
          ax1 = bond1;
          ax2 = bond2;
        }
      }
      ++beg2;
    }
    ++beg1;
  }
  CHECK_INVARIANT(ax1, "axial bond not found");
  CHECK_INVARIANT(ax2, "axial bond not found");

  boost::tie(beg1, end1) = mol.getAtomBonds(atom);
  while (beg1 != end1) {
    const Bond *bond = mol[*beg1];
    ++beg1;
    if (bond == ax1 || bond == ax2) continue;
    if (!eq1)
      eq1 = bond;
    else if (!eq2)
      eq2 = bond;
    else if (!eq3)
      eq3 = bond;
  }

  CHECK_INVARIANT(eq1, "equatorial bond not found");
  CHECK_INVARIANT(eq2, "equatorial bond not found");
  CHECK_INVARIANT(eq3, "equatorial bond not found");

  //------------------------------------------------------------
  // alright, add the angles:
  AngleBendContrib *contrib;
  int atomIdx = atom->getIdx();
  int i, j;

  // Axial-Axial
  i = ax1->getOtherAtomIdx(atomIdx);
  j = ax2->getOtherAtomIdx(atomIdx);
  if (params[i] && params[j]) {
    contrib = new AngleBendContrib(
        field, i, atomIdx, j, ax1->getBondTypeAsDouble(),
        ax2->getBondTypeAsDouble(), params[i], params[atomIdx], params[j], 2);
    field->contribs().push_back(ForceFields::ContribPtr(contrib));
  }
  // Equatorial-Equatorial
  i = eq1->getOtherAtomIdx(atomIdx);
  j = eq2->getOtherAtomIdx(atomIdx);
  if (params[i] && params[j]) {
    contrib = new AngleBendContrib(
        field, i, atomIdx, j, eq1->getBondTypeAsDouble(),
        eq2->getBondTypeAsDouble(), params[i], params[atomIdx], params[j], 3);
    field->contribs().push_back(ForceFields::ContribPtr(contrib));
  }
  i = eq1->getOtherAtomIdx(atomIdx);
  j = eq3->getOtherAtomIdx(atomIdx);
  if (params[i] && params[j]) {
    contrib = new AngleBendContrib(
        field, i, atomIdx, j, eq1->getBondTypeAsDouble(),
        eq3->getBondTypeAsDouble(), params[i], params[atomIdx], params[j], 3);
    field->contribs().push_back(ForceFields::ContribPtr(contrib));
  }
  i = eq2->getOtherAtomIdx(atomIdx);
  j = eq3->getOtherAtomIdx(atomIdx);
  if (params[i] && params[j]) {
    contrib = new AngleBendContrib(
        field, i, atomIdx, j, eq2->getBondTypeAsDouble(),
        eq3->getBondTypeAsDouble(), params[i], params[atomIdx], params[j], 3);
    field->contribs().push_back(ForceFields::ContribPtr(contrib));
  }

  // Axial-Equatorial
  i = ax1->getOtherAtomIdx(atomIdx);
  j = eq1->getOtherAtomIdx(atomIdx);
  if (params[i] && params[j]) {
    contrib = new AngleBendContrib(
        field, i, atomIdx, j, ax1->getBondTypeAsDouble(),
        eq1->getBondTypeAsDouble(), params[i], params[atomIdx], params[j]);
    field->contribs().push_back(ForceFields::ContribPtr(contrib));
  }
  i = ax1->getOtherAtomIdx(atomIdx);
  j = eq2->getOtherAtomIdx(atomIdx);
  if (params[i] && params[j]) {
    contrib = new AngleBendContrib(
        field, i, atomIdx, j, ax1->getBondTypeAsDouble(),
        eq2->getBondTypeAsDouble(), params[i], params[atomIdx], params[j]);
    field->contribs().push_back(ForceFields::ContribPtr(contrib));
  }
  i = ax1->getOtherAtomIdx(atomIdx);
  j = eq3->getOtherAtomIdx(atomIdx);
  if (params[i] && params[j]) {
    contrib = new AngleBendContrib(
        field, i, atomIdx, j, ax1->getBondTypeAsDouble(),
        eq3->getBondTypeAsDouble(), params[i], params[atomIdx], params[j]);
    field->contribs().push_back(ForceFields::ContribPtr(contrib));
  }
  i = ax2->getOtherAtomIdx(atomIdx);
  j = eq1->getOtherAtomIdx(atomIdx);
  if (params[i] && params[j]) {
    contrib = new AngleBendContrib(
        field, i, atomIdx, j, ax2->getBondTypeAsDouble(),
        eq1->getBondTypeAsDouble(), params[i], params[atomIdx], params[j]);
    field->contribs().push_back(ForceFields::ContribPtr(contrib));
  }
  i = ax2->getOtherAtomIdx(atomIdx);
  j = eq2->getOtherAtomIdx(atomIdx);
  if (params[i] && params[j]) {
    contrib = new AngleBendContrib(
        field, i, atomIdx, j, ax2->getBondTypeAsDouble(),
        eq2->getBondTypeAsDouble(), params[i], params[atomIdx], params[j]);
    field->contribs().push_back(ForceFields::ContribPtr(contrib));
  }
  i = ax2->getOtherAtomIdx(atomIdx);
  j = eq3->getOtherAtomIdx(atomIdx);
  if (params[i] && params[j]) {
    contrib = new AngleBendContrib(
        field, i, atomIdx, j, ax2->getBondTypeAsDouble(),
        eq3->getBondTypeAsDouble(), params[i], params[atomIdx], params[j]);
    field->contribs().push_back(ForceFields::ContribPtr(contrib));
  }
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addAngleSpecialCases(const ROMol &mol, int confId,
                          const AtomicParamVect &params,
                          ForceFields::ForceField *field) {
  PRECONDITION(mol.getNumAtoms() == params.size(), "bad parameters");
  PRECONDITION(field, "bad forcefield");

  unsigned int nAtoms = mol.getNumAtoms();
  for (unsigned int i = 0; i < nAtoms; i++) {
    const Atom *atom = mol.getAtomWithIdx(i);
    // trigonal bipyramidal:
    if ((atom->getHybridization() == Atom::SP3D && atom->getDegree() == 5)) {
      addTrigonalBipyramidAngles(atom, mol, confId, params, field);
    }
  }
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addNonbonded(const ROMol &mol, int confId, const AtomicParamVect &params,
                  ForceFields::ForceField *field,
                  boost::shared_array<boost::uint8_t> neighborMatrix,
                  double vdwThresh, bool ignoreInterfragInteractions) {
  PRECONDITION(mol.getNumAtoms() == params.size(), "bad parameters");
  PRECONDITION(field, "bad forcefield");

  INT_VECT fragMapping;
  if (ignoreInterfragInteractions) {
    std::vector<ROMOL_SPTR> molFrags =
        MolOps::getMolFrags(mol, true, &fragMapping);
  }

  unsigned int nAtoms = mol.getNumAtoms();
  const Conformer &conf = mol.getConformer(confId);
  for (unsigned int i = 0; i < nAtoms; i++) {
    if (!params[i]) continue;
    for (unsigned int j = i + 1; j < nAtoms; j++) {
      if (!params[j] ||
          (ignoreInterfragInteractions && fragMapping[i] != fragMapping[j])) {
        continue;
      }
      if (getTwoBitCell(neighborMatrix, twoBitCellPos(nAtoms, i, j)) >=
          RELATION_1_4) {
        double dist = (conf.getAtomPos(i) - conf.getAtomPos(j)).length();
        if (dist < vdwThresh *
                       UFF::Utils::calcNonbondedMinimum(params[i], params[j])) {
          vdWContrib *contrib;
          contrib = new vdWContrib(field, i, j, params[i], params[j]);
          field->contribs().push_back(ForceFields::ContribPtr(contrib));
        }
      }
    }
  }
}

#if 0
      // ------------------------------------------------------------------------
      //
      //
      //
      // ------------------------------------------------------------------------
      bool okToIncludeTorsion(const ROMol &mol,const Bond *bond,
                              int idx1,int idx2,int idx3,int idx4){
        bool res=true;
        RingInfo *rings=mol.getRingInfo();
        // having torsions in small rings makes the solver unstable
        // and tends to yield poor-quality geometries, so filter those out:
        if(rings->isBondInRingOfSize(bond->getIdx(),3)){
          res = false;
        }// else if(rings->isBondInRingOfSize(bond->getIdx(),4)){
         // res = false;
        //}
        return res;
      }
#endif

const std::string DefaultTorsionBondSmarts::ds_string =
    "[!$(*#*)&!D1]~[!$(*#*)&!D1]";
boost::scoped_ptr<const ROMol> DefaultTorsionBondSmarts::ds_instance;
#ifdef RDK_THREADSAFE_SSS
std::once_flag DefaultTorsionBondSmarts::ds_flag;
#endif
void DefaultTorsionBondSmarts::create() {
  ds_instance.reset(SmartsToMol(ds_string));
}

const ROMol *DefaultTorsionBondSmarts::query() {
#ifdef RDK_THREADSAFE_SSS
  std::call_once(ds_flag, create);
#else
  static bool created = false;
  if (!created) {
    created = true;
    create();
  }
#endif
  return ds_instance.get();
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addTorsions(const ROMol &mol, const AtomicParamVect &params,
                 ForceFields::ForceField *field,
                 const std::string &torsionBondSmarts) {
  PRECONDITION(mol.getNumAtoms() == params.size(), "bad parameters");
  PRECONDITION(field, "bad forcefield");

  // find all of the torsion bonds:
  std::vector<MatchVectType> matchVect;
  const ROMol *defaultQuery = DefaultTorsionBondSmarts::query();
  const ROMol *query = (torsionBondSmarts == DefaultTorsionBondSmarts::string())
                           ? defaultQuery
                           : SmartsToMol(torsionBondSmarts);
  TEST_ASSERT(query);
  unsigned int nHits = SubstructMatch(mol, *query, matchVect);
  if (query != defaultQuery) delete query;

  for (unsigned int i = 0; i < nHits; i++) {
    MatchVectType match = matchVect[i];
    TEST_ASSERT(match.size() == 2);
    int idx1 = match[0].second;
    int idx2 = match[1].second;
    if (!params[idx1] || !params[idx2]) continue;
    const Bond *bond = mol.getBondBetweenAtoms(idx1, idx2);
    std::vector<TorsionAngleContrib *> contribsHere;
    TEST_ASSERT(bond);
    const Atom *atom1 = mol.getAtomWithIdx(idx1);
    const Atom *atom2 = mol.getAtomWithIdx(idx2);

    if ((atom1->getHybridization() == Atom::SP2 ||
         atom1->getHybridization() == Atom::SP3) &&
        (atom2->getHybridization() == Atom::SP2 ||
         atom2->getHybridization() == Atom::SP3)) {
      ROMol::OEDGE_ITER beg1, end1;
      boost::tie(beg1, end1) = mol.getAtomBonds(atom1);
      while (beg1 != end1) {
        const Bond *tBond1 = mol[*beg1];
        if (tBond1 != bond) {
          int bIdx = tBond1->getOtherAtomIdx(idx1);
          ROMol::OEDGE_ITER beg2, end2;
          boost::tie(beg2, end2) = mol.getAtomBonds(atom2);
          while (beg2 != end2) {
            const Bond *tBond2 = mol[*beg2];
            if (tBond2 != bond && tBond2 != tBond1) {
              int eIdx = tBond2->getOtherAtomIdx(idx2);
              // make sure this isn't a three-membered ring:
              if (eIdx != bIdx) {
                // we now have a torsion involving atoms (bonds):
                //  bIdx - (tBond1) - idx1 - (bond) - idx2 - (tBond2) - eIdx
                TorsionAngleContrib *contrib;

                // if either of the end atoms is SP2 hybridized, set a flag
                // here.
                bool hasSP2 = false;
                if (mol.getAtomWithIdx(bIdx)->getHybridization() == Atom::SP2 ||
                    mol.getAtomWithIdx(bIdx)->getHybridization() == Atom::SP2) {
                  hasSP2 = true;
                }
                // std::cout << "Torsion: " << bIdx << "-" << idx1 << "-" <<
                // idx2 << "-" << eIdx << std::endl;
                // if(okToIncludeTorsion(mol,bond,bIdx,idx1,idx2,eIdx)){
                // std::cout << "  INCLUDED" << std::endl;
                contrib = new TorsionAngleContrib(
                    field, bIdx, idx1, idx2, eIdx, bond->getBondTypeAsDouble(),
                    atom1->getAtomicNum(), atom2->getAtomicNum(),
                    atom1->getHybridization(), atom2->getHybridization(),
                    params[idx1], params[idx2], hasSP2);
                field->contribs().push_back(ForceFields::ContribPtr(contrib));
                contribsHere.push_back(contrib);
                //}
              }
            }
            beg2++;
          }
        }
        beg1++;
      }
    }
    // now divide the force constant for each contribution to the torsion energy
    // about this bond by the number of contribs about this bond:
    for (auto chI = contribsHere.begin(); chI != contribsHere.end(); ++chI) {
      (*chI)->scaleForceConstant(contribsHere.size());
    }
  }
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addInversions(const ROMol &mol, const AtomicParamVect &params,
                   ForceFields::ForceField *field) {
  PRECONDITION(mol.getNumAtoms() == params.size(), "bad parameters");
  PRECONDITION(field, "bad forcefield");

  unsigned int idx[4];
  unsigned int n[4];
  const Atom *atom[4];
  ROMol::ADJ_ITER nbrIdx;
  ROMol::ADJ_ITER endNbrs;

  for (idx[1] = 0; idx[1] < mol.getNumAtoms(); ++idx[1]) {
    atom[1] = mol.getAtomWithIdx(idx[1]);
    int at2AtomicNum = atom[1]->getAtomicNum();
    // if the central atom is not carbon, nitrogen, oxygen,
    // phosphorous, arsenic, antimonium or bismuth, skip it
    if (((at2AtomicNum != 6) && (at2AtomicNum != 7) && (at2AtomicNum != 8) &&
         (at2AtomicNum != 15) && (at2AtomicNum != 33) && (at2AtomicNum != 51) &&
         (at2AtomicNum != 83)) ||
        (atom[1]->getDegree() != 3)) {
      continue;
    }
    // if the central atom is carbon, nitrogen or oxygen
    // but hybridization is not sp2, skip it
    if (((at2AtomicNum == 6) || (at2AtomicNum == 7) || (at2AtomicNum == 8)) &&
        (atom[1]->getHybridization() != Atom::SP2)) {
      continue;
    }
    boost::tie(nbrIdx, endNbrs) = mol.getAtomNeighbors(atom[1]);
    unsigned int i = 0;
    bool isBoundToSP2O = false;
    for (; nbrIdx != endNbrs; ++nbrIdx) {
      atom[i] = mol[*nbrIdx];
      idx[i] = atom[i]->getIdx();
      // if the central atom is sp2 carbon and is
      // bound to sp2 oxygen, set a flag
      if (!isBoundToSP2O) {
        isBoundToSP2O =
            ((at2AtomicNum == 6) && (atom[i]->getAtomicNum() == 8) &&
             (atom[i]->getHybridization() == Atom::SP2));
      }
      if (!i) {
        ++i;
      }
      ++i;
    }
    for (unsigned int i = 0; i < 3; ++i) {
      n[1] = 1;
      switch (i) {
        case 0:
          n[0] = 0;
          n[2] = 2;
          n[3] = 3;
          break;

        case 1:
          n[0] = 0;
          n[2] = 3;
          n[3] = 2;
          break;

        case 2:
          n[0] = 2;
          n[2] = 3;
          n[3] = 0;
          break;
      }
      InversionContrib *contrib;
      contrib = new InversionContrib(field, idx[n[0]], idx[n[1]], idx[n[2]],
                                     idx[n[3]], at2AtomicNum, isBoundToSP2O);
      field->contribs().push_back(ForceFields::ContribPtr(contrib));
    }
  }
}
}  // end of namespace Tools

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
ForceFields::ForceField *constructForceField(ROMol &mol,
                                             const AtomicParamVect &params,
                                             double vdwThresh, int confId,
                                             bool ignoreInterfragInteractions) {
  PRECONDITION(mol.getNumAtoms() == params.size(), "bad parameters");

  auto *res = new ForceFields::ForceField();

  // add the atomic positions:
  Conformer &conf = mol.getConformer(confId);
  for (unsigned int i = 0; i < mol.getNumAtoms(); i++) {
    res->positions().push_back(&conf.getAtomPos(i));
  }

  Tools::addBonds(mol, params, res);
  Tools::addAngles(mol, params, res);
  Tools::addAngleSpecialCases(mol, confId, params, res);
  boost::shared_array<boost::uint8_t> neighborMat =
      Tools::buildNeighborMatrix(mol);
  Tools::addNonbonded(mol, confId, params, res, neighborMat, vdwThresh,
                      ignoreInterfragInteractions);
  Tools::addTorsions(mol, params, res);
  Tools::addInversions(mol, params, res);

  return res;
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
ForceFields::ForceField *constructForceField(ROMol &mol, double vdwThresh,
                                             int confId,
                                             bool ignoreInterfragInteractions) {
  bool foundAll;
  AtomicParamVect params;
  boost::tie(params, foundAll) = getAtomTypes(mol);
  return constructForceField(mol, params, vdwThresh, confId,
                             ignoreInterfragInteractions);
}
}
}