Coverage Report

Created: 2026-12-01 06:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openbabel/include/openbabel/forcefield.h
Line
Count
Source
1
/**********************************************************************
2
forcefield.h - Handle OBForceField class.
3
4
Copyright (C) 2006-2007 by Tim Vandermeersch <tim.vandermeersch@gmail.com>
5
6
This file is part of the Open Babel project.
7
For more information, see <http://openbabel.org/>
8
9
This program is free software; you can redistribute it and/or modify
10
it under the terms of the GNU General Public License as published by
11
the Free Software Foundation version 2 of the License.
12
13
This program is distributed in the hope that it will be useful,
14
but WITHOUT ANY WARRANTY; without even the implied warranty of
15
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
GNU General Public License for more details.
17
***********************************************************************/
18
19
#ifndef OB_FORCEFIELD_H
20
#define OB_FORCEFIELD_H
21
22
#include <vector>
23
#include <string>
24
25
#include <openbabel/babelconfig.h>
26
#include <openbabel/mol.h>  // TODO: Move OBMol code out of the header (use OBMol*)
27
#include <openbabel/atom.h> // TODO: Move OBAtom code out of the header
28
#include <openbabel/plugin.h>
29
#include <openbabel/bitvec.h>
30
#include <float.h>
31
32
namespace OpenBabel
33
{
34
  class OBGridData;
35
36
  // log levels
37
0
#define OBFF_LOGLVL_NONE  0   //!< no output
38
19.6k
#define OBFF_LOGLVL_LOW   1   //!< SteepestDescent progress... (no output from Energy())
39
31.1k
#define OBFF_LOGLVL_MEDIUM  2   //!< individual energy terms
40
24.1k
#define OBFF_LOGLVL_HIGH  3   //!< individual calculations and parameters
41
42
  // terms
43
0
#define OBFF_ENERGY   (1 << 0)   //!< all terms
44
0
#define OBFF_EBOND    (1 << 1)   //!< bond term
45
0
#define OBFF_EANGLE   (1 << 2)   //!< angle term
46
0
#define OBFF_ESTRBND    (1 << 3)   //!< strbnd term
47
0
#define OBFF_ETORSION   (1 << 4)   //!< torsion term
48
0
#define OBFF_EOOP   (1 << 5)   //!< oop term
49
0
#define OBFF_EVDW   (1 << 6)   //!< vdw term
50
0
#define OBFF_EELECTROSTATIC (1 << 7)   //!< electrostatic term
51
52
  // constraint types
53
0
#define OBFF_CONST_IGNORE (1 << 0)   //!< ignore the atom while setting up calculations
54
0
#define OBFF_CONST_ATOM   (1 << 1)   //!< fix the atom position
55
0
#define OBFF_CONST_ATOM_X (1 << 2)   //!< fix the x coordinate of the atom position
56
0
#define OBFF_CONST_ATOM_Y (1 << 3)   //!< fix the y coordinate of the atom position
57
0
#define OBFF_CONST_ATOM_Z (1 << 4)   //!< fix the z coordinate of the atom position
58
0
#define OBFF_CONST_DISTANCE (1 << 5)   //!< constrain distance length
59
0
#define OBFF_CONST_ANGLE  (1 << 6)   //!< constrain angle
60
0
#define OBFF_CONST_TORSION  (1 << 7)   //!< constrain torsion
61
#define OBFF_CONST_CHIRAL (1 << 8)   //!< constrain chiral volume
62
63
  // mode arguments for SteepestDescent, ConjugateGradients, ...
64
#define OBFF_NUMERICAL_GRADIENT   (1 << 0)  //!< use numerical gradients
65
#define OBFF_ANALYTICAL_GRADIENT  (1 << 1)  //!< use analytical gradients
66
67
const double KCAL_TO_KJ = 4.1868;
68
const double GAS_CONSTANT = 8.31446261815324e-3 / KCAL_TO_KJ;  //!< kcal mol^-1 K^-1 (2018 CODATA recommended value)
69
70
  // inline if statements for logging.
71
19.6k
#define IF_OBFF_LOGLVL_LOW    if(_loglvl >= OBFF_LOGLVL_LOW)
72
31.1k
#define IF_OBFF_LOGLVL_MEDIUM if(_loglvl >= OBFF_LOGLVL_MEDIUM)
73
24.1k
#define IF_OBFF_LOGLVL_HIGH   if(_loglvl >= OBFF_LOGLVL_HIGH)
74
75
  //! The type of line search to be used for optimization -- simple or Newton numeric
76
  struct LineSearchType
77
  {
78
    enum {
79
      Simple, Newton2Num
80
    };
81
  };
82
  /*
83
  struct ConstraintType
84
  {
85
    enum {
86
      Ignore, Atom, AtomX, AtomY, AtomZ, Distance, Angle, Torsion, Chiral
87
    };
88
  };
89
  */
90
91
  //! \class OBFFParameter forcefield.h <openbabel/forcefield.h>
92
  //! \brief Internal class for OBForceField to hold forcefield parameters
93
  class OBFPRT OBFFParameter {
94
  public:
95
    //! Used to store integer atom types
96
    int         a, b, c, d;
97
    //! used to store string atom types
98
    std::string _a, _b, _c, _d;
99
100
    //! Used to store integer type parameters (bondtypes, multiplicity, ...)
101
    std::vector<int>    _ipar;
102
    //! Used to store double type parameters (force constants, bond lengths, angles, ...)
103
    std::vector<double> _dpar;
104
105
    //! Assignment
106
    OBFFParameter& operator=(const OBFFParameter &ai)
107
0
      {
108
0
        if (this != &ai) {
109
0
          a = ai.a;
110
0
          b = ai.b;
111
0
          c = ai.c;
112
0
          d = ai.d;
113
0
          _a = ai._a;
114
0
          _b = ai._b;
115
0
          _c = ai._c;
116
0
          _d = ai._d;
117
0
          _ipar = ai._ipar;
118
0
          _dpar = ai._dpar;
119
0
        }
120
121
0
        return *this;
122
0
      }
123
124
    //! Reset the atom types and set all parameters to zero
125
    void clear ()
126
0
    {
127
0
      a = b = c = d = 0;
128
0
      _ipar.clear();
129
0
      _dpar.clear();
130
0
    }
131
  }; // class OBFFParameter
132
133
  // specific class introductions in forcefieldYYYY.cpp (for YYYY calculations)
134
135
  //! \class OBFFCalculation2 forcefield.h <openbabel/forcefield.h>
136
  //! \brief Internal class for OBForceField to hold energy and gradient calculations on specific force fields
137
  class OBFPRT OBFFCalculation2
138
  {
139
  public:
140
    //! Used to store the energy for this OBFFCalculation
141
    double energy;
142
    //! Used to store the atoms for this OBFFCalculation
143
    OBAtom *a, *b;
144
    //! Used to store the index of atoms for this OBFFCalculation
145
    int idx_a, idx_b;
146
    //! Pointer to atom coordinates as double[3]
147
    double *pos_a, *pos_b;
148
    //! Pointer to atom forces
149
    double force_a[3], force_b[3];
150
    //! Destructor
151
    virtual ~OBFFCalculation2()
152
4.92k
    {
153
4.92k
    }
154
    //! \return Setup pointers to atom positions and forces (To be called
155
    //!  while setting up calculations). Sets optimized to true.
156
    virtual void SetupPointers()
157
0
    {
158
0
      if (!a || !b) return;
159
0
      pos_a = a->GetCoordinate();
160
0
      idx_a = a->GetIdx();
161
0
      pos_b = b->GetCoordinate();
162
0
      idx_b = b->GetIdx();
163
0
    }
164
  };
165
166
  //! \class OBFFCalculation3 forcefield.h <openbabel/forcefield.h>
167
  //! \brief Internal class for OBForceField to hold energy and gradient calculations on specific force fields
168
  class OBFPRT OBFFCalculation3: public OBFFCalculation2
169
  {
170
  public:
171
    //! Used to store the atoms for this OBFFCalculation
172
    OBAtom *c;
173
    //! Used to store the index of atoms for this OBFFCalculation
174
    int idx_c;
175
    //! Pointer to atom coordinates as double[3]
176
    double *pos_c;
177
    //! Pointer to atom forces
178
    double force_c[3];
179
    //! Destructor
180
    virtual ~OBFFCalculation3()
181
0
    {
182
0
    }
183
    //! \return Setup pointers to atom positions and forces (To be called
184
    //!  while setting up calculations). Sets optimized to true.
185
    void SetupPointers() override
186
0
    {
187
0
      if (!a || !b || !c) return;
188
0
      pos_a = a->GetCoordinate();
189
0
      idx_a = a->GetIdx();
190
0
      pos_b = b->GetCoordinate();
191
0
      idx_b = b->GetIdx();
192
0
      pos_c = c->GetCoordinate();
193
0
      idx_c = c->GetIdx();
194
0
    }
195
  };
196
197
  //! \class OBFFCalculation4 forcefield.h <openbabel/forcefield.h>
198
  //! \brief Internal class for OBForceField to hold energy and gradient calculations on specific force fields
199
  class OBFPRT OBFFCalculation4: public OBFFCalculation3
200
  {
201
  public:
202
    //! Used to store the atoms for this OBFFCalculation
203
    OBAtom *d;
204
    //! Used to store the index of atoms for this OBFFCalculation
205
    int idx_d;
206
    //! Pointer to atom coordinates as double[3]
207
    double *pos_d;
208
    //! Pointer to atom forces
209
    double force_d[3];
210
    //! Destructor
211
    virtual ~OBFFCalculation4()
212
0
    {
213
0
    }
214
    //! \return Setup pointers to atom positions and forces (To be called
215
    //!  while setting up calculations). Sets optimized to true.
216
    void SetupPointers()
217
0
    {
218
0
      if (!a || !b || !c || !d) return;
219
0
      pos_a = a->GetCoordinate();
220
0
      idx_a = a->GetIdx();
221
0
      pos_b = b->GetCoordinate();
222
0
      idx_b = b->GetIdx();
223
0
      pos_c = c->GetCoordinate();
224
0
      idx_c = c->GetIdx();
225
0
      pos_d = d->GetCoordinate();
226
0
      idx_d = d->GetIdx();
227
0
    }
228
  };
229
230
  //! \class OBFFConstraint forcefield.h <openbabel/forcefield.h>
231
  //! \brief Internal class for OBForceField to hold constraints
232
  //! \since version 2.2
233
  class OBFPRT OBFFConstraint
234
  {
235
  public:
236
    //! Used to store the contraint energy for this OBFFConstraint
237
    double factor, constraint_value;
238
    double rab0, rbc0;
239
    //! Used to store the contraint type for this OBFFConstraint
240
    int type, ia, ib, ic, id;
241
    //! Used to store the atoms for this OBFFCostraint
242
    OBAtom *a, *b, *c, *d;
243
    //! Used to store the gradients for this OBFFCalculation
244
    vector3 grada, gradb, gradc, gradd;
245
246
    //! Constructor
247
    OBFFConstraint()
248
0
      {
249
0
        a = b = c = d = nullptr;
250
0
        ia = ib = ic = id = 0;
251
0
        constraint_value = 0.0;
252
0
        factor = 0.0;
253
0
      }
254
    //! Destructor
255
    ~OBFFConstraint()
256
0
      {
257
0
      }
258
259
    vector3 GetGradient(int a)
260
0
    {
261
0
      if (a == ia)
262
0
        return grada;
263
0
      else if (a == ib)
264
0
        return gradb;
265
0
      else if (a == ic)
266
0
        return gradc;
267
0
      else if (a == id)
268
0
        return gradd;
269
0
      else
270
0
        return  VZero;
271
0
    }
272
  };
273
274
  //! \class OBFFConstraints forcefield.h <openbabel/forcefield.h>
275
  //! \brief Internal class for OBForceField to handle constraints
276
  //! \since version 2.2
277
  class OBFPRT OBFFConstraints
278
  {
279
  public:
280
    //! Constructor
281
    OBFFConstraints();
282
    //! Destructor
283
    ~OBFFConstraints()
284
0
      {
285
0
        _constraints.clear();
286
0
        _ignored.Clear();
287
0
        _fixed.Clear();
288
0
        _Xfixed.Clear();
289
0
        _Yfixed.Clear();
290
0
        _Zfixed.Clear();
291
0
      }
292
    //! Clear all constraints
293
    void Clear();
294
    //! Get the constraint energy
295
    double GetConstraintEnergy();
296
    //! Get the constraint gradient for atom with index a
297
    vector3 GetGradient(int a);
298
    //! Get the constrain gradient for the atom
299
    OBFFConstraints& operator=(const OBFFConstraints &ai)
300
0
      {
301
0
        if (this != &ai) {
302
0
          _constraints = ai._constraints;
303
0
          _ignored = ai._ignored;
304
0
          _fixed = ai._fixed;
305
0
          _Xfixed = ai._Xfixed;
306
0
          _Yfixed = ai._Yfixed;
307
0
          _Zfixed = ai._Zfixed;
308
0
        }
309
0
        return *this;
310
0
      }
311
312
    /*! Translate indices to OBAtom* objects, this function is called from OBForceField::Setup,
313
     *  this function doesn't have to be called from anywhere else.
314
     */
315
    void Setup(OBMol &mol);
316
317
    /////////////////////////////////////////////////////////////////////////
318
    // Set Constraints                                                     //
319
    /////////////////////////////////////////////////////////////////////////
320
    //! \name Methods to set constraints
321
    //@{
322
    //! Set Constraint factor
323
    void SetFactor(double factor);
324
    //! Ignore the atom while setting up calculations
325
    void AddIgnore(int a);
326
    //! Fix the position of an atom
327
    void AddAtomConstraint(int a);
328
    //! Fix the x coordinate of the atom position
329
    void AddAtomXConstraint(int a);
330
    //! Fix the y coordinate of the atom position
331
    void AddAtomYConstraint(int a);
332
    //! Fix the z coordinate of the atom position
333
    void AddAtomZConstraint(int a);
334
    //! Constrain the bond length a-b
335
    void AddDistanceConstraint(int a, int b, double length);
336
    //! Constrain the angle a-b-c
337
    void AddAngleConstraint(int a, int b, int c, double angle);
338
    //! Constrain the torsion angle a-b-c-d
339
    void AddTorsionConstraint(int a, int b, int c, int d, double torsion);
340
    //! Delete a constraint
341
    //! \par index constraint index
342
    void DeleteConstraint(int index);
343
    //@}
344
    /////////////////////////////////////////////////////////////////////////
345
    // Get Constraints                                                     //
346
    /////////////////////////////////////////////////////////////////////////
347
    //! \name Methods to get information about set constraints
348
    //@{
349
    //! Get Constraint factor
350
    double GetFactor();
351
    //! \returns the number of set constraints
352
    int Size() const;
353
    /*! The following constraint types are known: OBFF_CONST_IGNORE (ignore
354
     *  the atom while setting up calculations, forcefield implementations
355
     *  need to check this value in their setup function), OBFF_CONST_ATOM
356
     *  (fix atom position), OBFF_CONST_ATOM_X (fix x coordinate),
357
     *  OBFF_CONST_ATOM_Y (fix y coordinate), OBFF_CONST_ATOM_Z (fix z
358
     *  coordinate), OBFF_CONST_BOND (constrain bond length), OBFF_CONST_ANGLE
359
     *  (constrain angle), OBFF_CONST_TORSION (constrain torsion angle)
360
     *  \return the constraint type
361
     */
362
    int GetConstraintType(int index) const;
363
    /*! \return The constraint value, this can be a bond length, angle or
364
     *   torsion angle depending on the constraint type.
365
     */
366
    double GetConstraintValue(int index) const;
367
    //! \return The constraint atom a (or fixed atom)
368
    //! \par index constraint index
369
    int GetConstraintAtomA(int index) const;
370
    //! \return The constraint atom b
371
    //! \par index constraint index
372
    int GetConstraintAtomB(int index) const;
373
    //! \return The constraint atom c
374
    //! \par index constraint index
375
    int GetConstraintAtomC(int index) const;
376
    //! \return The constraint atom d
377
    //! \par index constraint index
378
    int GetConstraintAtomD(int index) const;
379
    //! \return true if this atom is ignored
380
    //! \par a atom index
381
    bool IsIgnored(int a);
382
    //! \return true if this atom is fixed
383
    //! \par a atom index
384
    bool IsFixed(int a);
385
    //! \return true if the x coordinate for this atom is fixed
386
    //! \par a atom index
387
    bool IsXFixed(int a);
388
    //! \return true if the y coordinate for this atom is fixed
389
    //! \par a atom index
390
    bool IsYFixed(int a);
391
    //! \return true if the z coordinate for this atom is fixed
392
    //! \par a atom index
393
    bool IsZFixed(int a);
394
    //! \return the ignored atom indexes as bitvec. (used in
395
    //! OBForceField::Setup() to determine if a call to
396
    //! OBForceField::SetupCalculations() is needed)
397
0
    OBBitVec GetIgnoredBitVec() { return _ignored; }
398
    //! \return the fixed atom indexes as bitvec. (used in
399
    //! OBForceField::SystematicRotorSearch() and similar)
400
0
    OBBitVec GetFixedBitVec() { return _fixed; }
401
    //@}
402
403
  private:
404
    std::vector<OBFFConstraint> _constraints;
405
    OBBitVec  _ignored;
406
    OBBitVec  _fixed;
407
    OBBitVec  _Xfixed;
408
    OBBitVec  _Yfixed;
409
    OBBitVec  _Zfixed;
410
    double _factor;
411
  };
412
413
  // Class OBForceField
414
  // class introduction in forcefield.cpp
415
  class OBFPRT OBForceField : public OBPlugin
416
  {
417
    MAKE_PLUGIN(OBForceField)
418
419
    protected:
420
421
      /*!
422
      Get the correct OBFFParameter from a OBFFParameter vector.
423
424
      \code vector<OBFFParameter> parameters; \endcode
425
426
      this vector is filled with entries (as OBFFParameter) from
427
      a parameter file. This happens in the Setup() function.
428
429
      \code GetParameter(a, 0, 0, 0, parameters); \endcode
430
431
      returns the first OBFFParameter from vector<OBFFParameter>
432
      parameters where: pa = a (pa = parameter.a)
433
434
      use: vdw parameters, ...
435
436
      \code GetParameter(a, b, 0, 0, parameters); \endcode
437
438
      returns the first OBFFParameter from vector<OBFFParameter>
439
      parameters where: pa = a & pb = b      (ab)
440
      or: pa = b & pb = a      (ba)
441
442
      use: bond parameters, vdw parameters (pairs), ...
443
444
      \code GetParameter(a, b, c, 0, parameters); \endcode
445
446
      returns the first OBFFParameter from vector<OBFFParameter>
447
      parameters where: pa = a & pb = b & pc = c     (abc)
448
      or: pa = c & pb = b & pc = a     (cba)
449
450
      use: angle parameters, ...
451
452
      \code GetParameter(a, b, c, d, parameters); \endcode
453
454
      returns the first OBFFParameter from vector<OBFFParameter>
455
      parameters where: pa = a & pb = b & pc = c & pd = d    (abcd)
456
      or: pa = d & pb = b & pc = c & pd = a    (dbca)
457
      or: pa = a & pb = c & pc = b & pd = d    (acbd)
458
      or: pa = d & pb = c & pc = b & pd = a    (dcba)
459
460
      use: torsion parameters, ...
461
    */
462
    OBFFParameter* GetParameter(int a, int b, int c, int d, std::vector<OBFFParameter> &parameter);
463
    //! see GetParameter(int a, int b, int c, int d, std::vector<OBFFParameter> &parameter)
464
    OBFFParameter* GetParameter(const char* a, const char* b, const char* c, const char* d,
465
        std::vector<OBFFParameter> &parameter);
466
    //! Get index for vector<OBFFParameter> ...
467
    int GetParameterIdx(int a, int b, int c, int d, std::vector<OBFFParameter> &parameter);
468
469
    /*! Calculate the potential energy function derivative numerically with
470
     *  repect to the coordinates of atom with index a (this vector is the gradient)
471
     *
472
     * \param a  provides coordinates
473
     * \param terms OBFF_ENERGY, OBFF_EBOND, OBFF_EANGLE, OBFF_ESTRBND, OBFF_ETORSION,
474
     * OBFF_EOOP, OBFF_EVDW, OBFF_ELECTROSTATIC
475
     * \return the negative gradient of atom a
476
     */
477
    vector3 NumericalDerivative(OBAtom *a, int terms = OBFF_ENERGY);
478
    //! OB 3.0
479
    vector3 NumericalSecondDerivative(OBAtom *a, int terms = OBFF_ENERGY);
480
481
    /*
482
     *   NEW gradients functions
483
     */
484
485
    /*! Set the gradient for atom with index idx to grad
486
     */
487
    void SetGradient(double *grad, int idx)
488
0
    {
489
0
      const int coordIdx = (idx - 1) * 3;
490
0
      for (unsigned int i = 0; i < 3; ++i) {
491
0
        _gradientPtr[coordIdx + i] = grad[i];
492
0
      }
493
0
    }
494
495
    /*! Add grad to the gradient for atom with index idx
496
     */
497
    void AddGradient(double *grad, int idx)
498
0
    {
499
0
      const int coordIdx = (idx - 1) * 3;
500
0
      for (unsigned int i = 0; i < 3; ++i) {
501
0
        _gradientPtr[coordIdx + i] += grad[i];
502
0
      }
503
0
    }
504
505
    /*! Set all gradients to zero
506
     */
507
    virtual void ClearGradients()
508
1.16k
    {
509
      // We cannot use memset because IEEE floating point representations
510
      // are not guaranteed by C/C++ standard, but this loop can be
511
      // unrolled or vectorized by compilers
512
4.04k
      for (unsigned int i = 0; i < _ncoords; ++i)
513
2.88k
        _gradientPtr[i] = 0.0;
514
      //      memset(_gradientPtr, '\0', sizeof(double)*_ncoords);
515
1.16k
    }
516
517
    /*! Check if two atoms are in the same ring. [NOTE: this function uses SSSR,
518
     *  this means that not all rings are found for bridged rings. This causes
519
     *  some problems with the MMFF94 validation.]
520
     *  \param a atom a
521
     *  \param b atom b
522
     *  \return true if atom a and b are in the same ring
523
     */
524
    bool IsInSameRing(OBAtom* a, OBAtom* b);
525
526
    // general variables
527
    OBMol   _mol; //!< Molecule to be evaluated or minimized
528
    bool  _init; //!< Used to make sure we only parse the parameter file once, when needed
529
    std::string _parFile; //!< parameter file name
530
    bool  _validSetup; //!< was the last call to Setup successful
531
    double  *_gradientPtr; //!< pointer to the gradients (used by AddGradient(), minimization functions, ...)
532
    // logging variables
533
    std::ostream* _logos; //!< Output for logfile
534
    char  _logbuf[BUFF_SIZE+1]; //!< Temporary buffer for logfile output
535
    int   _loglvl; //!< Log level for output
536
    int   _origLogLevel;
537
    // conformer genereation (rotor search) variables
538
    int   _current_conformer; //!< used to hold i for current conformer (needed by UpdateConformers)
539
    std::vector<double> _energies; //!< used to hold the energies for all conformers
540
    // minimization variables
541
    double  _econv, _gconv, _e_n1; //!< Used for conjugate gradients and steepest descent(Initialize and TakeNSteps)
542
    int   _cstep, _nsteps; //!< Used for conjugate gradients and steepest descent(Initialize and TakeNSteps)
543
    double  *_grad1; //!< Used for conjugate gradients and steepest descent(Initialize and TakeNSteps)
544
    unsigned int _ncoords; //!< Number of coordinates for conjugate gradients
545
    int         _linesearch; //!< LineSearch type
546
    //! Hidden L-BFGS history. Forward-declared here (full definition lives
547
    //! in forcefield.cpp behind HAVE_EIGEN3) to keep Eigen out of this header
548
    //! and out of builds that don't link Eigen.
549
    struct LBFGSState;
550
    LBFGSState* _lbfgsState = nullptr; //!< Used for L-BFGS (Initialize and TakeNSteps); owned, destroyed in ~OBForceField()
551
#ifdef HAVE_EIGEN3
552
    //! Gather the per-atom gradient as a flat vector for L-BFGS. Writes the
553
    //! true gradient (negated from OB's "GetGradient() returns force"
554
    //! convention), honors fixed-atom and per-axis constraints, and reports
555
    //! the minimum per-atom squared force as minGrad2 (matches the
556
    //! convergence metric used by SD/CG).
557
    void gatherLBFGSGradient(double* gradOut, double& minGrad2);
558
#endif
559
    // molecular dynamics variables
560
    double  _timestep; //!< Molecular dynamics time step in picoseconds
561
    double  _temp; //!< Molecular dynamics temperature in Kelvin
562
    double  *_velocityPtr; //!< pointer to the velocities
563
    // contraint varibles
564
    static OBFFConstraints _constraints; //!< Constraints
565
    static unsigned int _fixAtom; //!< SetFixAtom()/UnsetFixAtom()
566
    static unsigned int _ignoreAtom; //!< SetIgnoreAtom()/UnsetIgnoreAtom()
567
    // cut-off variables
568
    bool  _cutoff; //!< true = cut-off enabled
569
    double  _rvdw; //!< VDW cut-off distance
570
    double  _rele; //!< Electrostatic cut-off distance
571
    double _epsilon; //!< Dielectric constant for electrostatics
572
    OBBitVec  _vdwpairs; //!< VDW pairs that should be calculated
573
    OBBitVec  _elepairs; //!< Electrostatic pairs that should be calculated
574
    int   _pairfreq; //!< The frequence to update non-bonded pairs
575
    // group variables
576
    std::vector<OBBitVec> _intraGroup; //!< groups for which intra-molecular interactions should be calculated
577
    std::vector<OBBitVec> _interGroup; //!< groups for which intra-molecular interactions should be calculated
578
    std::vector<std::pair<OBBitVec, OBBitVec> > _interGroups; //!< groups for which intra-molecular
579
                                                              //!< interactions should be calculated
580
  public:
581
    /*! Clone the current instance. May be desirable in multithreaded environments,
582
     *  Should be deleted after use
583
     */
584
    virtual OBForceField* MakeNewInstance()=0;
585
586
    //! Destructor (defined in forcefield.cpp because _lbfgsState's pimpl
587
    //! type LBFGSState is incomplete in this header).
588
    virtual ~OBForceField();
589
590
    //! \return Plugin type ("forcefields")
591
    const char* TypeID() override
592
60
    {
593
60
      return "forcefields";
594
60
    }
595
596
    /*! \param ID forcefield id (Ghemical, MMFF94, UFF, ...).
597
     *  \return A pointer to a forcefield (the default if ID is empty), or NULL if not available.
598
     */
599
    static OBForceField* FindForceField(const std::string& ID)
600
0
    {
601
0
      return FindType(ID.c_str());
602
0
    }
603
    /*! \param ID forcefield id (Ghemical, MMFF94, UFF, ...).
604
     *  \return A pointer to a forcefield (the default if ID is empty), or NULL if not available.
605
     */
606
    static OBForceField* FindForceField(const char *ID)
607
2.02k
    {
608
2.02k
      return FindType(ID);
609
2.02k
    }
610
    /*
611
     *
612
     */
613
    void SetParameterFile(const std::string &filename)
614
0
    {
615
0
      _parFile = filename;
616
0
      _init = false;
617
0
    }
618
    /*! \return The unit (kcal/mol, kJ/mol, ...) in which the energy is expressed as std::string.
619
     */
620
0
    virtual std::string GetUnit() { return std::string("au"); }
621
    /* Does this force field have analytical gradients defined for all
622
     * calculation components (bonds, angles, non-bonded, etc.)
623
     * If this is true, code should default to using OBFF_ANALYTICAL_GRADIENT
624
     * for SteepestDescent() or ConjugateGradients().
625
     * \return True if all analytical gradients are implemented.
626
     */
627
0
    virtual bool HasAnalyticalGradients() { return false; }
628
    /*! Setup the forcefield for mol (assigns atom types, charges, etc.). Keep current constraints.
629
     *  \param mol The OBMol object that contains the atoms and bonds.
630
     *  \return True if successful.
631
     */
632
    bool Setup(OBMol &mol);
633
    /*! Setup the forcefield for mol (assigns atom types, charges, etc.). Use new constraints.
634
     *  \param mol The OBMol object that contains the atoms and bonds.
635
     *  \param constraints The OBFFConstraints object that contains the constraints.
636
     *  \return True if successful.
637
     */
638
    bool Setup(OBMol &mol, OBFFConstraints &constraints);
639
    /*! Load the parameters (this function is overloaded by the individual forcefields,
640
     *  and is called autoamically from OBForceField::Setup()).
641
     */
642
    // move to protected in future version
643
0
    virtual bool ParseParamFile() { return false; }
644
    /*! Set the atom types (this function is overloaded by the individual forcefields,
645
     *  and is called autoamically from OBForceField::Setup()).
646
     */
647
    // move to protected in future version
648
0
    virtual bool SetTypes() { return false; }
649
    /*! Set the formal charges (this function is overloaded by the individual forcefields,
650
     *  and is called autoamically from OBForceField::Setup()).
651
     */
652
    // move to protected in future version
653
0
    virtual bool SetFormalCharges() { return false; }
654
    /*! Set the partial charges (this function is overloaded by the individual forcefields,
655
     *  and is called autoamically from OBForceField::Setup()).
656
     */
657
    // move to protected in future version
658
0
    virtual bool SetPartialCharges() { return false; }
659
    /*! Setup the calculations (this function is overloaded by the individual forcefields,
660
     *  and is called autoamically from OBForceField::Setup()).
661
     */
662
    // move to protected in future version
663
0
    virtual bool SetupCalculations() { return false; }
664
    /*! Setup the pointers to the atom positions in the OBFFCalculation objects. This method
665
     *  will iterate over all the calculations and call SetupPointers for each one. (This
666
     *  function should be implemented by the individual force field implementations).
667
     */
668
    // move to protected in future version
669
0
    virtual bool SetupPointers() { return false; }
670
    /*! Compare the internal forcefield OBMol object to mol. If the two have the
671
     *  same number of atoms and bonds, and all atomic numbers are the same,
672
     *  this function returns false, and no call to Setup is needed.
673
     *  \return True if Setup needs to be called.
674
     */
675
    bool IsSetupNeeded(OBMol &mol);
676
    /*! Get the force atom types. The atom types will be added to
677
     *  the atoms of mol as OBPairData. The attribute will be "FFAtomType".
678
     *
679
     *  \code
680
     *  ...
681
     *  pFF->Setup(&mol);
682
     *  pFF->GetAtomTypes(&mol);
683
     *  FOR_ATOMS_OF_MOL (atom, mol) {
684
     *    OBPairData *type = (OBPairData*) atom->GetData("FFAtomType");
685
     *    if (type)
686
     *      cout << "atom " << atom->GetIdx() << " : " << type->GetValue() << endl;
687
     *  }
688
     *  ...
689
     *  \endcode
690
     */
691
    bool GetAtomTypes(OBMol &mol);
692
    /*! Get the force field formal charges. The formal charges will be added to
693
     *  the atoms of mol as OBPairData. The attribute will be "FFPartialCharge".
694
     *
695
     *  \code
696
     *  ...
697
     *  pFF->Setup(&mol);
698
     *  pFF->GetPartialCharges(&mol);
699
     *  FOR_ATOMS_OF_MOL (atom, mol) {
700
     *    OBPairData *chg = (OBPairData*) atom->GetData("FFPartialCharge");
701
     *    if (chg)
702
     *      cout << "atom " << atom->GetIdx() << " : " << chg->GetValue() << endl;
703
     *  }
704
     *  ...
705
     *  \endcode
706
     */
707
    bool GetPartialCharges(OBMol &mol);
708
709
710
711
    /*! Get coordinates for current conformer and attach OBConformerData with energies, forces, ... to mol.
712
     *  \param mol The OBMol object to copy the coordinates to (from OBForceField::_mol).
713
     *  \return True if successful.
714
     */
715
    bool GetCoordinates(OBMol &mol);
716
    //! \deprecated Use GetCooordinates instead.
717
    OB_DEPRECATED_MSG("Use GetCooordinates instead.")
718
0
    bool UpdateCoordinates(OBMol &mol) {return GetCoordinates(mol); }
719
    /*! Get coordinates for all conformers and attach OBConformerData with energies, forces, ... to mol.
720
     *  \param mol The OBMol object to copy the coordinates to (from OBForceField::_mol).
721
     *  \return True if successful.
722
     */
723
    bool GetConformers(OBMol &mol);
724
    //! \deprecated Use GetConformers instead.
725
    OB_DEPRECATED_MSG("Use GetConformers instead.")
726
0
    bool UpdateConformers(OBMol &mol) { return GetConformers(mol); }
727
    /*! Set coordinates for current conformer.
728
     *  \param mol the OBMol object to copy the coordinates from (to OBForceField::_mol).
729
     *  \return true if successful.
730
     */
731
    bool SetCoordinates(OBMol &mol);
732
    /*! Set coordinates for all conformers.
733
     *  \param mol The OBMol object to copy the coordinates from (to OBForceField::_mol).
734
     *  \return True if successful.
735
     */
736
    bool SetConformers(OBMol &mol);
737
    /*! Create a grid with spacing @p step and @p padding. Place a probe atom of type probe at every grid point,
738
     *  calculate the energy and store it in the grid. These grids can then be used to create isosurfaces to
739
     *  identify locations where the probe atom has favourable interactions with the molecule.
740
     *  \param step The grid step size in A..
741
     *  \param padding The padding for the grid in A.
742
     *  \param type The force field atom type for the probe.
743
     *  \param pchg The partial charge for the probe atom.
744
     *  \return Pointer to the grid constaining the results.
745
     */
746
    OBGridData *GetGrid(double step, double padding, const char *type, double pchg);
747
748
    /////////////////////////////////////////////////////////////////////////
749
    // Interacting groups                                                  //
750
    /////////////////////////////////////////////////////////////////////////
751
752
    //! \name Methods for specifying interaction groups
753
    //@{
754
    /*! Enable intra-molecular interactions for group (bonds, angles, strbnd, torsions, oop).
755
     *  This function should be called before Setup().
756
     *  \param group OBBitVec with bits set for the indexes of the atoms which make up the group.
757
     */
758
    void AddIntraGroup(OBBitVec &group);
759
    /*! Enable inter-molecular interactions for group (non-bonded: vdw & ele).
760
     *  This function should be called before Setup().
761
     *  \param group OBBitVec with bits set for the indexes of the atoms which make up the group.
762
     */
763
    void AddInterGroup(OBBitVec &group);
764
    /*! Enable inter-molecular interactions between group1 and group2 (non-bonded: vdw & ele).
765
     *  Note that this function doesn't enable bonded interactions in either group. Non-bonded
766
     *  interactions in the groups itself are also not enabled.
767
     *  This function should be called before Setup().
768
     *  \param group1 OBBitVec with bits set for the indexes of the atoms which make up the first group.
769
     *  \param group2 OBBitVec with bits set for the indexes of the atoms which make up the second group.
770
     */
771
    void AddInterGroups(OBBitVec &group1, OBBitVec &group2);
772
    /*! Clear all previously specified groups.
773
     */
774
    void ClearGroups();
775
    /*! \return true if there are groups.
776
     */
777
    bool HasGroups();
778
    //@}
779
780
    /////////////////////////////////////////////////////////////////////////
781
    // Cut-off                                                             //
782
    /////////////////////////////////////////////////////////////////////////
783
784
    //! \name Methods for Cut-off distances
785
    //@{
786
    /*! Enable or disable Cut-offs. Cut-offs are disabled by default.
787
     *  \param enable Enable when true, disable when false.
788
     */
789
    void EnableCutOff(bool enable)
790
0
    {
791
0
      _cutoff = enable;
792
0
    }
793
    /*! \return True if Cut-off distances are used.
794
     */
795
    bool IsCutOffEnabled()
796
0
    {
797
0
      return _cutoff;
798
0
    }
799
    /*! Set the VDW cut-off distance to r. Note that this does not enable cut-off distances.
800
     *  \param r The VDW cut-off distance to be used in A.
801
     */
802
    void SetVDWCutOff(double r)
803
0
    {
804
0
      _rvdw = r;
805
0
    }
806
    /*! Get the VDW cut-off distance.
807
     *  \return The VDW cut-off distance in A.
808
     */
809
    double GetVDWCutOff()
810
0
    {
811
0
      return _rvdw;
812
0
    }
813
    /*! Set the Electrostatic cut-off distance to r. Note that this does not
814
     *  enable cut-off distances.
815
     *  \param r The electrostatic cut-off distance to be used in A.
816
     */
817
    void SetElectrostaticCutOff(double r)
818
0
    {
819
0
      _rele = r;
820
0
    }
821
    /*! Get the Electrostatic cut-off distance.
822
     *  \return The electrostatic cut-off distance in A.
823
     */
824
    double GetElectrostaticCutOff()
825
0
    {
826
0
      return _rele;
827
0
    }
828
    /*! Set the dielectric constant for electrostatic SetupCalculations
829
     * \param epsilon The relative permittivity to use (default = 1.0)
830
     */
831
     void SetDielectricConstant(double epsilon)
832
0
     {
833
0
       _epsilon = epsilon;
834
0
     }
835
     /* Get the dielectric permittivity used for electrostatic calculations
836
     * \rreturn The current relative permittivity
837
     */
838
     double GetDielectricConstant()
839
0
     {
840
0
       return _epsilon;
841
0
     }
842
    /*! Set the frequency by which non-bonded pairs are updated. Values from 10 to 20
843
     *  are recommended. Too low will decrease performance, too high will cause
844
     *  non-bonded interactions within cut-off not to be calculated.
845
     *  \param f The pair list update frequency.
846
     */
847
    void SetUpdateFrequency(int f)
848
0
    {
849
0
      _pairfreq = f;
850
0
    }
851
    /*! Get the frequency by which non-bonded pairs are updated.
852
     *  \return The pair list update frequency.
853
     */
854
    int GetUpdateFrequency()
855
0
    {
856
0
      return _pairfreq;
857
0
    }
858
    /*! Set the bits in _vdwpairs and _elepairs to 1 for interactions that
859
     *  are within cut-off distance. This function is called in minimizing
860
     *  algorithms such as SteepestDescent and ConjugateGradients.
861
     */
862
    void UpdatePairsSimple();
863
864
    //void UpdatePairsGroup(); TODO
865
866
    /*! Get the number of non-bonded pairs in _mol.
867
     *  \return The number of atom pairs (ignores cutoff)
868
     */
869
    unsigned int GetNumPairs();
870
    /*! Get the number of enabled electrostatic pairs in _mol.
871
     *  \return The number of pairs currently enabled (within cut-off distance)
872
     */
873
    unsigned int GetNumElectrostaticPairs();
874
    /*! Get the number of enabled VDW pairs in _mol.
875
     *  \return The number of pairs currently enabled (within cut-off distance)
876
     */
877
    unsigned int GetNumVDWPairs();
878
    /*! Set bits in range 0..._numpairs-1 to 1. Using this means there will
879
     *  be no cut-off. (not-working: see code for more information.
880
     */
881
    void EnableAllPairs()
882
0
    {
883
0
      // TODO: OBBitVec doesn't seem to be allocating it's memory correctly
884
0
      //_vdwpairs.SetRangeOn(0, _numpairs-1);
885
0
      //_elepairs.SetRangeOn(0, _numpairs-1);
886
0
    }
887
    //@}
888
889
    /*! Get the pointer to the gradients
890
     */
891
    virtual vector3 GetGradient(OBAtom *a, int /*terms*/ = OBFF_ENERGY)
892
420
    {
893
420
      const int coordIdx = (a->GetIdx() - 1) * 3;
894
420
      return _gradientPtr + coordIdx;
895
420
    }
896
897
    /*! Get the pointer to the gradients
898
     */
899
    double* GetGradientPtr()
900
0
    {
901
0
      return _gradientPtr;
902
0
    }
903
904
    /////////////////////////////////////////////////////////////////////////
905
    // Energy Evaluation                                                   //
906
    /////////////////////////////////////////////////////////////////////////
907
908
    //! \name Methods for energy evaluation
909
    //@{
910
    /*! \param gradients Set to true when the gradients need to be calculated
911
     *  (needs to be done before calling GetGradient()).
912
     *  \return Total energy.
913
     *   \par Output to log:
914
     *    OBFF_LOGLVL_NONE:   none \n
915
     *    OBFF_LOGLVL_LOW:    none \n
916
     *    OBFF_LOGLVL_MEDIUM: energy for individual energy terms \n
917
     *    OBFF_LOGLVL_HIGH:   energy for individual energy interactions \n
918
     */
919
0
    virtual double Energy(bool /*gradients*/ = true) { return 0.0f; }
920
    /*! \param gradients Set to true when the gradients need to be calculated
921
     *  (needs to be done before calling GetGradient()).
922
     *  \return Bond stretching energy.
923
     *   \par Output to log:
924
     *    see Energy()
925
     */
926
0
    virtual double E_Bond(bool /*gradients*/ = true) { return 0.0f; }
927
    /*! \param gradients Set to true when the gradients need to be calculated
928
     *  (needs to be done before calling GetGradient()).
929
     *  \return Angle bending energy.
930
     *  \par Output to log:
931
     *   see Energy()
932
     */
933
0
    virtual double E_Angle(bool /*gradients*/ = true) { return 0.0f; }
934
    /*! \param gradients Set to true when the gradients need to be calculated
935
     *  (needs to be done before calling GetGradient()).
936
     *  \return Stretch bending energy.
937
     *   \par Output to log:
938
     *    see Energy()
939
     */
940
0
    virtual double E_StrBnd(bool /*gradients*/ = true) { return 0.0f; }
941
    /*! \param gradients Set to true when the gradients need to be calculated
942
     *  (needs to be done before calling GetGradient()).
943
     *  \return Torsional energy.
944
     *    \par Output to log:
945
     *    see Energy()
946
     */
947
0
    virtual double E_Torsion(bool /*gradients*/ = true) { return 0.0f; }
948
    /*! \param gradients Set to true when the gradients need to be calculated
949
     *  (needs to be done before calling GetGradient()).
950
     *  \return Out-Of-Plane bending energy.
951
     *   \par Output to log:
952
     *    see Energy()
953
     */
954
0
    virtual double E_OOP(bool /*gradients*/ = true) { return 0.0f; }
955
    /*! \param gradients Set to true when the gradients need to be calculated
956
     *  (needs to be done before calling GetGradient()).
957
     *  \return Van der Waals energy.
958
     *   \par Output to log:
959
     *    see Energy()
960
     */
961
0
    virtual double E_VDW(bool /*gradients*/ = true) { return 0.0f; }
962
    /*! \param gradients Set to true when the gradients need to be calculated
963
     *  (needs to be done before calling GetGradient()).
964
     *  \return Electrostatic energy.
965
     *   \par Output to log:
966
     *    see Energy()
967
     */
968
0
    virtual double E_Electrostatic(bool /*gradients*/ = true) { return 0.0f; }
969
    //@}
970
971
    /////////////////////////////////////////////////////////////////////////
972
    // Logging                                                             //
973
    /////////////////////////////////////////////////////////////////////////
974
975
    //! \name Methods for logging
976
    //@{
977
    /*! Print the atom types to the log.
978
     */
979
    void PrintTypes();
980
    /*! Print the formal charges to the log (atom.GetPartialCharge(),
981
     *  MMFF94 FC's are not always int).
982
     */
983
    void PrintFormalCharges();
984
    /*! Print the partial charges to the log.
985
     */
986
    void PrintPartialCharges();
987
    /*! Print the velocities to the log.
988
     */
989
    void PrintVelocities();
990
    /*! Set the stream for logging (can also be &cout for logging to screen).
991
     *  \param pos Stream (when pos is 0, std::cout wil be used).
992
     *  \return True if successful.
993
     */
994
    bool SetLogFile(std::ostream *pos);
995
    /*! Set the log level (OBFF_LOGLVL_NONE, OBFF_LOGLVL_LOW, OBFF_LOGLVL_MEDIUM, OBFF_LOGLVL_HIGH).
996
     *  Inline if statements for logging are available:
997
     *  \code
998
     *  #define IF_OBFF_LOGLVL_LOW    if(_loglvl >= OBFF_LOGLVL_LOW)
999
     *  #define IF_OBFF_LOGLVL_MEDIUM if(_loglvl >= OBFF_LOGLVL_MEDIUM)
1000
     *  #define IF_OBFF_LOGLVL_HIGH   if(_loglvl >= OBFF_LOGLVL_HIGH)
1001
     *  \endcode
1002
     *
1003
     *  example:
1004
     *  \code
1005
     *  SetLogLevel(OBFF_LOGLVL_MEDIUM);
1006
     *  IF_OBFF_LOGLVL_HIGH {
1007
     *    OBFFLog("this text will NOT be logged...\n");
1008
     *  }
1009
     *
1010
     *  IF_OBFF_LOGLVL_LOW {
1011
     *    OBFFLog"this text will be logged...\n");
1012
     *  }
1013
     *
1014
     *  IF_OBFF_LOGLVL_MEDIUM {
1015
     *    OBFFLog("this text will also be logged...\n");
1016
     *  }
1017
     *  \endcode
1018
     */
1019
    bool SetLogLevel(int level);
1020
    /*! \return The log level.
1021
     */
1022
0
    int GetLogLevel() { return _loglvl; }
1023
    /*! Print msg to the logfile.
1024
     *  \param msg The message to print.
1025
     */
1026
    void OBFFLog(std::string msg)
1027
0
    {
1028
0
      if (!_logos)
1029
0
        return;
1030
0
1031
0
      *_logos << msg;
1032
0
    }
1033
    /*! Print msg to the logfile.
1034
     *  \param msg The message to print.
1035
     */
1036
    void OBFFLog(const char *msg)
1037
0
    {
1038
0
      if (!_logos)
1039
0
        return;
1040
1041
0
      *_logos << msg;
1042
0
    }
1043
    //@}
1044
1045
    /////////////////////////////////////////////////////////////////////////
1046
    // Structure Generation                                                //
1047
    /////////////////////////////////////////////////////////////////////////
1048
1049
    //! \name Methods for structure generation
1050
    //@{
1051
    //! Generate coordinates for the molecule (distance geometry)
1052
    //! \deprecated Use OBDistanceGeometry class instead
1053
    OB_DEPRECATED_MSG("Use OBDistanceGeometry class instead")
1054
    void DistanceGeometry();
1055
    /*! Generate conformers for the molecule (systematicaly rotating torsions).
1056
     *
1057
     *  The initial starting structure here is important, this structure should be
1058
     *  minimized for the best results. SystematicRotorSearch works by rotating around
1059
     *  the rotatable bond in a molecule (see OBRotamerList class). This rotating generates
1060
     *  multiple conformers. The energy for all these conformers is then evaluated and the
1061
     *  lowest energy conformer is selected.
1062
     *
1063
     *  \param geomSteps The number of steps to take during geometry optimization.
1064
     *  \param sampleRingBonds Whether to sample ring torsions.
1065
     *
1066
     *  \par Output to log:
1067
     *  This function should only be called with the log level set to OBFF_LOGLVL_NONE or OBFF_LOGLVL_LOW. Otherwise
1068
     *  too much information about the energy calculations needed for this function will interfere with the output for
1069
     *  this function. \n\n
1070
     *  OBFF_LOGLVL_NONE:   None. \n
1071
     *  OBFF_LOGLVL_LOW:    Number of rotatable bonds, energies for the conformers, which one is the lowest, ... \n
1072
     *  OBFF_LOGLVL_MEDIUM: See note above. \n
1073
     *  OBFF_LOGLVL_HIGH:   See note above. \n
1074
     */
1075
    void SystematicRotorSearch(unsigned int geomSteps = 2500, bool sampleRingBonds = false);
1076
    /*! Generate conformers for the molecule by systematicaly rotating torsions. To be used in combination with
1077
     *  SystematicRotorSearchNexConformer().
1078
     *
1079
     *  example:
1080
     *  \code
1081
     *  // pFF is a pointer to a OBForceField class
1082
     *  pFF->SystematicRotorSearchInitialize(300);
1083
     *  while (pFF->SystematicRotorSearchNextConformer(300)) {
1084
     *    // do some updating in your program (show last generated conformer, ...)
1085
     *  }
1086
     *  \endcode
1087
     *
1088
     *  If you don't need any updating in your program, SystematicRotorSearch() is recommended.
1089
     *
1090
     *  \param geomSteps The number of steps to take during geometry optimization.
1091
     *  \param sampleRingBonds Whether to sample ring torsions.
1092
     *  \return The number of conformers.
1093
     */
1094
    int SystematicRotorSearchInitialize(unsigned int geomSteps = 2500, bool sampleRingBonds = false);
1095
    /*! Evaluate the next conformer.
1096
     *  \param geomSteps The number of steps to take during geometry optimization.
1097
     *  \return True if there are more conformers.
1098
     */
1099
    bool SystematicRotorSearchNextConformer(unsigned int geomSteps = 2500);
1100
    /*! Generate conformers for the molecule (randomly rotating torsions).
1101
     *
1102
     *  The initial starting structure here is important, this structure should be
1103
     *  minimized for the best results. RandomRotorSearch works by randomly rotating around
1104
     *  the rotatable bonds in a molecule (see OBRotamerList class). This rotating generates
1105
     *  multiple conformers. The energy for all these conformers is then evaluated and the
1106
     *  lowest energy conformer is selected.
1107
     *
1108
     *  \param conformers The number of random conformers to consider during the search.
1109
     *  \param geomSteps The number of steps to take during geometry optimization for each conformer.
1110
     *  \param sampleRingBonds Whether to sample ring torsions.
1111
     *
1112
     *  \par Output to log:
1113
     *  This function should only be called with the log level set to OBFF_LOGLVL_NONE or OBFF_LOGLVL_LOW. Otherwise
1114
     *  too much information about the energy calculations needed for this function will interfere with the output for
1115
     *  this function. \n\n
1116
     *  OBFF_LOGLVL_NONE:   None. \n
1117
     *  OBFF_LOGLVL_LOW:    Number of rotatable bonds, energies for the conformers, which one is the lowest, ... \n
1118
     *  OBFF_LOGLVL_MEDIUM: See note above. \n
1119
     *  OBFF_LOGLVL_HIGH:   See note above. \n
1120
     */
1121
    void RandomRotorSearch(unsigned int conformers, unsigned int geomSteps = 2500,
1122
                           bool sampleRingBonds = false);
1123
    /*! Generate conformers for the molecule by randomly rotating torsions. To be used in combination with
1124
     *  RandomRotorSearchNexConformer().
1125
     *
1126
     *  example:
1127
     *  \code
1128
     *  // pFF is a pointer to a OBForceField class
1129
     *  pFF->RandomRotorSearchInitialize(300);
1130
     *  while (pFF->RandomRotorSearchNextConformer(300)) {
1131
     *    // do some updating in your program (show last generated conformer, ...)
1132
     *  }
1133
     *  \endcode
1134
     *
1135
     *  If you don't need any updating in your program, RandomRotorSearch() is recommended.
1136
     *
1137
     *  \param conformers The number of random conformers to consider during the search
1138
     *  \param geomSteps The number of steps to take during geometry optimization
1139
     *  \param sampleRingBonds Whether to sample ring torsions.
1140
     */
1141
    void RandomRotorSearchInitialize(unsigned int conformers, unsigned int geomSteps = 2500,
1142
                                     bool sampleRingBonds = false);
1143
    /*! Evaluate the next conformer.
1144
     *  \param geomSteps The number of steps to take during geometry optimization.
1145
     *  \return True if there are more conformers.
1146
     */
1147
    bool RandomRotorSearchNextConformer(unsigned int geomSteps = 2500);
1148
    /*! Generate conformers for the molecule (randomly rotating torsions).
1149
     *
1150
     *  The initial starting structure here is important, this structure should be
1151
     *  minimized for the best results. WeightedRotorSearch works by randomly rotating around
1152
     *  the rotatable bonds in a molecule (see OBRotamerList class). Unlike RandomRotorSearch()
1153
     *  the random choice of torsions is reweighted based on the energy of the generated conformer.
1154
     *  Over time, the generated conformers for each step should become increasingly better.
1155
     *  The lowest energy conformer is selected.
1156
     *
1157
     * \param conformers The number of random conformers to consider during the search.
1158
     * \param geomSteps The number of steps to take during geometry optimization for each conformer.
1159
     *  \param sampleRingBonds Whether to sample ring torsions.
1160
     *
1161
     *  \par Output to log:
1162
     *  This function should only be called with the log level set to OBFF_LOGLVL_NONE or OBFF_LOGLVL_LOW. Otherwise
1163
     *  too much information about the energy calculations needed for this function will interfere with the output for
1164
     *  this function. \n\n
1165
     *  OBFF_LOGLVL_NONE:   None. \n
1166
     *  OBFF_LOGLVL_LOW:    Number of rotatable bonds, energies for the conformers, which one is the lowest, ... \n
1167
     *  OBFF_LOGLVL_MEDIUM: See note above. \n
1168
     *  OBFF_LOGLVL_HIGH:   See note above. \n
1169
     */
1170
    void WeightedRotorSearch(unsigned int conformers, unsigned int geomSteps,
1171
                             bool sampleRingBonds = false);
1172
    /**
1173
     * @brief A fast rotor search to find low energy conformations
1174
     *
1175
     * Iterate over each of the rotors, and set the
1176
     * torsion angle to that which minimizes the energy (while keeping the rest of the molecule
1177
     * fixed). In general (for molecules with more than
1178
     * one rotatable bond), this procedure will not find
1179
     * the global minimum, but it will at least get rid of any bad
1180
     * clashes, and it do so quickly.
1181
     *
1182
     * Torsions closer to the center
1183
     * of the molecule will be optimized first as these most likely
1184
     * to generate large clashes.
1185
     *
1186
     * One possible use of this procedure is to prepare a reasonable 3D structure
1187
     * of a molecule for viewing. Another is to prepare the starting structure
1188
     * for a more systematic rotor search (in which case you should geometry
1189
     * optimize the final structure).
1190
     *
1191
     * @param permute Whether or not to permute the order of the 4 most central rotors.
1192
     *                Default is true. This does a more thorough search, but takes 4! = 24 times
1193
     *                as long.
1194
     * @since version 2.4
1195
     */
1196
    int FastRotorSearch(bool permute = true);
1197
1198
#ifdef HAVE_EIGEN3
1199
    //! \since version 2.4
1200
    int DiverseConfGen(double rmsd, unsigned int nconfs = 0, double energy_gap = 50, bool verbose = false);
1201
#endif
1202
1203
    /////////////////////////////////////////////////////////////////////////
1204
    // Energy Minimization                                                 //
1205
    /////////////////////////////////////////////////////////////////////////
1206
1207
    //! \name Methods for energy minimization
1208
    //@{
1209
    /*! Set the LineSearchType. The default type is LineSearchType::Newton2Num.
1210
     *  \param type The LineSearchType to be used in SteepestDescent and ConjugateGradients.
1211
     */
1212
    void SetLineSearchType(int type)
1213
0
    {
1214
0
      _linesearch = type;
1215
0
    }
1216
    /*! Get the LineSearchType.
1217
     *  \return The current LineSearchType.
1218
     */
1219
    int GetLineSearchType()
1220
0
    {
1221
0
      return _linesearch;
1222
0
    }
1223
    /*! Perform a linesearch starting at atom in direction direction.
1224
     * \deprecated Current code should use LineSearch(double *, double*) instead.
1225
     */
1226
    OB_DEPRECATED_MSG("Current code should use LineSearch(double *, double*) instead.")
1227
    vector3 LineSearch(OBAtom *atom, vector3 &direction);
1228
    /*! Perform a linesearch for the entire molecule in direction @p direction.
1229
     *  This function is called when using LineSearchType::Simple.
1230
     *
1231
     *  \param currentCoords Start coordinates.
1232
     *  \param direction The search direction.
1233
     *  \return alpha, The scale of the step we moved along the direction vector.
1234
     *
1235
     *  \par Output to log:
1236
     *  OBFF_LOGLVL_NONE:   none \n
1237
     *  OBFF_LOGLVL_LOW:    none \n
1238
     *  OBFF_LOGLVL_MEDIUM: none \n
1239
     *  OBFF_LOGLVL_HIGH:   none \n
1240
     */
1241
    double LineSearch(double *currentCoords, double *direction);
1242
    /*! Perform a linesearch for the entire molecule.
1243
     *  This function is called when using LineSearchType::Newton2Num.
1244
     *
1245
     *  \param direction The search direction.
1246
     *  \return alpha, The scale of the step we moved along the direction vector.
1247
     *
1248
     *  \par Output to log:
1249
     *  OBFF_LOGLVL_NONE:   none \n
1250
     *  OBFF_LOGLVL_LOW:    none \n
1251
     *  OBFF_LOGLVL_MEDIUM: none \n
1252
     *  OBFF_LOGLVL_HIGH:   none \n
1253
     */
1254
    double Newton2NumLineSearch(double *direction);
1255
    /*! Set the coordinates of the atoms to origCoord + step.
1256
     *  \param origCoords Start coordinates.
1257
     *  \param direction The search direction.
1258
     *  \param step The step to take.
1259
     */
1260
    void   LineSearchTakeStep(double *origCoords, double *direction, double step);
1261
    /*! Perform steepest descent optimalization for steps steps or until convergence criteria is reached.
1262
     *
1263
     *  \param steps The number of steps.
1264
     *  \param econv Energy convergence criteria. (defualt is 1e-6)
1265
     *  \param method Deprecated. (see HasAnalyticalGradients())
1266
     *
1267
     *  \par Output to log:
1268
     *  This function should only be called with the log level set to OBFF_LOGLVL_NONE or OBFF_LOGLVL_LOW. Otherwise
1269
     *  too much information about the energy calculations needed for the minimization will interfere with the list
1270
     *  of energies for succesive steps. \n\n
1271
     *  OBFF_LOGLVL_NONE:   none \n
1272
     *  OBFF_LOGLVL_LOW:    header including number of steps and first step \n
1273
     *  OBFF_LOGLVL_MEDIUM: see note above \n
1274
     *  OBFF_LOGLVL_HIGH:   see note above \n
1275
     */
1276
    void SteepestDescent(int steps, double econv = 1e-6f, int method = OBFF_ANALYTICAL_GRADIENT);
1277
    /*! Initialize steepest descent optimalization, to be used in combination with SteepestDescentTakeNSteps().
1278
     *
1279
     *  example:
1280
     *  \code
1281
     *  // pFF is a pointer to a OBForceField class
1282
     *  pFF->SteepestDescentInitialize(100, 1e-5f);
1283
     *  while (pFF->SteepestDescentTakeNSteps(5)) {
1284
     *    // do some updating in your program (redraw structure, ...)
1285
     *  }
1286
     *  \endcode
1287
     *
1288
     *  If you don't need any updating in your program, SteepestDescent() is recommended.
1289
     *
1290
     *  \param steps The number of steps.
1291
     *  \param econv Energy convergence criteria. (defualt is 1e-6)
1292
     *  \param method Deprecated. (see HasAnalyticalGradients())
1293
     *
1294
     *  \par Output to log:
1295
     *  This function should only be called with the log level set to OBFF_LOGLVL_NONE or OBFF_LOGLVL_LOW. Otherwise
1296
     *  too much information about the energy calculations needed for the minimization will interfere with the list
1297
     *  of energies for succesive steps. \n\n
1298
     *  OBFF_LOGLVL_NONE:   none \n
1299
     *  OBFF_LOGLVL_LOW:    header including number of steps \n
1300
     *  OBFF_LOGLVL_MEDIUM: see note above \n
1301
     *  OBFF_LOGLVL_HIGH:   see note above \n
1302
     */
1303
    void SteepestDescentInitialize(int steps = 1000, double econv = 1e-6f, int method = OBFF_ANALYTICAL_GRADIENT);
1304
    /*! Take n steps in a steepestdescent optimalization that was previously initialized with SteepestDescentInitialize().
1305
     *
1306
     *  \param n The number of steps to take.
1307
     *  \return False if convergence or the number of steps given by SteepestDescentInitialize() has been reached.
1308
     *
1309
     *  \par Output to log:
1310
     *  This function should only be called with the log level set to OBFF_LOGLVL_NONE or OBFF_LOGLVL_LOW. Otherwise
1311
     *  too much information about the energy calculations needed for the minimization will interfere with the list
1312
     *  of energies for succesive steps. \n\n
1313
     *  OBFF_LOGLVL_NONE:   none \n
1314
     *  OBFF_LOGLVL_LOW:    step number, energy and energy for the previous step \n
1315
     *  OBFF_LOGLVL_MEDIUM: see note above \n
1316
     *  OBFF_LOGLVL_HIGH:   see note above \n
1317
     */
1318
    bool SteepestDescentTakeNSteps(int n);
1319
    /*! Perform conjugate gradient optimalization for steps steps or until convergence criteria is reached.
1320
     *
1321
     *  \param steps The number of steps.
1322
     *  \param econv Energy convergence criteria. (defualt is 1e-6)
1323
     *  \param method Deprecated. (see HasAnalyticalGradients())
1324
     *
1325
     *  \par Output to log:
1326
     *  This function should only be called with the log level set to OBFF_LOGLVL_NONE or OBFF_LOGLVL_LOW. Otherwise
1327
     *  too much information about the energy calculations needed for the minimization will interfere with the list
1328
     *  of energies for succesive steps. \n\n
1329
     *  OBFF_LOGLVL_NONE:   none \n
1330
     *  OBFF_LOGLVL_LOW:    information about the progress of the minimization \n
1331
     *  OBFF_LOGLVL_MEDIUM: see note above \n
1332
     *  OBFF_LOGLVL_HIGH:   see note above \n
1333
     */
1334
    void ConjugateGradients(int steps, double econv = 1e-6f, int method = OBFF_ANALYTICAL_GRADIENT);
1335
    /*! Initialize conjugate gradient optimalization and take the first step, to be
1336
     *  used in combination with ConjugateGradientsTakeNSteps().
1337
     *
1338
     *  example:
1339
     *  \code
1340
     *  // pFF is a pointer to a OBForceField class
1341
     *  pFF->ConjugateGradientsInitialize(100, 1e-5f);
1342
     *  while (pFF->ConjugateGradientsTakeNSteps(5)) {
1343
     *    // do some updating in your program (redraw structure, ...)
1344
     *  }
1345
     *  \endcode
1346
     *
1347
     *  If you don't need any updating in your program, ConjugateGradients() is recommended.
1348
     *
1349
     *  \param steps The number of steps.
1350
     *  \param econv Energy convergence criteria. (defualt is 1e-6)
1351
     *  \param method Deprecated. (see HasAnalyticalGradients())
1352
     *
1353
     *  \par Output to log:
1354
     *  This function should only be called with the log level set to OBFF_LOGLVL_NONE or OBFF_LOGLVL_LOW. Otherwise
1355
     *  too much information about the energy calculations needed for the minimization will interfere with the list
1356
     *  of energies for succesive steps. \n\n
1357
     *  OBFF_LOGLVL_NONE:   none \n
1358
     *  OBFF_LOGLVL_LOW:    header including number of steps and first step \n
1359
     *  OBFF_LOGLVL_MEDIUM: see note above \n
1360
     *  OBFF_LOGLVL_HIGH:   see note above \n
1361
     */
1362
    void ConjugateGradientsInitialize(int steps = 1000, double econv = 1e-6f, int method = OBFF_ANALYTICAL_GRADIENT);
1363
    /*! Take n steps in a conjugate gradient optimalization that was previously
1364
     *  initialized with ConjugateGradientsInitialize().
1365
     *
1366
     *  \param n The number of steps to take.
1367
     *  \return False if convergence or the number of steps given by ConjugateGradientsInitialize() has been reached.
1368
     *
1369
     *  \par Output to log:
1370
     *  This function should only be called with the log level set to OBFF_LOGLVL_NONE or OBFF_LOGLVL_LOW. Otherwise
1371
     *  too much information about the energy calculations needed for the minimization will interfere with the list
1372
     *  of energies for succesive steps. \n\n
1373
     *  OBFF_LOGLVL_NONE:   none \n
1374
     *  OBFF_LOGLVL_LOW:    step number, energy and energy for the previous step \n
1375
     *  OBFF_LOGLVL_MEDIUM: see note above \n
1376
     *  OBFF_LOGLVL_HIGH:   see note above \n
1377
    */
1378
    bool ConjugateGradientsTakeNSteps(int n);
1379
    /*! Perform L-BFGS optimization for steps steps or until convergence criteria is reached.
1380
     *
1381
     *  L-BFGS is a quasi-Newton method that approximates the inverse Hessian
1382
     *  from a limited history of gradient changes. For typical molecular
1383
     *  systems it converges faster than steepest descent or conjugate
1384
     *  gradients while using comparable memory.
1385
     *
1386
     *  Note: the line search algorithm chosen via SetLineSearchType()
1387
     *  (Simple, Newton2Num) does NOT apply here. L-BFGS uses an internal
1388
     *  backtracking line search with the Armijo condition; mixing in an
1389
     *  arbitrary line search would break the curvature approximation.
1390
     *
1391
     *  \param steps The number of steps.
1392
     *  \param econv Energy convergence criteria. (default is 1e-6)
1393
     *  \param method Deprecated. (see HasAnalyticalGradients())
1394
     */
1395
    void LBFGS(int steps, double econv = 1e-6f, int method = OBFF_ANALYTICAL_GRADIENT);
1396
    /*! Initialize L-BFGS optimization, to be used in combination with LBFGSTakeNSteps().
1397
     *
1398
     *  example:
1399
     *  \code
1400
     *  // pFF is a pointer to an OBForceField class
1401
     *  pFF->LBFGSInitialize(100, 1e-5f);
1402
     *  while (pFF->LBFGSTakeNSteps(5)) {
1403
     *    // do some updating in your program (redraw structure, ...)
1404
     *  }
1405
     *  \endcode
1406
     *
1407
     *  If you don't need any updating in your program, LBFGS() is recommended.
1408
     *
1409
     *  \param steps The number of steps.
1410
     *  \param econv Energy convergence criteria. (default is 1e-6)
1411
     *  \param method Deprecated. (see HasAnalyticalGradients())
1412
     */
1413
    void LBFGSInitialize(int steps = 1000, double econv = 1e-6f, int method = OBFF_ANALYTICAL_GRADIENT);
1414
    /*! Take n steps in an L-BFGS optimization previously initialized with LBFGSInitialize().
1415
     *
1416
     *  \param n The number of steps to take.
1417
     *  \return False if convergence or the number of steps given by LBFGSInitialize() has been reached.
1418
     */
1419
    bool LBFGSTakeNSteps(int n);
1420
    //@}
1421
1422
    /////////////////////////////////////////////////////////////////////////
1423
    // Molecular Dynamics                                                  //
1424
    /////////////////////////////////////////////////////////////////////////
1425
1426
    //! \name Methods for molecular dynamics
1427
    //@{
1428
    /*! Generate starting velocities with a Maxwellian distribution.
1429
     */
1430
    void GenerateVelocities();
1431
    /*! Correct the velocities so that the following is true:
1432
     *
1433
     *  \code
1434
     *        3N
1435
     *       ----
1436
     *  0.5  \    m_i * v_i^2 = 0.5 * Ndf * R * T = E_kin
1437
     *       /
1438
     *       ----
1439
     *       i=1
1440
     *
1441
     *  E_kin : kinetic energy
1442
     *  m_i : mass of atom i
1443
     *  v_i : velocity of atom i
1444
     *  Ndf : number of degrees of freedom (3 * number of atoms)
1445
     *  R : gas constant
1446
     *  T : temperature
1447
     *  \endcode
1448
     *
1449
     */
1450
    void CorrectVelocities();
1451
    /*! Take n steps at temperature T. If no velocities are set, they will be generated.
1452
     *
1453
     *  example:
1454
     *  \code
1455
     *  // pFF is a pointer to a OBForceField class
1456
     *  while (pFF->MolecularDynamicsTakeNSteps(5, 300)) {
1457
     *    // do some updating in your program (redraw structure, ...)
1458
     *  }
1459
     * \endcode
1460
     *
1461
     *  \param n The number of steps to take.
1462
     *  \param T Absolute temperature in Kelvin.
1463
     *  \param timestep The time step in picoseconds. (10e-12 s)
1464
     *  \param method OBFF_ANALYTICAL_GRADIENTS (default) or OBFF_NUMERICAL_GRADIENTS
1465
     */
1466
    void MolecularDynamicsTakeNSteps(int n, double T, double timestep = 0.001, int method = OBFF_ANALYTICAL_GRADIENT);
1467
    //@}
1468
1469
    /////////////////////////////////////////////////////////////////////////
1470
    // Constraints                                                         //
1471
    /////////////////////////////////////////////////////////////////////////
1472
1473
    //! \name Methods for constraints
1474
    //@{
1475
    /*! Get the current constraints.
1476
     *  \return The current constrains stored in the force field.
1477
     */
1478
    OBFFConstraints& GetConstraints();
1479
    /*! Set the constraints.
1480
     *  \param constraints The new constraints to be used.
1481
     */
1482
    void SetConstraints(OBFFConstraints& constraints);
1483
    /*! Fix the atom position until UnsetFixAtom() is called. This function
1484
     *  can be used in programs that allow the user to interact with a molecule
1485
     *  that is being minimized without having to check if the atom is already
1486
     *  fixed in the constraints set by Setup() or SetConstraints(). Using this
1487
     *  makes sure the selected atom follows the mouse cursur.
1488
     *  \param index The index for the atom to fix.
1489
     */
1490
    void SetFixAtom(int index);
1491
    /*! Undo last SetFixAtom. This function will not remove the fix atom
1492
     *  constraint for this atom if set by Setup() or SetConstraints().
1493
     */
1494
    void UnsetFixAtom();
1495
    /*! Ignore the atom until UnsetIgnoreAtom() is called. This function
1496
     *  can be used in programs that allow the user to interact with a molecule
1497
     *  that is being minimized without having to check if the atom is already
1498
     *  ignored in the constraints set by Setup() or SetConstraints(). Using this
1499
     *  makes sure, in drawing mode, you can close rings without your newly
1500
     *  created puching the other atoms away.
1501
     *  \param index The index for the atom to ignore.
1502
     */
1503
    void SetIgnoreAtom(int index);
1504
    /*! Undo last SetIgnoreAtom. This function will not remove the ignore atom
1505
     *  constraint for this atom if set by Setup() or SetConstraints().
1506
     */
1507
    void UnsetIgnoreAtom();
1508
1509
    //! internal function
1510
    static bool IgnoreCalculation(int a, int b);
1511
    //! internal function
1512
    static bool IgnoreCalculation(int a, int b, int c);
1513
    //! internal function
1514
    static bool IgnoreCalculation(int a, int b, int c, int d);
1515
    //@}
1516
1517
1518
    /////////////////////////////////////////////////////////////////////////
1519
    // Validation                                                          //
1520
    /////////////////////////////////////////////////////////////////////////
1521
1522
    //! \name Methods for forcefield validation
1523
    //@{
1524
    //! (debugging)
1525
    bool DetectExplosion();
1526
    //! (debugging)
1527
    vector3 ValidateLineSearch(OBAtom *atom, vector3 &direction);
1528
    //! (debugging)
1529
    void ValidateSteepestDescent(int steps);
1530
    //! (debugging)
1531
    void ValidateConjugateGradients(int steps);
1532
    //! Validate the force field implementation (debugging)
1533
0
    virtual bool Validate() { return false; }
1534
    /*!
1535
      Validate the analytical gradients by comparing them to numerical ones. This function has to
1536
      be implemented force field specific. (debugging)
1537
    */
1538
0
    virtual bool ValidateGradients() { return false; }
1539
    /*!
1540
      Calculate the error of the analytical gradient (debugging)
1541
      \return  error = fabs(numgrad - anagrad) / anagrad * 100%
1542
    */
1543
    vector3 ValidateGradientError(vector3 &numgrad, vector3 &anagrad);
1544
    //@}
1545
1546
    /////////////////////////////////////////////////////////////////////////
1547
    // Vector Analysis                                                     //
1548
    /////////////////////////////////////////////////////////////////////////
1549
1550
    //! \name Methods for vector analysis (used by OBFFXXXXCalculationYYYY)
1551
    //@{
1552
    /*! Calculate the derivative of a vector length. The vector is given by a - b,
1553
     * the length of this vector rab = sqrt(ab.x^2 + ab.y^2 + ab.z^2).
1554
     * \param pos_a atom a (coordinates)
1555
     * \param pos_b atom b (coordinates)
1556
     * \param force_a - return value for the force on atom a
1557
     * \param force_b - return value for the force on atom b
1558
     * \return The distance between a and b (bondlength for bond stretching, separation for vdw, electrostatic)
1559
     */
1560
    static double VectorBondDerivative(double *pos_a, double *pos_b,
1561
                                       double *force_a, double *force_b);
1562
    /*! To be used for VDW or Electrostatic interactions. This
1563
     *  is faster than VectorBondDerivative, but does no error checking.
1564
     */
1565
    static double VectorDistanceDerivative(const double* const pos_i, const double* const pos_j,
1566
                                           double *force_i, double *force_j);
1567
    //! \deprecated
1568
    OB_DEPRECATED
1569
    static double VectorLengthDerivative(vector3 &a, vector3 &b);
1570
1571
    /*! Calculate the derivative of a angle a-b-c. The angle is given by dot(ab,cb)/rab*rcb.
1572
     *  Used for harmonic (cubic) angle potentials.
1573
     * \param pos_a atom a (coordinates)
1574
     * \param pos_b atom b (coordinates)
1575
     * \param pos_c atom c (coordinates)
1576
     * \param force_a - return value for the force on atom a
1577
     * \param force_b - return value for the force on atom b
1578
     * \param force_c - return value for the force on atom c
1579
     * \return The angle between a-b-c
1580
     */
1581
    static double VectorAngleDerivative(double *pos_a, double *pos_b, double *pos_c,
1582
                                        double *force_a, double *force_b, double *force_c);
1583
    //! \deprecated
1584
    OB_DEPRECATED
1585
    static double VectorAngleDerivative(vector3 &a, vector3 &b, vector3 &c);
1586
    /*! Calculate the derivative of a OOP angle a-b-c-d. b is the central atom, and a-b-c is the plane.
1587
     * The OOP angle is given by 90° - arccos(dot(corss(ab,cb),db)/rabbc*rdb).
1588
     * \param pos_a atom a (coordinates)
1589
     * \param pos_b atom b (coordinates)
1590
     * \param pos_c atom c (coordinates)
1591
     * \param pos_d atom d (coordinates)
1592
     * \param force_a - return value for the force on atom a
1593
     * \param force_b - return value for the force on atom b
1594
     * \param force_c - return value for the force on atom c
1595
     * \param force_d - return value for the force on atom d
1596
     * \return The OOP angle for a-b-c-d
1597
     */
1598
    static double VectorOOPDerivative(double *pos_a, double *pos_b, double *pos_c, double *pos_d,
1599
                                      double *force_a, double *force_b, double *force_c, double *force_d);
1600
    //! \deprecated
1601
    OB_DEPRECATED
1602
    static double VectorOOPDerivative(vector3 &a, vector3 &b, vector3 &c, vector3 &d);
1603
    /*! Calculate the derivative of a torsion angle a-b-c-d. The torsion angle is given by arccos(dot(corss(ab,bc),cross(bc,cd))/rabbc*rbccd).
1604
     * \param pos_a atom a (coordinates)
1605
     * \param pos_b atom b (coordinates)
1606
     * \param pos_c atom c (coordinates)
1607
     * \param pos_d atom d (coordinates)
1608
     * \param force_a - return value for the force on atom a
1609
     * \param force_b - return value for the force on atom b
1610
     * \param force_c - return value for the force on atom c
1611
     * \param force_d - return value for the force on atom d
1612
     * \return The tosion angle for a-b-c-d
1613
     */
1614
    static double VectorTorsionDerivative(double *pos_a, double *pos_b, double *pos_c, double *pos_d,
1615
                                          double *force_a, double *force_b, double *force_c, double *force_d);
1616
    //! \deprecated
1617
    OB_DEPRECATED
1618
    static double VectorTorsionDerivative(vector3 &a, vector3 &b, vector3 &c, vector3 &d);
1619
1620
    /*! inline fuction to speed up minimization speed
1621
     * \param i pointer to i[3]
1622
     * \param j pointer to j[3]
1623
     * \param result pointer to result[3], will be set to i - j
1624
     */
1625
    static void VectorSubtract(double *i, double *j, double *result)
1626
0
    {
1627
0
      for (unsigned int c = 0; c < 3; ++c)
1628
0
        result[c] = i[c] - j[c];
1629
0
    }
1630
1631
    static void VectorSubtract(const double* const i, const double* const j, double *result)
1632
0
    {
1633
0
      for (unsigned int c = 0; c < 3; ++c)
1634
0
        result[c] = i[c] - j[c];
1635
0
    }
1636
1637
    /*! inline fuction to speed up minimization speed
1638
     * \param i pointer to i[3]
1639
     * \param j pointer to j[3]
1640
     * \param result pointer to result[3], will be set to i + j
1641
     */
1642
    static void VectorAdd(double *i, double *j, double *result)
1643
0
    {
1644
0
      for (unsigned int c = 0; c < 3; ++c)
1645
0
        result[c] = i[c] + j[c];
1646
0
    }
1647
1648
    /*! inline fuction to speed up minimization speed
1649
     * \param i pointer to i[3]
1650
     * \param n divide x,y,z with n
1651
     * \param result pointer to result[3]
1652
     */
1653
    static void VectorDivide(double *i, double n, double *result)
1654
0
    {
1655
0
      const double inv_n = 1.0 / n;
1656
0
      result[0] = i[0] * inv_n;
1657
0
      result[1] = i[1] * inv_n;
1658
0
      result[2] = i[2] * inv_n;
1659
0
    }
1660
1661
    /*! inline fuction to speed up minimization speed
1662
     * \param i pointer to i[3]
1663
     * \param n multiply x,y,z with n
1664
     * \param result pointer to result[3]
1665
     */
1666
    static void VectorMultiply(double *i, double n, double *result)
1667
0
    {
1668
0
      for (unsigned int c = 0; c < 3; ++c)
1669
0
        result[c] = i[c] * n;
1670
0
    }
1671
1672
    static void VectorMultiply(const double* const i, const double n, double *result)
1673
0
    {
1674
0
      for (unsigned int c = 0; c < 3; ++c)
1675
0
        result[c] = i[c] * n;
1676
0
    }
1677
1678
    /*! inline fuction to speed up minimization speed
1679
     * \param i pointer to i[3], multiply this vector by n and set this vector to the result.
1680
     * \param n the scalar value to be multipled
1681
     */
1682
    static void VectorSelfMultiply(double *i, double n)
1683
0
    {
1684
0
      for (unsigned int c = 0; c < 3; ++c)
1685
0
        i[c] *= n;
1686
0
    }
1687
1688
    /*! inline fuction to speed up minimization speed
1689
     * \param i pointer to i[3] to be normalized
1690
     */
1691
    static void VectorNormalize(double *i)
1692
0
    {
1693
0
      const double inv_length = 1.0 / VectorLength(i);
1694
0
      i[0] *= inv_length;
1695
0
      i[1] *= inv_length;
1696
0
      i[2] *= inv_length;
1697
0
    }
1698
1699
    /*! inline fuction to speed up minimization speed
1700
     * \param from pointer to i[3] to be copied from
1701
     * \param to pointer to j[3] to be copied to
1702
     */
1703
    static void VectorCopy(double *from, double *to)
1704
0
    {
1705
0
      for (unsigned int c = 0; c < 3; ++c)
1706
0
        to[c] = from[c];
1707
0
    }
1708
1709
    /*! inline fuction to speed up minimization speed
1710
     * \param i pointer to i[3]
1711
     * \return the vector length
1712
     */
1713
    static double VectorLength(double *i)
1714
0
    {
1715
0
      return sqrt( i[0]*i[0] + i[1]*i[1] + i[2]*i[2] );
1716
0
    }
1717
1718
    static double VectorDistance(double *pos_i, double *pos_j)
1719
0
    {
1720
0
      double ij[3];
1721
0
      VectorSubtract(pos_i, pos_j, ij);
1722
0
      const double rij = VectorLength(ij);
1723
0
      return rij;
1724
0
    }
1725
1726
    /*! inline fuction to speed up minimization speed
1727
     * \param i pointer to i[3]
1728
     * \param j pointer to j[3]
1729
     * \param k pointer to k[3]
1730
     * \return the vector angle ijk (deg)
1731
     */
1732
    static double VectorAngle(double *i, double *j, double *k);
1733
1734
    /*! inline fuction to speed up minimization speed
1735
     * \param i pointer to i[3]
1736
     * \param j pointer to j[3]
1737
     * \param k pointer to k[3]
1738
     * \param l pointer to l[3]
1739
     * \return the vector torson ijkl (deg)
1740
     */
1741
    static double VectorTorsion(double *i, double *j, double *k, double *l);
1742
1743
    /*! inline fuction to speed up minimization speed
1744
     * \param i pointer to i[3]
1745
     * \param j pointer to j[3]
1746
     * \param k pointer to k[3]
1747
     * \param l pointer to l[3]
1748
     * \return the vector torson ijkl (deg)
1749
     */
1750
    static double VectorOOP(double *i, double *j, double *k, double *l);
1751
1752
    /*! inline fuction to speed up minimization speed
1753
     * \param i pointer to i[3], will set x,y,z to 0,0,0
1754
     */
1755
    static void VectorClear(double *i)
1756
0
    {
1757
0
      for (unsigned int c = 0; c < 3; ++c)
1758
0
        i[c] = 0.0;
1759
0
    }
1760
1761
    /*! inline fuction to speed up minimization speed
1762
     * \param i pointer to i[3]
1763
     * \param j pointer to j[3]
1764
     * \return the dot product
1765
     */
1766
    static double VectorDot(double *i, double *j)
1767
0
    {
1768
0
      double result = 0.0;
1769
      // Written as a loop for vectorization
1770
      // Loop will be unrolled by compiler otherwise
1771
0
      for (unsigned int c = 0; c < 3; ++c)
1772
0
        result += i[c]*j[c];
1773
0
      return result;
1774
0
    }
1775
1776
    /*! inline fuction to speed up minimization speed
1777
     * \param i pointer to i[3]
1778
     * \param j pointer to j[3]
1779
     * \param result the dot product (as a return value double[3])
1780
     */
1781
    static void VectorCross(double *i, double *j, double *result)
1782
0
    {
1783
0
      result[0] =   i[1]*j[2] - i[2]*j[1];
1784
0
      result[1] = - i[0]*j[2] + i[2]*j[0];
1785
0
      result[2] =   i[0]*j[1] - i[1]*j[0];
1786
0
    }
1787
1788
    static void PrintVector(double *i)
1789
0
    {
1790
0
      std::cout << "<" << i[0] << ", " << i[1] << ", " << i[2] << ">" << std::endl;
1791
0
    }
1792
    //@}
1793
1794
  }; // class OBForceField
1795
1796
}// namespace OpenBabel
1797
1798
#endif   // OB_FORCEFIELD_H
1799
1800
//! \file forcefield.h
1801
//! \brief Handle forcefields