File: MIFDescriptors.cpp

package info (click to toggle)
rdkit 202503.1-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 220,160 kB
  • sloc: cpp: 399,240; python: 77,453; ansic: 25,517; java: 8,173; javascript: 4,005; sql: 2,389; yacc: 1,565; lex: 1,263; cs: 1,081; makefile: 580; xml: 229; fortran: 183; sh: 105
file content (1983 lines) | stat: -rw-r--r-- 74,101 bytes parent folder | download | duplicates (2)
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
//
//  Copyright (c) 2014-2024, Novartis Institutes for BioMedical Research and
//  other RDKit contributors
//
//   @@ 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 "MIFDescriptors.h"
#include <Geometry/point.h>
#include <Geometry/UniformRealValueGrid3D.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <RDGeneral/FileParseException.h>
#include <RDGeneral/BadFileException.h>
#include <GraphMol/ForceFieldHelpers/MMFF/AtomTyper.h>
#include <ForceField/MMFF/Nonbonded.h>
#include <ForceField/UFF/Nonbonded.h>
#include <ForceField/UFF/Params.h>
#include <vector>
#include <iostream>
#include <fstream>

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923
#endif

namespace {
constexpr double M_55D = 0.95993108859688126730;
// angle C-O-H , C-N-H
constexpr double M_70_5D = 1.23045712265600235173;
constexpr double M_110D = 1.91986217719376253461;

constexpr double CUTOFF = 0.001;
constexpr double MIN_CUTOFF_VAL = CUTOFF * CUTOFF;
}  // namespace

namespace RDMIF {

std::unique_ptr<RDGeom::UniformRealValueGrid3D> constructGrid(
    const RDKit::ROMol &mol, int confId, double margin, double spacing) {
  PRECONDITION(mol.getNumConformers(), "No conformers available for molecule.");

  const std::vector<RDGeom::Point3D> &ptVect =
      mol.getConformer(confId).getPositions();
  RDGeom::Point3D originPt(0.0, 0.0, 0.0);
  RDGeom::Point3D marginPt(margin, margin, margin);
  const RDGeom::Point3D &firstPoint =
      (!ptVect.empty() ? ptVect.front() : originPt);

  auto minPt = firstPoint;
  auto maxPt = minPt;
  for (const auto &pt : ptVect) {
    for (auto i = 0u; i < pt.dimension(); ++i) {
      minPt[i] = std::min(minPt[i], pt[i]);
      maxPt[i] = std::max(maxPt[i], pt[i]);
    }
  }
  minPt -= marginPt;
  maxPt += marginPt;

  auto res = std::make_unique<RDGeom::UniformRealValueGrid3D>(
      maxPt.x - minPt.x, maxPt.y - minPt.y, maxPt.z - minPt.z, spacing, &minPt);

  return res;
}

VdWaals::VdWaals(const RDKit::ROMol &mol, int confId, double cutoff) {
  d_cutoff = std::max(cutoff * cutoff, MIN_CUTOFF_VAL);
  d_nAtoms = mol.getNumAtoms();
  d_pos.reserve(3 * d_nAtoms);
  d_R_star_ij.reserve(d_nAtoms);
  d_wellDepth.reserve(d_nAtoms);
  // this will throw a ConformerException if confId does not exist
  const RDKit::Conformer &conf = mol.getConformer(confId);
  d_mol.reset(new RDKit::ROMol(mol, false, conf.getId()));
}

void VdWaals::fillVectors() {
  const auto &conf = d_mol->getConformer();
  for (unsigned int i = 0; i < d_nAtoms; i++) {
    const RDGeom::Point3D &pt = conf.getAtomPos(i);
    d_pos.push_back(pt.x);
    d_pos.push_back(pt.y);
    d_pos.push_back(pt.z);
    fillVdwParamVectors(i);
  }
}

MMFFVdWaals::MMFFVdWaals(const RDKit::ROMol &mol, int confId,
                         unsigned int probeAtomType, bool scaling,
                         double cutoff)
    : VdWaals::VdWaals(mol, confId, cutoff), d_scaling(scaling) {
  d_props.reset(new RDKit::MMFF::MMFFMolProperties(*d_mol));
  if (!d_props->isValid()) {
    throw ValueErrorException(
        "No MMFF atom types available for at least one atom in molecule.");
  }
  d_mmffVdW = RDKit::MMFF::DefaultParameters::getMMFFVdW();
  d_probeParams = (*d_mmffVdW)(probeAtomType);
  fillVectors();
}

void MMFFVdWaals::fillVdwParamVectors(unsigned int atomIdx) {
  PRECONDITION(atomIdx < d_mol->getNumAtoms(), "atomIdx out of bounds");
  const auto iAtomType = d_props->getMMFFAtomType(atomIdx);
  auto params = (*d_mmffVdW)(iAtomType);
  auto rStarIJ = ForceFields::MMFF::Utils::calcUnscaledVdWMinimum(
      d_mmffVdW, params, d_probeParams);
  d_R_star_ij.push_back(rStarIJ);
  d_wellDepth.push_back(ForceFields::MMFF::Utils::calcUnscaledVdWWellDepth(
      rStarIJ, params, d_probeParams));
  // scaling for taking undirected H-Bonds into account
  if (d_scaling) {
    ForceFields::MMFF::Utils::scaleVdWParams(d_R_star_ij[atomIdx],
                                             d_wellDepth[atomIdx], d_mmffVdW,
                                             params, d_probeParams);
  }
}

UFFVdWaals::UFFVdWaals(const RDKit::ROMol &mol, int confId,
                       const std::string &probeAtomType, double cutoff)
    : VdWaals::VdWaals(mol, confId, cutoff) {
  d_uffParamColl = ForceFields::UFF::ParamCollection::getParams();
  d_probeParams = (*d_uffParamColl)(probeAtomType);
  const auto [params, haveParams] = RDKit::UFF::getAtomTypes(mol);
  if (!haveParams) {
    throw ValueErrorException(
        "No UFF atom types available for at least one atom in molecule.");
  }
  d_params = std::move(params);
  fillVectors();
}

void UFFVdWaals::fillVdwParamVectors(unsigned int atomIdx) {
  PRECONDITION(atomIdx < d_mol->getNumAtoms(), "atomIdx out of bounds");
  d_R_star_ij.push_back(d_probeParams->x1 * d_params[atomIdx]->x1);
  d_wellDepth.push_back(ForceFields::UFF::Utils::calcNonbondedDepth(
      d_probeParams, d_params[atomIdx]));
}

double VdWaals::operator()(double x, double y, double z, double thres) const {
  double res = 0.0;
  for (unsigned int i = 0, j = 0; i < d_nAtoms; ++i) {
    auto temp = x - d_pos[j++];
    auto dist2 = temp * temp;
    temp = y - d_pos[j++];
    dist2 += temp * temp;
    temp = z - d_pos[j++];
    dist2 += temp * temp;
    if (dist2 < thres) {
      dist2 = std::max(dist2, d_cutoff);
      res += calcEnergy(dist2, d_R_star_ij[i], d_wellDepth[i]);
    }
  }
  return res;
}

double UFFVdWaals::calcEnergy(double dist2, double x_ij,
                              double wellDepth) const {
  double r6 = x_ij / dist2;
  r6 *= r6 * r6;
  double r12 = r6 * r6;
  return wellDepth * (r12 - 2.0 * r6);
}

double MMFFVdWaals::calcEnergy(double dist2, double R_star_ij,
                               double wellDepth) const {
  return ForceFields::MMFF::Utils::calcVdWEnergy(sqrt(dist2), R_star_ij,
                                                 wellDepth);
}

namespace CoulombDetail {
constexpr double prefactor =
    1 / (4.0 * 3.141592 * 8.854188) * 1.602 * 1.602 * 6.02214129 * 10000;
}

Coulomb::Coulomb(const std::vector<double> &charges,
                 const std::vector<RDGeom::Point3D> &positions,
                 double probeCharge, bool absVal, double alpha, double cutoff)
    : d_nAtoms(charges.size()),
      d_absVal(absVal),
      d_cutoff(cutoff * cutoff),
      d_probe(probeCharge),
      d_alpha(alpha),
      d_charges(charges) {
  PRECONDITION(d_charges.size() == positions.size(),
               "Lengths of positions and charges vectors do not match.");
  d_pos.reserve(3 * d_nAtoms);
  for (const auto &position : positions) {
    d_pos.push_back(position.x);
    d_pos.push_back(position.y);
    d_pos.push_back(position.z);
  }
  if (fabs(d_alpha) < MIN_CUTOFF_VAL) {
    d_softcore = false;
    if (d_cutoff < MIN_CUTOFF_VAL) {
      d_cutoff = CUTOFF;
    }
  } else {
    d_softcore = true;
  }
}

Coulomb::Coulomb(const RDKit::ROMol &mol, int confId, double probeCharge,
                 bool absVal, const std::string &prop, double alpha,
                 double cutoff)
    : d_nAtoms(mol.getNumAtoms()),
      d_absVal(absVal),
      d_cutoff(cutoff * cutoff),
      d_probe(probeCharge),
      d_alpha(alpha) {
  d_charges.reserve(d_nAtoms);
  d_pos.reserve(3 * d_nAtoms);
  RDKit::Conformer conf = mol.getConformer(confId);
  for (unsigned int i = 0; i < d_nAtoms; ++i) {
    d_charges.push_back(mol.getAtomWithIdx(i)->getProp<double>(prop));
    const RDGeom::Point3D &pt = conf.getAtomPos(i);
    d_pos.push_back(pt.x);
    d_pos.push_back(pt.y);
    d_pos.push_back(pt.z);
  }
  if (fabs(d_alpha) < MIN_CUTOFF_VAL) {
    d_softcore = false;
    if (d_cutoff < MIN_CUTOFF_VAL) {
      d_cutoff = CUTOFF;
    }
  } else {
    d_softcore = true;
  }
}

double Coulomb::operator()(double x, double y, double z, double thres) const {
  double res = 0.0, dist2, temp;
  if (d_softcore) {
    for (unsigned int i = 0, j = 0; i < d_nAtoms; i++) {
      temp = x - d_pos[j++];
      dist2 = temp * temp;
      temp = y - d_pos[j++];
      dist2 += temp * temp;
      temp = z - d_pos[j++];
      dist2 += temp * temp;
      if (dist2 < thres) {
        res += d_charges[i] * (1.0 / sqrt(d_alpha + dist2));
      }
    }
  } else {
    for (unsigned int i = 0, j = 0; i < d_nAtoms; i++) {
      temp = x - d_pos[j++];
      dist2 = temp * temp;
      temp = y - d_pos[j++];
      dist2 += temp * temp;
      temp = z - d_pos[j++];
      dist2 += temp * temp;
      if (dist2 < thres) {
        dist2 = std::max(dist2, d_cutoff);
        res += d_charges[i] * (1.0 / sqrt(dist2));
      }
    }
  }
  res *= CoulombDetail::prefactor * d_probe;
  if (d_absVal) {
    res = -fabs(
        res);  // takes the negative absolute value of the interaction energy
  }
  return res;
}

CoulombDielectric::CoulombDielectric(
    const std::vector<double> &charges,
    const std::vector<RDGeom::Point3D> &positions, double probeCharge,
    bool absVal, double alpha, double cutoff, double epsilon, double xi)
    : d_nAtoms(charges.size()),
      d_absVal(absVal),
      d_cutoff(cutoff * cutoff),
      d_probe(probeCharge),
      d_epsilon(epsilon),
      d_xi(xi),
      d_alpha(alpha),
      d_charges(charges) {
  PRECONDITION(d_charges.size() == positions.size(),
               "Lengths of position and charge vectors do not match.");
  d_dielectric = (d_xi - d_epsilon) / (d_xi + d_epsilon);
  std::vector<unsigned int> neighbors(positions.size(), 0);

  d_dists.resize(d_nAtoms);
  d_sp.reserve(d_nAtoms);
  d_pos.reserve(3 * d_nAtoms);
  for (unsigned int i = 0; i < positions.size(); ++i) {
    d_pos.push_back(positions[i].x);
    d_pos.push_back(positions[i].y);
    d_pos.push_back(positions[i].z);
    for (unsigned int j = i + 1; j < positions.size(); ++j) {
      double dis = (positions[j] - positions[i]).length();
      if (dis < 4.0) {
        ++neighbors[i];
        ++neighbors[j];
      }
    }
  }
  for (unsigned int neighbor : neighbors) {
    switch (neighbor) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
        d_sp.push_back(0.0);
        break;
      case 7:
        d_sp.push_back(.4);
        break;
      case 8:
        d_sp.push_back(.9);
        break;
      case 9:
        d_sp.push_back(1.4);
        break;
      case 10:
        d_sp.push_back(1.9);
        break;
      case 11:
        d_sp.push_back(2.6);
        break;
      default:
        d_sp.push_back(4.0);
    }
  }
  if (fabs(d_alpha) < MIN_CUTOFF_VAL) {
    d_softcore = false;
    if (d_cutoff < MIN_CUTOFF_VAL * MIN_CUTOFF_VAL) {
      d_cutoff = CUTOFF * CUTOFF;
    }
  } else {
    d_softcore = true;
  }
}

CoulombDielectric::CoulombDielectric(const RDKit::ROMol &mol, int confId,
                                     double probeCharge, bool absVal,
                                     const std::string &prop, double alpha,
                                     double cutoff, double epsilon, double xi)
    : d_nAtoms(mol.getNumAtoms()),
      d_absVal(absVal),
      d_cutoff(cutoff * cutoff),
      d_probe(probeCharge),
      d_epsilon(epsilon),
      d_xi(xi),
      d_alpha(alpha) {
  PRECONDITION(mol.getNumConformers() > 0, "No Conformers for Molecule");

  d_charges.reserve(d_nAtoms);
  d_sp.reserve(d_nAtoms);
  d_dists.resize(d_nAtoms);
  d_pos.reserve(3 * d_nAtoms);

  RDKit::Conformer conf = mol.getConformer(confId);
  for (unsigned int i = 0; i < d_nAtoms; ++i) {
    d_charges.push_back(mol.getAtomWithIdx(i)->getProp<double>(prop));
    const RDGeom::Point3D &pt = conf.getAtomPos(i);
    d_pos.push_back(pt.x);
    d_pos.push_back(pt.y);
    d_pos.push_back(pt.z);
  }
  d_dielectric = (d_xi - d_epsilon) / (d_xi + d_epsilon);

  std::vector<unsigned int> neighbors(d_charges.size(), 0);

  for (unsigned int i = 0; i < d_charges.size() - 1; ++i) {
    for (unsigned int j = i + 1; j < d_charges.size(); ++j) {
      double temp = d_pos[j * 3] - d_pos[i * 3];
      double dist2 = temp * temp;
      temp = d_pos[j * 3 + 1] - d_pos[i * 3 + 1];
      dist2 += temp * temp;
      temp = d_pos[j * 3 + 2] - d_pos[i * 3 + 2];
      dist2 += temp * temp;
      if (dist2 < 16.0) {
        neighbors[i]++;
        neighbors[j]++;
      }
    }
  }
  for (unsigned int neighbor : neighbors) {
    switch (neighbor) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
        d_sp.push_back(0.0);
        break;
      case 7:
        d_sp.push_back(.4);
        break;
      case 8:
        d_sp.push_back(.9);
        break;
      case 9:
        d_sp.push_back(1.4);
        break;
      case 10:
        d_sp.push_back(1.9);
        break;
      case 11:
        d_sp.push_back(2.6);
        break;
      default:
        d_sp.push_back(4.0);
    }
  }
  if (fabs(d_alpha) < MIN_CUTOFF_VAL) {
    d_softcore = false;
    if (d_cutoff < MIN_CUTOFF_VAL * MIN_CUTOFF_VAL) {
      d_cutoff = CUTOFF * CUTOFF;
    }
  } else {
    d_softcore = true;
  }
}

double CoulombDielectric::operator()(double x, double y, double z,
                                     double thres) const {
  int neigh = 0;
  double res = 0.0, sq = 0.0;

  for (unsigned int i = 0, j = 0; i < d_nAtoms; ++i, j += 3) {
    double temp = x - d_pos[j];
    double dist2 = temp * temp;
    temp = y - d_pos[j + 1];
    dist2 += temp * temp;
    temp = z - d_pos[j + 2];
    dist2 += temp * temp;
    d_dists[i] = dist2;
    if (dist2 < 16.0) {
      neigh += 1;
    }
  }

  switch (neigh) {
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
      sq = 0.0;
      break;
    case 7:
      sq = .4;
      break;
    case 8:
      sq = .9;
      break;
    case 9:
      sq = 1.4;
      break;
    case 10:
      sq = 1.9;
      break;
    case 11:
      sq = 2.6;
      break;
    default:
      sq = 4.0;
  }

  if (d_softcore) {
    for (unsigned int i = 0; i < d_nAtoms; i++) {
      if (d_dists[i] < thres) {
        res += d_charges[i] *
               (1 / sqrt(d_alpha + d_dists[i]) +
                d_dielectric / sqrt(d_alpha + d_dists[i] + 4.0 * d_sp[i] * sq));
      }
    }
  } else {
    for (unsigned int i = 0; i < d_nAtoms; i++) {
      if (d_dists[i] < thres) {
        double dist2 = std::max(d_dists[i], d_cutoff);
        res += d_charges[i] * (1 / sqrt(dist2) +
                               d_dielectric / sqrt(dist2 + 4.0 * d_sp[i] * sq));
      }
    }
  }
  res *= CoulombDetail::prefactor * (1 / d_xi) * d_probe;

  if (d_absVal) {
    res = -fabs(
        res);  // takes the negative absolute value of the interaction energy
  }
  return res;
}

namespace HBondDetail {
const double em[2][2] = {{-8.368, -11.715}, {-11.715, -16.736}};
const double rm[2][2] = {{3.2, 3.0}, {3.0, 2.8}};
const double K1 = 562.25380293;
const double K2 = 0.11697778;
const double bondlength[2] = {-0.972, -1.019};

double cos_2(double t, double, double) {
  if (t < M_PI_2) {
    double temp = cos(t);
    temp *= temp;
    return temp;
  } else {
    return 0.0;
  }
};

double cos_2_0(double t, double t_0 = 0.0, double t_i = 1.0) {
  double temp;
  if (t_i < M_55D) {
    temp = cos(t_0);
    temp *= temp;
    return temp;
  } else if (t_i < M_PI_2) {
    temp = cos(t);
    temp *= temp;
    return temp;
  } else {
    return 0.0;
  }
};

double cos_2_rot(double t, double, double) {
  t -= M_70_5D;
  if (t < M_PI_2) {
    double temp = cos(t);
    temp *= temp;
    return temp;
  } else {
    return 0.0;
  }
};

double cos_4(double t, double, double) {
  if (t < M_PI_2) {
    double temp = cos(t);
    temp *= temp;
    temp *= temp;
    return temp;
  } else {
    return 0.0;
  }
};

double cos_4_rot(double t, double, double) {
  t -= M_70_5D;
  if (t < M_PI_2) {
    double temp = cos(t);
    temp *= temp;
    temp *= temp;
    return temp;
  } else {
    return 0.0;
  }
};

double cos_6(double t, double, double) {
  if (t < M_PI_2) {
    double temp = cos(t);
    temp *= temp;
    temp *= temp * temp;
    return temp;
  } else {
    return 0.0;
  }
};

double cos_6_rot(double t, double, double) {
  t -= M_70_5D;
  if (t < M_PI_2) {
    double temp = cos(t);
    temp *= temp;
    temp *= temp * temp;
    return temp;
  } else {
    return 0.0;
  }
};

double cos_acc(double, double t_0, double t_i) {
  double temp;
  if (t_i < M_PI_2) {
    temp = cos(t_0) * (0.9 + 0.1 * sin(2 * t_i));
    return temp;
  } else if (t_i < M_110D) {
    temp = cos(t_i);
    temp *= temp;
    temp = K2 - temp;
    temp *= temp * temp;
    temp *= cos(t_0) * K1;
    return temp;
  } else {
    return 0.0;
  }
};

double no_dep(double, double, double) { return 1.0; };
}  // namespace HBondDetail

HBond::HBond(const RDKit::ROMol &mol, int confId,
             const std::string &probeAtomType, bool fixed, double cutoff)
    : d_cutoff(cutoff * cutoff) {
  if (d_cutoff < (MIN_CUTOFF_VAL * MIN_CUTOFF_VAL)) {
    d_cutoff = CUTOFF * CUTOFF;
  }

  if (probeAtomType == "O") {
    d_DAprop = 'D';
    d_probetype = O;
  } else if (probeAtomType == "OH") {
    d_DAprop = 'A';
    d_probetype = O;
  } else if (probeAtomType == "N") {
    d_DAprop = 'D';
    d_probetype = N;
  } else if (probeAtomType == "NH") {
    d_DAprop = 'A';
    d_probetype = N;
  } else {
    const std::string msg = "Probe atom type not supported: " + probeAtomType;
    BOOST_LOG(rdErrorLog) << msg << std::endl;
    throw ValueErrorException(msg);
  }

  d_nInteract = mol.getNumAtoms();  // number of atoms = highest possible number
                                    // of interactions

  std::vector<unsigned int> specialAtoms;
  findSpecials(mol, confId, fixed, specialAtoms);

  if (d_DAprop == 'A') {
    if (fixed) {
      findAcceptors(mol, confId, specialAtoms);
    } else {
      findAcceptorsUnfixed(mol, confId, specialAtoms);
    }
  } else if (d_DAprop == 'D') {
    if (fixed) {
      findDonors(mol, confId, specialAtoms);
    } else {
      findDonorsUnfixed(mol, confId, specialAtoms);
    }
  } else {  // this should never be the case
    BOOST_LOG(rdErrorLog) << "HBond: unknown target property d_DAprop: "
                          << d_DAprop << std::endl;
  }

  d_nInteract = d_targettypes.size();  // updated to number of interactions
  d_eneContrib.resize(d_nInteract, 0);
  d_vectTargetProbe.resize(d_nInteract * 3, 0);

  POSTCONDITION(
      d_nInteract * 3 == d_pos.size(),
      "Error in constructing H-Bond descriptor: Vector length mismatch (target atom types).");
  POSTCONDITION(
      d_nInteract * 3 == d_direction.size(),
      "Error in constructing H-Bond descriptor: Vector length mismatch (bond directions).");
  POSTCONDITION(
      d_nInteract == d_function.size(),
      "Error in constructing H-Bond descriptor: Vector length mismatch (angular functions).");
  POSTCONDITION(
      d_nInteract * 3 == d_plane.size(),
      "Error in constructing H-Bond descriptor: Vector length mismatch (lone pair planes).");
  POSTCONDITION(
      d_nInteract == d_lengths.size(),
      "Error in constructing H-Bond descriptor: Vector length mismatch (bondlengths).");
}

unsigned int HBond::findSpecials(const RDKit::ROMol &mol, int confId,
                                 bool fixed,
                                 std::vector<unsigned int> &specials) {
  using namespace HBondDetail;

  RDKit::MatchVectType matches;
  RDKit::ROMol::ADJ_ITER nbrIdx, endNbrs;
  RDGeom::Point3D pos, dir, hbonddir, plane, bondDirection[12];
  unsigned int nbrs;
  unsigned int match = 0, nMatches = 0;

  const RDKit::Conformer &conf = mol.getConformer(confId);
  // RDKit::RWMol thr = *RDKit::SmilesToMol("C[C@H]([C@@H](C(=O))N)O");
  // //threonine, serine itself is a substructure of this
  static const auto ser = RDKit::v2::SmilesParse::MolFromSmiles(
      "[CH2]([C@@H](C(=O))N)O");  // serine
  // RDKit::RWMol his = *RDKit::SmilesToMol("Cc1cnc[nH]1"); //imidazole residue,
  // is correctly taken into account in 'normal' treatment

  match = RDKit::SubstructMatch(mol, *ser, matches);
  nMatches += match;

  for (auto &matche : matches) {
    const auto *atom = mol.getAtomWithIdx(matche.second);
    if (atom->getAtomicNum() == 8) {
      boost::tie(nbrIdx, endNbrs) = mol.getAtomNeighbors(atom);
      pos = conf.getAtomPos(matche.second);
      if (d_DAprop == 'A') {
        nbrs = 0;
        while (nbrIdx != endNbrs) {  // loop over atoms
          if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() == 1) {
            hbonddir = pos - conf.getAtomPos(*nbrIdx);
            hbonddir.normalize();
          } else {
            bondDirection[nbrs] = pos - conf.getAtomPos(*nbrIdx);
            bondDirection[nbrs].normalize();
            ++nbrs;
          }
          ++nbrIdx;
        }
        if (nbrs == 2) {
          dir = bondDirection[0] + hbonddir;
          plane =
              bondDirection[0].crossProduct(hbonddir);  // X-O-Y plane vector
          plane = plane.crossProduct(dir);              // lp plane vector
          if (fixed) {
            addVectElements(O, &cos_2_0, pos, dir, plane);
          } else {
            addVectElements(O, &cos_4_rot, pos, bondDirection[0]);
          }
          specials.push_back(matche.second);
        }
      } else if (d_DAprop == 'D') {
        if (fixed) {
          while (nbrIdx != endNbrs) {
            if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() ==
                1) {  // hydrogen neighbor necessary for H bond donation
              dir = conf.getAtomPos(*nbrIdx) - pos;
              addVectElements(O, &cos_6, pos, dir);
            }
            ++nbrIdx;
          }
        } else {
          while (nbrIdx != endNbrs) {
            if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() !=
                1) {  // search for non-hydrogen bond direction
              dir = pos - conf.getAtomPos(*nbrIdx);
              addVectElements(O, &cos_6_rot, pos, dir);
            }
            ++nbrIdx;
          }
        }
        specials.push_back(matche.second);
      } else {  // this should never be the case
        BOOST_LOG(rdErrorLog)
            << "HBond::operator(): unknown target property d_DAprop: "
            << d_DAprop << std::endl;
      }
    }
  }
  return nMatches;
}

/* General structure of findAcceptors, findAcceptorsUnfixed, findDonors,
 * findDonorsUnfixed functions: loop over all atoms:
 *   - check whether atom was already treated in specialAtoms
 *   - switch ( atomicNum ): find atoms which are able to donate/accept
 * hydrogen bonds if able:
 *   - switch ( number of neighbors ): find the right geometry
 *   - check for charge or aromatic neighborhood
 *   - calculate adequate hydrogen bond direction vector,
 * lone pair plane vector
 *   - choose correct angular function
 *   - add atomtype, angular function, position of atom,
 * hydrogen bond direction vector and lone pair plane vector to vectors for
 * calculating the interaction returns number of added interactions
 */
unsigned int HBond::findAcceptors(const RDKit::ROMol &mol, int confId,
                                  const std::vector<unsigned int> &specials) {
  using namespace HBondDetail;

  const RDKit::Conformer &conf =
      mol.getConformer(confId);  // get conformer of molecule
  RDKit::ROMol::ADJ_ITER nbrIdx, endNbrs;
  RDKit::ROMol::ADJ_ITER secnbrIdx, secendNbrs;
  RDGeom::Point3D pos, dir, plane, bondDirection[12];
  unsigned int nbrs;          // no of neigbors
  unsigned int interact = 0;  // no of interactions
  bool aromaticnbr;           // aromatic neighbor atom?

  for (unsigned int i = 0; i < d_nInteract; i++) {  // loop over all atoms
    if (std::find(specials.begin(), specials.end(), i) !=
        specials.end()) {  // check whether atom was already treated specially
      interact++;
      continue;
    }

    const auto *atom = mol.getAtomWithIdx(i);  // get ptr to atom

    switch (atom->getAtomicNum()) {  // find atoms able to donate hydrogen bonds
      case 7:                        // Nitrogen
        boost::tie(nbrIdx, endNbrs) =
            mol.getAtomNeighbors(atom);  // get neighbors
        pos = conf.getAtomPos(i);        // get position of atom

        nbrs = 0;
        while (nbrIdx != endNbrs) {  // loop over all neigbors
          bondDirection[nbrs] =
              pos - conf.getAtomPos(*nbrIdx);  // store bond vectors in an array
          bondDirection[nbrs].normalize();
          ++nbrs;  // count neigbors
          ++nbrIdx;
        }

        switch (nbrs) {  // number of neigbors
          case 1:        // sp, eg. nitriles
            if (atom->getFormalCharge() <=
                0) {  // no positively charged nitrogens
              addVectElements(
                  N, &cos_2, pos,
                  bondDirection[0]);  // no differentiation between in-plane and
                                      // out-of-plane angle, plane not needed
              interact++;
            }
            break;
          case 2:  // eg. imines, heterocycles
            if (atom->getFormalCharge() <=
                0) {  // no positively charged nitrogen
              dir = bondDirection[0] +
                    bondDirection[1];  // get hydrogen bond direction
              plane = bondDirection[0].crossProduct(
                  bondDirection[1]);  // normal vector of lone pair plane =
                                      // plane of three atoms
              addVectElements(N, &cos_2, pos, dir, plane);
              interact++;
            }
            break;
          case 3:  // amines, iminium ions
            if (atom->getFormalCharge() <= 0 &&
                !(RDKit::MolOps::atomHasConjugatedBond(
                    atom))) {  // no positively charged nitrogen, no conjugated
                               // nitrogen (amide bonds!)
              dir = bondDirection[0] + bondDirection[1] +
                    bondDirection[2];  // get hydrogen bond direction
              addVectElements(N, &cos_2, pos,
                              dir);  // no differentiation between in-plane and
                                     // out-of-plane angle, plane not needed
              interact++;
            }
            break;
          case 0:  // unbound nitrogen atoms, no hydrogen bonding
          case 4:  // ammonium ions, no hydrogen bonding
            break;
          default:  // more than four bonds: not possible with nitrogen
            BOOST_LOG(rdErrorLog)
                << "HBond: Nitrogen atom bound to more than 4 neighbor atoms: Atom: "
                << i << std::endl;
        }
        break;
      case 8:  // Oxygen
        boost::tie(nbrIdx, endNbrs) =
            mol.getAtomNeighbors(atom);  // get neighbors
        pos = conf.getAtomPos(i);        // get position of atom

        nbrs = 0;
        aromaticnbr = false;
        while (nbrIdx != endNbrs) {  // loop over neighbors
          bondDirection[nbrs] =
              pos - conf.getAtomPos(*nbrIdx);  // store bond vectors in an array
          bondDirection[nbrs].normalize();     // normalization
          if (mol.getAtomWithIdx(*nbrIdx)
                  ->getIsAromatic()) {  // check whether neighbor is aromatic
                                        // (phenolic oxygens)
            aromaticnbr = true;
          }
          ++nbrs;  // count neighbors
          ++nbrIdx;
        }

        switch (nbrs) {  // no of neighbors
          case 1:        // carbonyl, carboxyl C=O, X=O (X=S,P,...), anions
                         // (alcoholates, carboxylates)
            --nbrIdx;
            boost::tie(secnbrIdx, secendNbrs) = mol.getAtomNeighbors(
                mol.getAtomWithIdx(*nbrIdx));  // get neighbors of neighbor atom
            while (secnbrIdx !=
                   secendNbrs) {  // loop over neighbors of neighbor atom
              if ((*secnbrIdx) !=
                  i) {  // second neighbor should not be the oxygen itself
                // bond direction of neighbor atom to second neighbor atom
                dir = conf.getAtomPos(*secnbrIdx) - conf.getAtomPos(*nbrIdx);
                break;  // we only need one bond vector
              }
              ++secnbrIdx;
            }
            plane = bondDirection[0].crossProduct(dir);  // lp plane vector
            if (atom->getFormalCharge() == 0) {  // carbonyl, carboxyl C=O, X=O
              addVectElements(O, &cos_acc, pos, bondDirection[0], plane);
              interact++;
            } else if (atom->getFormalCharge() ==
                       -1) {  // anion, eg. phenolate, carboxylic acid
              if (RDKit::MolOps::atomHasConjugatedBond(atom)) {
                // charged oxygen in conjungated system, eg phenolates or
                // carboxylates
                addVectElements(O, &cos_acc, pos, bondDirection[0], plane);
              } else {
                // non-conjugated anion, eg sp3-alcoholate
                addVectElements(O, &cos_2, pos, bondDirection[0], plane);
              }
              interact++;
            }
            break;
          case 2:  // alcohols, ethers, carboxyl OH
            dir = bondDirection[0] + bondDirection[1];  // get bond direction
            plane = bondDirection[0].crossProduct(
                bondDirection[1]);            // X-O-Y plane vector
            plane = plane.crossProduct(dir);  // lp plane vector
            if (aromaticnbr) {  // if oxygen bound to aromatic system, eg.
                                // phenol
              addVectElements(O, &cos_2, pos, dir, plane);
            } else {  // all other
              addVectElements(O, &cos_2_0, pos, dir, plane);
            }
            interact++;
            break;
          case 0:  // oxygen atoms, no hydrogen bonding
          case 3:  // only with positively charged atom possible, no hydrogen
                   // bonding
            break;
          default:  // more than 3 neighbors: not possible with oxygen
            BOOST_LOG(rdErrorLog)
                << "HBond: Oxygen atom bound to more than 3 neighbor atoms: Atom: "
                << i << std::endl;
        }
        break;
      // Halogens
      case 9:                                  // F
      case 17:                                 // Cl
      case 35:                                 // Br
      case 53:                                 // I
        pos = conf.getAtomPos(i);              // get position of atom
        dir = RDGeom::Point3D(1.0, 1.0, 1.0);  // no directionality needed
        addVectElements(
            N, &no_dep, pos,
            dir);  // type of halogens ~ nitrogen; no lp plane needed
        interact++;
        break;
      default:
        break;
    }
  }
  return interact;
}

unsigned int HBond::findAcceptorsUnfixed(
    const RDKit::ROMol &mol, int confId,
    const std::vector<unsigned int> &specials) {
  using namespace HBondDetail;

  const RDKit::Conformer &conf =
      mol.getConformer(confId);  // get conformer of molecule
  RDKit::ROMol::ADJ_ITER nbrIdx, endNbrs;
  RDKit::ROMol::ADJ_ITER secnbrIdx, secendNbrs;
  RDGeom::Point3D pos, dir, plane, bondDirection[12];
  unsigned int nbrs,
      nonhnbrs;               // no of neighbors, no of nonhydrogen - neighbors
  unsigned int interact = 0;  // no of interactions
  bool aromaticnbr;           // aromatic neighbor atom?

  for (unsigned int i = 0; i < d_nInteract; i++) {  // loop over all atoms
    if (std::find(specials.begin(), specials.end(), i) !=
        specials.end()) {  // check whether atom was already treated specially
      interact++;
      continue;
    }

    const auto *atom = mol.getAtomWithIdx(i);  // get pointer to atom

    switch (atom->getAtomicNum()) {  // find atoms able to accept hydrogen bonds
                                     // (O, N, halogens)
      case 7:                        // Nitrogen
        boost::tie(nbrIdx, endNbrs) =
            mol.getAtomNeighbors(atom);  // get neighbors
        pos = conf.getAtomPos(i);        // get position of atom

        nbrs = 0;
        nonhnbrs = 0;
        while (nbrIdx != endNbrs) {  // loop over neighbors
          if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() !=
              1) {  // hydrogen bond directions are not included
            bondDirection[nonhnbrs] =
                pos -
                conf.getAtomPos(*nbrIdx);  // store bond direction in an array
            bondDirection[nonhnbrs].normalize();
            ++nonhnbrs;  // count non hydrogen neighbors
          }
          ++nbrs;  // count neighbors
          ++nbrIdx;
        }

        switch (nbrs) {  // number of neigbors
          case 1:        // sp, eg. nitriles,   no difference to fixed bonds
            if (atom->getFormalCharge() <=
                0) {  // no positively charged nitrogens
              addVectElements(
                  N, &cos_2, pos,
                  bondDirection[0]);  // no differentiation between in-plane and
                                      // out-of-plane angle, plane not needed
              interact++;
            }
            break;
          case 2:  // eg. imines, heterocycles
            if (atom->getFormalCharge() <=
                0) {                // no positively charged nitrogen
              if (nonhnbrs == 2) {  // secondary imines, heterocycles
                dir = bondDirection[0] +
                      bondDirection[1];  // get hydrogen bond direction
                plane = bondDirection[0].crossProduct(
                    bondDirection[1]);  // normal vector of lone pair plane =
                                        // plane of three atoms
                addVectElements(N, &cos_2, pos, dir, plane);
              } else if (nonhnbrs == 1) {  // primary imine, hydrogen is allowed
                                           // to swap places
                nbrIdx -= 2;
                nbrs = nonhnbrs;
                while (nbrIdx != endNbrs) {
                  if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() ==
                      1) {  // only bond directions to hydrogens are included
                    bondDirection[nbrs] = pos - conf.getAtomPos(*nbrIdx);
                    bondDirection[nbrs].normalize();
                    ++nbrs;
                  }
                  ++nbrIdx;
                }
                plane = bondDirection[0].crossProduct(
                    bondDirection[1]);  // normal vector of lone pair plane =
                                        // plane of three atoms
                addVectElements(N, &cos_acc, pos, bondDirection[0], plane);
              } else {  //[N-]H2 rotating
                addVectElements(N, &no_dep, pos,
                                RDGeom::Point3D(0.0, 0.0, 0.0));
              }
              interact++;
            }
            break;
          case 3:  // amines, iminium ions
            if (atom->getFormalCharge() <=
                0) {  // no iminium ions, no positively charged nitrogen
              if (nonhnbrs == 0) {  // ammonia
                addVectElements(N, &no_dep, pos,
                                RDGeom::Point3D(0.0, 0.0, 0.0));
              } else if (nonhnbrs == 1) {  // primary amines, rotation
                addVectElements(
                    N, &cos_2_rot, pos,
                    bondDirection[0]);  // no differentiation between in-plane
                                        // and out-of-plane angle, plane not
                                        // needed
              } else {  // secondary amines (not flexible) and tertiary amines,
                        // same as fixed hydrogen bonds
                if (atom->getFormalCharge() <= 0 &&
                    !(RDKit::MolOps::atomHasConjugatedBond(
                        atom))) {  // positively charged nitrogen, no conjugated
                                   // nitrogen (amide bonds!)
                  nbrIdx -= 3;
                  nbrs = nonhnbrs;
                  while (nbrIdx != endNbrs) {
                    if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() ==
                        1) {  // only bond directions to hydrogens are included
                      bondDirection[nbrs] = pos - conf.getAtomPos(*nbrIdx);
                      bondDirection[nbrs].normalize();
                      ++nbrs;
                    }
                    ++nbrIdx;
                  }
                  dir = bondDirection[0] + bondDirection[1] +
                        bondDirection[2];  // hydrogen bond direction
                  addVectElements(
                      N, &cos_2, pos,
                      dir);  // no differentiation between in-plane and
                             // out-of-plane angle, plane not needed
                }
              }
              interact++;
            }
            break;
          case 0:  // unbound nitrogen atoms, no hydrogen bonding
          case 4:  // ammonium ions, no hydrogen bonding
            break;
          default:  // more than four bonds: not possible with nitrogen
            BOOST_LOG(rdErrorLog)
                << "HBond: Nitrogen atom bound to more than 4 neighbor atoms: Atom: "
                << i << std::endl;
        }
        break;
      case 8:  // Oxygen
        boost::tie(nbrIdx, endNbrs) =
            mol.getAtomNeighbors(atom);  // get neighbors
        pos = conf.getAtomPos(i);        // get atom position

        nbrs = 0;
        nonhnbrs = 0;
        aromaticnbr = false;
        while (nbrIdx != endNbrs) {  // loop over neighbors
          if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() !=
              1) {  // bond directions to hydrogen are not included
            bondDirection[nonhnbrs] = pos - conf.getAtomPos(*nbrIdx);
            bondDirection[nonhnbrs].normalize();
            ++nonhnbrs;  // count non hydrogen neighbors
          }
          if (mol.getAtomWithIdx(*nbrIdx)
                  ->getIsAromatic()) {  // check whether aromatic neighbor
            aromaticnbr = true;
          }
          ++nbrs;  // count neighbors
          ++nbrIdx;
        }

        switch (nbrs) {  // no of neighbors
          case 1:        // carbonyl, carboxyl C=O, X=O (X=S,P,...), anions
                         // (alcoholates, carboxylates)
            --nbrIdx;
            boost::tie(secnbrIdx, secendNbrs) = mol.getAtomNeighbors(
                mol.getAtomWithIdx(*nbrIdx));  // get neighbors of neighbor atom
            while (secnbrIdx !=
                   secendNbrs) {  // loop over neighbors of neighbor atom
              if ((*secnbrIdx) !=
                  i) {  // second neighbor should not be the oxygen itself
                // bond direction of neighbor atom to second neighbor atom
                dir = conf.getAtomPos(*secnbrIdx) - conf.getAtomPos(*nbrIdx);
                break;  // we only need one vector
              }
              ++secnbrIdx;
            }
            plane = bondDirection[0].crossProduct(dir);  // lp plane vector
            if (atom->getFormalCharge() == 0) {  // carbonyl, carboxyl C=O, X=O
              addVectElements(O, &cos_acc, pos, bondDirection[0], plane);
              interact++;
            } else if (atom->getFormalCharge() ==
                       -1) {  // anion, eg. phenolate, carboxylic acid
              if (RDKit::MolOps::atomHasConjugatedBond(atom)) {
                // charged oxygen in conjungated system, eg phenolates or
                // carboxylates
                addVectElements(O, &cos_acc, pos, bondDirection[0], plane);
              } else {  // all other
                addVectElements(O, &cos_2, pos, bondDirection[0], plane);
              }
              interact++;
            }
            break;
          case 2:                 // alcohols, ethers, carboxyl OH
            if (nonhnbrs == 0) {  // water
              addVectElements(O, &no_dep, pos, RDGeom::Point3D(0.0, 0.0, 0.0));
            } else if (nonhnbrs == 1) {  // hydroxy groups
              if (aromaticnbr) {         // phenol
                nbrIdx -= 2;
                nbrs = nonhnbrs;
                while (nbrIdx != endNbrs) {  // loop over neighbors
                  if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() ==
                      1) {  // only bond directions to hydrogens are included
                    bondDirection[nbrs] =
                        pos - conf.getAtomPos(
                                  *nbrIdx);  // get O-H bond direction vector
                    bondDirection[nbrs].normalize();
                    ++nbrs;
                  }
                  ++nbrIdx;
                }
                plane = bondDirection[0].crossProduct(
                    bondDirection[1]);  // X-O-Y plane vector
                addVectElements(O, &cos_acc, pos, bondDirection[0], plane);
              } else {
                addVectElements(
                    O, &cos_2_rot, pos,
                    bondDirection[0]);  // no plane information needed
              }
            } else {  // ethers, same as fixed hydrogen bonds
              dir = bondDirection[0] +
                    bondDirection[1];  // get hydrogen bond direction
              plane = bondDirection[0].crossProduct(
                  bondDirection[1]);            // X-O-Y plane vector
              plane = plane.crossProduct(dir);  // lp plane vector
              addVectElements(O, &cos_2_0, pos, dir, plane);
            }
            interact++;
            break;
          case 0:  // oxygen atoms, no hydrogen bonding
          case 3:  // only with positively charged atom possible, no hydrogen
                   // bonding
            break;
          default:  // more than 3 neighbors: not possible with oxygen
            BOOST_LOG(rdErrorLog)
                << "HBond: Oxygen atom bound to more than 3 neighbor atoms: Atom: "
                << i << std::endl;
        }
        break;
      // Halogens
      case 9:                                  // F
      case 17:                                 // Cl
      case 35:                                 // Br
      case 53:                                 // I
        pos = conf.getAtomPos(i);              // get atoms position
        dir = RDGeom::Point3D(1.0, 1.0, 1.0);  // no directionality needed
        addVectElements(
            N, &no_dep, pos,
            dir);  // type of halogens ~ nitrogen; no lp plane needed
        interact++;
        break;
      default:
        break;
    }
  }
  return interact;
}

unsigned int HBond::findDonors(const RDKit::ROMol &mol, int confId,
                               const std::vector<unsigned int> &specials) {
  using namespace HBondDetail;

  const RDKit::Conformer &conf =
      mol.getConformer(confId);  // get conformer of molecule
  RDKit::ROMol::ADJ_ITER nbrIdx, endNbrs;
  RDGeom::Point3D pos, dir;
  unsigned int interact = 0;

  for (unsigned int i = 0; i < d_nInteract; i++) {  // loop over all atoms
    if (std::find(specials.begin(), specials.end(), i) !=
        specials.end()) {  // check whether atom was already treated specially
      interact++;
      continue;
    }

    const auto *atom = mol.getAtomWithIdx(i);  // get ptr to atom

    switch (
        atom->getAtomicNum()) {  // find atoms able to donate hydrogen bonds (O,
                                 // N, of course only with attached hydrogen)
      case 7:                    // Nitrogen
        boost::tie(nbrIdx, endNbrs) =
            mol.getAtomNeighbors(atom);  // get neigbors
        pos = conf.getAtomPos(i);        // get position

        while (nbrIdx != endNbrs) {  // loop over neighbors
          if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() ==
              1) {  // hydrogen neighbor necessary for H bond donation
            dir = conf.getAtomPos(*nbrIdx) -
                  pos;  // bond direction vector, IMPORTANT: no normalization,
                        // because operator() needs length of vector in case of
                        // donors
            addVectElements(N, &cos_2, pos, dir);
            interact++;
          }
          ++nbrIdx;
        }
        break;
      case 8:  // Oxygen
        boost::tie(nbrIdx, endNbrs) =
            mol.getAtomNeighbors(atom);  // get neigbors
        pos = conf.getAtomPos(i);        // get position

        while (nbrIdx != endNbrs) {  // loop over neighbors
          if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() ==
              1) {  // hydrogen neighbor necessary for H bond donation
            dir = conf.getAtomPos(*nbrIdx) -
                  pos;  // bond direction vector, IMPORTANT: no normalization,
                        // because operator() needs length of vector in case of
                        // donors
            addVectElements(O, &cos_4, pos, dir);
            interact++;
          }
          ++nbrIdx;
        }
        break;
      default:
        break;
    }
  }
  return interact;
}

unsigned int HBond::findDonorsUnfixed(
    const RDKit::ROMol &mol, int confId,
    const std::vector<unsigned int> &specials) {
  using namespace HBondDetail;

  const auto &conf = mol.getConformer(confId);  // get conformer of molecule
  RDKit::ROMol::ADJ_ITER nbrIdx, endNbrs;
  RDGeom::Point3D pos, hbonddir, dir, plane;
  unsigned int nbrs, nonhnbrs;  // no of neighbors, no of non hydrogen neighbors
  unsigned int interact = 0;
  bool aromaticnbr;

  for (unsigned int i = 0; i < d_nInteract; i++) {  // loop over all atoms
    if (std::find(specials.begin(), specials.end(), i) !=
        specials.end()) {  // check whether atom was already treated specially
      interact++;
      continue;  // skip loop for this atom
    }

    const auto *atom = mol.getAtomWithIdx(i);  // get ptr to atom

    switch (
        atom->getAtomicNum()) {  // find atoms able to donate hydrogen bonds (O,
                                 // N, of course only with attached hydrogen)
      case 7:                    // Nitrogen
        boost::tie(nbrIdx, endNbrs) =
            mol.getAtomNeighbors(atom);  // get neighbors
        pos = conf.getAtomPos(i);        // get position

        nbrs = 0;
        nonhnbrs = 0;
        while (nbrIdx != endNbrs) {  // loop over neighbors
          if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() != 1) {
            ++nonhnbrs;  // count non-hydrogen neighbors
          }
          ++nbrs;  // count neighbors
          ++nbrIdx;
        }
        nbrIdx -= nbrs;

        if (nonhnbrs != nbrs) {  // otherwise no hydrogens, no donation possible
          switch (nbrs) {        // number of neigbors
            case 2:              // eg. imines, heterocycles
              if (nonhnbrs == 0) {  //[N-]H2
                addVectElements(N, &no_dep, pos,
                                RDGeom::Point3D(0.0, 0.0, 0.0));
                interact++;
              } else {  // primary imine, swapping of hydrogen is allowed
                while (nbrIdx != endNbrs) {  // loop over neighbors
                  if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() != 1) {
                    dir = pos - conf.getAtomPos(*nbrIdx);  // the other bond
                    dir.normalize();

                  } else {
                    hbonddir = conf.getAtomPos(*nbrIdx) - pos;  // hydrogen bond
                  }
                  ++nbrIdx;
                }

                addVectElements(N, &cos_2, pos, hbonddir);  // first hbond
                interact++;

                // let's swap hydrogen and lp:
                plane = dir.crossProduct(hbonddir);  // lp plane vector
                plane =
                    plane.crossProduct(dir);  // plane through other bond
                                              // perpendicular to X-N-H plane
                dir = plane *
                      hbonddir.dotProduct(plane);  // projection of vector
                                                   // hbonddir on plane vector
                hbonddir -= dir * 2;  // mirroring of dir vector on plane
                addVectElements(
                    N, &cos_2, pos,
                    hbonddir);  // second hbond, hydrogen at other place
                interact++;
              }
              break;
            case 3:  // amines, iminium ions
              if (nonhnbrs ==
                  2) {  // sec amines, no rotation, same as fixed bonds
                while (nbrIdx != endNbrs) {  // loop over neighbors
                  if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() ==
                      1) {  // hydrogen neighbor necessary for H bond donation
                    hbonddir =
                        conf.getAtomPos(*nbrIdx) - pos;  // hbond direction
                  }
                  ++nbrIdx;
                }
                addVectElements(N, &cos_2, pos, hbonddir);
                interact++;
              } else if (nonhnbrs == 1) {    // primary amines, rotation
                while (nbrIdx != endNbrs) {  // loop over neighbors
                  if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() !=
                      1) {  // search for X-N bond
                    dir = pos - conf.getAtomPos(*nbrIdx);  // X-N bond direction
                    dir.normalize();
                  }
                  ++nbrIdx;
                }
                addVectElements(
                    N, &cos_2_rot, pos,
                    dir * (-bondlength[N]));  // vector dir has typcial N-H
                                              // bondlength, for approximate /
                                              // average calculation of angle p
                                              // (see operator())
                interact++;
              } else {  // ammonia
                addVectElements(N, &no_dep, pos,
                                RDGeom::Point3D(0.0, 0.0, 0.0));
                interact++;
              }
              break;
            case 4:
              if (nonhnbrs == 0) {  // ammonium ion
                addVectElements(N, &no_dep, pos,
                                RDGeom::Point3D(0.0, 0.0, 0.0));
                interact++;
              } else if (nonhnbrs == 1) {    // primary ammonium, rotation
                while (nbrIdx != endNbrs) {  // loop over neighbors
                  if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() !=
                      1) {  // search for X-N bond
                    dir = pos - conf.getAtomPos(*nbrIdx);  // X-N bond direction
                  }
                  ++nbrIdx;
                }
                addVectElements(
                    N, &cos_2_rot, pos,
                    dir * (-bondlength[N]));  // vector dir has typcial N-H
                                              // bondlength, for approximate /
                                              // average calculation of angle p
                                              // (see operator())
                interact++;
              } else {  // secondary or tertiary ammonium, no rotation, same as
                        // fixed bonds
                while (nbrIdx != endNbrs) {  // loop over neighbors
                  if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() ==
                      1) {  // hydrogen neighbor necessary for H bond donation
                    dir = pos -
                          conf.getAtomPos(*nbrIdx);  // hydrogen bond direction
                    addVectElements(N, &cos_2_rot, pos, dir);
                    interact++;
                  }
                  ++nbrIdx;
                }
              }
              break;
            default:  // more than four bonds: not possible with nitrogen
              BOOST_LOG(rdErrorLog)
                  << "HBond: Nitrogen atom bound to more than 4 neighbor atoms: Atom: "
                  << i << std::endl;
          }
        }
        break;
      case 8:  // Oxygen
        boost::tie(nbrIdx, endNbrs) =
            mol.getAtomNeighbors(atom);  // get neighbors
        pos = conf.getAtomPos(i);        // get position

        nbrs = 0;
        nonhnbrs = 0;
        aromaticnbr = false;
        while (nbrIdx != endNbrs) {  // loop over neighbors
          if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() != 1) {
            ++nonhnbrs;  // count non-hydrogen neighbors
          }
          if (mol.getAtomWithIdx(*nbrIdx)
                  ->getIsAromatic()) {  // check whether oxygen is bound to
                                        // aromatic system
            aromaticnbr = true;
          }
          ++nbrs;  // count neighbors
          ++nbrIdx;
        }
        nbrIdx -= nbrs;

        if (nonhnbrs != nbrs) {  // otherwise no hydrogen, no hydrogen bond
                                 // donation possible
          switch (nbrs) {        // no of neighbors
            case 1:              // hydroxyl
              addVectElements(O, &no_dep, pos, RDGeom::Point3D(0.0, 0.0, 0.0));
              interact++;
              break;
            case 2:
              if (nonhnbrs == 0) {  // water
                addVectElements(O, &no_dep, pos,
                                RDGeom::Point3D(0.0, 0.0, 0.0));
                interact++;
              } else {                       // OH groups
                while (nbrIdx != endNbrs) {  // loop over neighbors
                  if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() !=
                      1) {  // search for X-O bond
                    dir = pos - conf.getAtomPos(*nbrIdx);  // O-X bond direction
                    dir.normalize();
                  } else {
                    hbonddir =
                        conf.getAtomPos(*nbrIdx) - pos;  // O-H bond direction
                  }
                  ++nbrIdx;
                }
                if (aromaticnbr) {  // phenolic oxygen, allows h to swap places
                                    // in aromatic plane
                  addVectElements(O, &cos_4, pos, hbonddir);  // first hbond
                  interact++;

                  // let's swap hydrogen and lp:
                  plane = dir.crossProduct(hbonddir);  // lp plane vector
                  plane =
                      plane.crossProduct(dir);  // plane through other bond
                                                // perpendicular to X-N-H plane
                  dir = plane *
                        hbonddir.dotProduct(
                            plane);  // projection of vector dir on plane vector
                  hbonddir -= dir * 2;  // mirroring of dir vector on plane
                  addVectElements(
                      O, &cos_4, pos,
                      hbonddir);  // second hbond, hydrogen at other place
                  interact++;
                } else {  // all other oxygens, flexible
                  addVectElements(
                      O, &cos_4_rot, pos,
                      dir * (-bondlength[O]));  // vector dir has typcial O-H
                                                // bondlength, for approximate /
                                                // average calculation of angle
                                                // p (see operator())
                  interact++;
                }
              }
              break;
            case 3:                 // positively charged oxygen
              if (nonhnbrs == 0) {  // oxonium
                addVectElements(O, &no_dep, pos,
                                RDGeom::Point3D(0.0, 0.0, 0.0));
                interact++;
              } else if (nonhnbrs == 1) {    // R[O+]H2
                while (nbrIdx != endNbrs) {  // loop over neighbors
                  if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() !=
                      1) {  // search for X-O bond
                    dir = pos - conf.getAtomPos(*nbrIdx);  // X-O bond direction
                    dir.normalize();
                    addVectElements(
                        O, &cos_4_rot, pos,
                        dir * (-bondlength[O]));  // vector dir has typcial O-H
                                                  // bondlength, for approximate
                                                  // / average calculation of
                                                  // angle p (see operator())
                    interact++;
                  }
                  ++nbrIdx;
                }
              } else {                       // R1R2[O+]H, non-flexible
                while (nbrIdx != endNbrs) {  // loop over neighbors
                  if (mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() ==
                      1) {  // search for O-H bond
                    dir = conf.getAtomPos(*nbrIdx) - pos;  // O-H bond direction
                    addVectElements(O, &cos_4, pos, dir);
                    interact++;
                  }
                  ++nbrIdx;
                }
              }
              break;
            case 0:  // oxygen atom gas, no hydrogen bonding
              break;
            default:
              BOOST_LOG(rdErrorLog)
                  << "HBond: Oxygen atom bound to more than 3 neighbor atoms: Atom: "
                  << i << std::endl;
          }
        }
        break;
      default:
        break;
    }
  }
  return interact;
}

double HBond::operator()(double x, double y, double z, double thres) const {
  using namespace HBondDetail;

  if (d_nInteract < 1) {  // no interactions
    return 0.0;           // return 0.0
  }

  double res = 0.0;

  if (d_DAprop == 'A') {
    unsigned int minId = 0;
    double minEne = std::numeric_limits<double>::max();  // minimal energy
    double probeDirection[3];                            // direction of probe

    for (unsigned int i = 0, j = 0; i < d_nInteract;
         i++, j += 3) {  // calculation of energy contributions and searching
                         // for the favored probe direction ( direction of
                         // lowest energy contribution )
      d_vectTargetProbe[j] = x - d_pos[j];  // vector of interaction
      d_vectTargetProbe[j + 1] = y - d_pos[j + 1];
      d_vectTargetProbe[j + 2] = z - d_pos[j + 2];

      double dist2 =
          d_vectTargetProbe[j] * d_vectTargetProbe[j] +
          d_vectTargetProbe[j + 1] * d_vectTargetProbe[j + 1] +
          d_vectTargetProbe[j + 2] *
              d_vectTargetProbe[j +
                                2];  // calc of squared length of interaction
                                     //        std::cout << dist2 << std::endl;
      if (dist2 < thres) {
        double dis = sqrt(dist2);
        double distN[3] = {d_vectTargetProbe[j] / dis,
                           d_vectTargetProbe[j + 1] / dis,
                           d_vectTargetProbe[j + 2] / dis};

        dist2 = std::max(dist2, d_cutoff);

        double t = angle(
            distN[0], distN[1], distN[2], d_direction[j], d_direction[j + 1],
            d_direction[j + 2]);  // calc of angle between direction of hbond
                                  // and target-probe direction

        double eneTerm1 = rm[d_probetype][d_targettypes[i]];
        eneTerm1 *= eneTerm1;                   // squared rm
        eneTerm1 /= dist2;                      // division by squared distance
        double eneTerm2 = eneTerm1 * eneTerm1;  // fourth power of rm/distance
        eneTerm1 = eneTerm2 * eneTerm1;         // sixth power of rm/distance
        eneTerm2 *= eneTerm2;                   // eigth power of rm/distance
        eneTerm2 *= (4.0 * eneTerm1 - 3.0 * eneTerm2);
        eneTerm2 *=
            em[d_probetype][d_targettypes[i]];  // multiplication with em
        d_eneContrib[i] = eneTerm2;

        double t0, ti;
        if (d_function[i] == &cos_acc ||
            d_function[i] == &cos_2_0) {  // only if dependent of ti and t0
          double dotProd = d_vectTargetProbe[j] * d_plane[j] +
                           d_vectTargetProbe[j + 1] * d_plane[j + 1] +
                           d_vectTargetProbe[j + 2] * d_plane[j + 2];
          double vectTargetProbeInPlane[3] = {
              d_vectTargetProbe[j] -
                  d_plane[j] *
                      dotProd,  // projection of targetProbe vector on lp plane
              d_vectTargetProbe[j + 1] -
                  d_plane[j + 1] *
                      dotProd,  // projection of targetProbe vector on lp plane
              d_vectTargetProbe[j + 2] -
                  d_plane[j + 2] *
                      dotProd};  // projection of targetProbe vector on lp plane

          normalize(vectTargetProbeInPlane[0], vectTargetProbeInPlane[1],
                    vectTargetProbeInPlane[2]);

          // angles t_0 (out-of-lonepair-plane angle), t_i (in-lonepair-plane
          // angle),
          t0 = angle(distN[0], distN[1], distN[2], vectTargetProbeInPlane[0],
                     vectTargetProbeInPlane[1],
                     vectTargetProbeInPlane[2]);  // out of plane angle
          ti = angle(d_direction[j], d_direction[j + 1], d_direction[j + 2],
                     vectTargetProbeInPlane[0], vectTargetProbeInPlane[1],
                     vectTargetProbeInPlane[2]);  // in plane angle
        } else {
          t0 = 0.0;
          ti = 1.0;
        }
        d_eneContrib[i] *=
            (*(d_function[i]))(t, t0, ti);  // scaling of energy contribution

        if (d_eneContrib[i] <
            minEne) {  // check whether most favored interaction
          minEne = d_eneContrib[i];
          minId = i;
        }
      } else {
        d_eneContrib[i] = 0.0;
      }
    }
    minId *= 3;
    probeDirection[0] = -d_vectTargetProbe[minId];  // probe is directed to most
                                                    // favored interaction
    probeDirection[1] = -d_vectTargetProbe[++minId];
    probeDirection[2] = -d_vectTargetProbe[++minId];
    normalize(probeDirection[0], probeDirection[1], probeDirection[2]);

    for (unsigned int
             i = 0,
             j = 0;
         i < d_nInteract;
         i++,
             j +=
             3) {  // scaling to take probe direction into account and adding up
      double vectHydrogenTarget[3] = {
          probeDirection[0] * bondlength[d_probetype] - d_vectTargetProbe[j],
          probeDirection[1] * bondlength[d_probetype] -
              d_vectTargetProbe[j + 1],
          probeDirection[2] * bondlength[d_probetype] -
              d_vectTargetProbe[j + 2]};

      normalize(vectHydrogenTarget[0], vectHydrogenTarget[1],
                vectHydrogenTarget[2]);

      // p (angle between best hydrogen bond direction of probe and
      // hydrogen-acceptor vector)
      double p = angle(probeDirection[0], probeDirection[1], probeDirection[2],
                       vectHydrogenTarget[0], vectHydrogenTarget[1],
                       vectHydrogenTarget[2]);

      res +=
          d_eneContrib[i] *
          cos_2(p, 0.0, 1.0);  // scaling of energy contribution and adding up
    }
  } else {  // d_DAprop='D'
    unsigned int minId = 0;
    double minEne = std::numeric_limits<double>::max();  // minimal energy
    double probeDirection[3];                            // direction of prope

    for (unsigned int i = 0, j = 0; i < d_nInteract;
         i++, j += 3) {  // calculation of energy contributions and searching
                         // for the favored probe direction ( direction of
                         // lowest energy contribution )
      d_vectTargetProbe[j] = x - d_pos[j];  // vector of interaction
      d_vectTargetProbe[j + 1] = y - d_pos[j + 1];
      d_vectTargetProbe[j + 2] = z - d_pos[j + 2];

      double dist2 =
          d_vectTargetProbe[j] * d_vectTargetProbe[j] +
          d_vectTargetProbe[j + 1] * d_vectTargetProbe[j + 1] +
          d_vectTargetProbe[j + 2] *
              d_vectTargetProbe[j +
                                2];  // calc of squared length of interaction
                                     //    std::cout << dist2 << std::endl;
      if (dist2 < thres) {
        double dis = sqrt(dist2);
        double distN[3] = {d_vectTargetProbe[j] / dis,
                           d_vectTargetProbe[j + 1] / dis,
                           d_vectTargetProbe[j + 2] / dis};

        dist2 = std::max(dist2, d_cutoff);

        double t = angle(
            distN[0], distN[1], distN[2], d_direction[j], d_direction[j + 1],
            d_direction[j + 2]);  // calc of angle between direction of hbond
                                  // and target-probe direction

        double eneTerm1 = rm[d_probetype][d_targettypes[i]];
        eneTerm1 *= eneTerm1;                   // squared rm
        eneTerm1 /= dist2;                      // division by squared distance
        double eneTerm2 = eneTerm1 * eneTerm1;  // fourth power of rm/distance
        eneTerm1 = eneTerm2 * eneTerm1;         // sixth power of rm/distance
        eneTerm2 *= eneTerm2;                   // eigth power of rm/distance
        eneTerm2 *= (4.0 * eneTerm1 - 3.0 * eneTerm2);
        eneTerm2 *=
            em[d_probetype][d_targettypes[i]];  // multiplication with em
        d_eneContrib[i] = eneTerm2;

        d_eneContrib[i] *=
            (*(d_function[i]))(t, 0.0, 1.0);  // scaling of energy contribution

        if (d_eneContrib[i] <
            minEne) {  // check whether most favored interaction
          minEne = d_eneContrib[i];
          minId = i;
        }
      } else {
        d_eneContrib[i] = 0;
      }
    }
    minId *= 3;
    probeDirection[0] = -d_vectTargetProbe[minId];  // probe is directed to most
                                                    // favored interaction
    probeDirection[1] = -d_vectTargetProbe[++minId];
    probeDirection[2] = -d_vectTargetProbe[++minId];
    normalize(probeDirection[0], probeDirection[1], probeDirection[2]);

    for (unsigned int
             i = 0,
             j = 0;
         i < d_nInteract;
         i++,
             j +=
             3) {  // scaling to take probe direction into account and adding up
      double vectProbeHydrogen[3] = {
          d_direction[j] * d_lengths[i] - d_vectTargetProbe[j],
          d_direction[j + 1] * d_lengths[i] - d_vectTargetProbe[j + 1],
          d_direction[j + 2] * d_lengths[i] - d_vectTargetProbe[j + 2]};

      normalize(vectProbeHydrogen[0], vectProbeHydrogen[1],
                vectProbeHydrogen[2]);

      // p (angle between best hydrogen bond direction of probe and
      // hydrogen-acceptor vector)
      double p = angle(vectProbeHydrogen[0], vectProbeHydrogen[1],
                       vectProbeHydrogen[2], probeDirection[0],
                       probeDirection[1], probeDirection[2]);

      res +=
          d_eneContrib[i] *
          cos_2(p, 0.0, 1.0);  // scaling of energy contribution and adding up
    }
  }
  return res;
}

void HBond::addVectElements(atomtype type,
                            double (*funct)(double, double, double),
                            const RDGeom::Point3D &pos,
                            const RDGeom::Point3D &dir,
                            const RDGeom::Point3D &plane) {
  d_targettypes.push_back(type);
  d_function.push_back(funct);
  d_pos.push_back(pos.x);
  d_pos.push_back(pos.y);
  d_pos.push_back(pos.z);
  double len = dir.length();
  d_lengths.push_back(len);
  d_direction.push_back(dir.x / len);
  d_direction.push_back(dir.y / len);
  d_direction.push_back(dir.z / len);
  len = plane.length();
  if (len > 1.e-16) {
    d_plane.push_back(plane.x / len);
    d_plane.push_back(plane.y / len);
    d_plane.push_back(plane.z / len);
  } else {
    d_plane.push_back(0.0);
    d_plane.push_back(0.0);
    d_plane.push_back(0.0);
  }
}

void HBond::normalize(double &x, double &y, double &z) const {
  double temp = x * x + y * y + z * z;
  temp = sqrt(temp);
  x /= temp;
  y /= temp;
  z /= temp;
}

double HBond::angle(double x1, double y1, double z1, double x2, double y2,
                    double z2) const {
  double dotProd = x1 * x2 + y1 * y2 + z1 * z2;
  if (dotProd < -1.0) {
    dotProd = -1.0;
  } else if (dotProd > 1.0) {
    dotProd = 1.0;
  }
  return acos(dotProd);
}

Hydrophilic::Hydrophilic(const RDKit::ROMol &mol, int confId, bool fixed,
                         double cutoff) {
  d_hbondOH = HBond(mol, confId, "OH", fixed, cutoff);
  d_hbondO = HBond(mol, confId, "O", fixed, cutoff);
}

double Hydrophilic::operator()(double x, double y, double z,
                               double thres) const {
  double hbondO, hbondOH;
  hbondO = d_hbondO(x, y, z, thres);
  hbondOH = d_hbondOH(x, y, z, thres);
  return std::min(hbondO, hbondOH);
}

void writeToCubeStream(const RDGeom::UniformRealValueGrid3D &grd,
                       std::ostream &outStrm, const RDKit::ROMol *mol,
                       int confid) {
  PRECONDITION(outStrm, "bad stream");
  const double bohr = 0.529177249;
  int dimX = grd.getNumX();  //+2;
  int dimY = grd.getNumY();  //+2;
  int dimZ = grd.getNumZ();  //+2;
  auto spacing = grd.getSpacing() / bohr;
  auto offSet = grd.getOffset() / bohr;
  auto nAtoms = mol ? mol->getNumAtoms() : 0u;
  outStrm.setf(std::ios::left);
  outStrm
      << "Gaussian cube format generated by RDKit\n*************************\n";
  outStrm << std::setw(20) << std::setprecision(6) << nAtoms << std::setw(20)
          << std::setprecision(6) << offSet.x << std::setw(20)
          << std::setprecision(6) << offSet.y << std::setw(20)
          << std::setprecision(6) << offSet.z << std::endl;
  outStrm << std::setw(20) << std::setprecision(6) << dimX << std::setw(20)
          << std::setprecision(6) << spacing << std::setw(20)
          << std::setprecision(6) << 0 << std::setw(20) << std::setprecision(6)
          << 0 << std::endl
          << std::setw(20) << std::setprecision(6) << dimY << std::setw(20)
          << std::setprecision(6) << 0 << std::setw(20) << std::setprecision(6)
          << spacing << std::setw(20) << std::setprecision(6) << 0 << std::endl
          << std::setw(20) << std::setprecision(6) << dimZ << std::setw(20)
          << std::setprecision(6) << std::setw(20) << std::setprecision(6) << 0
          << std::setw(20) << std::setprecision(6) << 0 << std::setw(20)
          << std::setprecision(6) << spacing << std::endl;

  if (mol) {
    // this will throw a ConformerException if confId does not exist
    const auto &conf = mol->getConformer(confid);

    for (const auto &atom : mol->atoms()) {
      const auto &pt = conf.getAtomPos(atom->getIdx()) / bohr;
      outStrm << std::setw(20) << std::setprecision(6) << std::left
              << atom->getAtomicNum() << std::setw(20) << std::setprecision(6)
              << atom->getAtomicNum() << std::setw(20) << std::setprecision(6)
              << pt.x << std::setw(20) << std::setprecision(6) << std::setw(20)
              << std::setprecision(6) << pt.y << std::setw(20)
              << std::setprecision(6) << pt.z << std::endl;
    }
  }

  for (auto xi = 0u; xi < grd.getNumX(); ++xi) {
    for (auto yi = 0u; yi < grd.getNumY(); ++yi) {
      for (auto zi = 0u; zi < grd.getNumZ(); ++zi) {
        outStrm << std::setw(20) << std::setprecision(6) << std::left
                << static_cast<double>(
                       grd.getVal(grd.getGridIndex(xi, yi, zi)));
        // grd->d_numX-xi-1, grd->d_numY-yi-1, grd->d_numZ-zi-1
        if ((zi + 1) % 8 == 0) {
          outStrm << std::endl;
        }
      }
      outStrm << std::endl;
    }
    outStrm << std::endl;
  }
}

void writeToCubeFile(const RDGeom::UniformRealValueGrid3D &grd,
                     const std::string &filename, const RDKit::ROMol *mol,
                     int confid) {
  std::ofstream ofStrm(filename.c_str());
  writeToCubeStream(grd, ofStrm, mol, confid);
}

std::unique_ptr<RDKit::RWMol> readFromCubeStream(
    RDGeom::UniformRealValueGrid3D &grd, std::istream &inStrm) {
  PRECONDITION(inStrm, "bad stream");
  constexpr double bohr = 0.529177249;
  constexpr double spacingThreshold = 0.0001;
  if (inStrm.eof()) {
    return nullptr;
  }
  std::string string;
  int nAtoms;
  std::getline(inStrm, string);
  std::getline(inStrm, string);
  inStrm >> nAtoms;
  double x, y, z;
  inStrm >> x >> y >> z;
  const RDGeom::Point3D offSet(x * bohr, y * bohr, z * bohr);

  int dimX, dimY, dimZ;
  double spacingX, spacingY, spacingZ, temp1, temp2;
  inStrm >> dimX >> spacingX >> temp1 >> temp2;
  inStrm >> dimY >> temp1 >> spacingY >> temp2;
  inStrm >> dimZ >> temp1 >> temp2 >> spacingZ;

  if ((fabs(spacingX - spacingY) > spacingThreshold) ||
      (fabs(spacingX - spacingZ) > spacingThreshold)) {
    std::ostringstream errout;
    errout << "Same spacing in all directions needed";
    throw RDKit::FileParseException(errout.str());
  } else {
    spacingX *= bohr;
    grd = RDGeom::UniformRealValueGrid3D(spacingX * static_cast<double>(dimX),
                                         spacingX * static_cast<double>(dimY),
                                         spacingX * static_cast<double>(dimZ),
                                         spacingX, &offSet);
  }
  std::unique_ptr<RDKit::RWMol> molecule;
  if (nAtoms) {
    molecule.reset(new RDKit::RWMol());
    std::unique_ptr<RDKit::Conformer> conf(new RDKit::Conformer(nAtoms));
    int atomNum;
    for (auto i = 0; i < nAtoms; ++i) {
      inStrm >> atomNum >> temp1 >> x >> y >> z;
      RDKit::Atom atom(atomNum);
      molecule->addAtom(&atom, true, false);
      RDGeom::Point3D pos(x * bohr, y * bohr, z * bohr);
      conf->setAtomPos(i, pos);
    }
    molecule->addConformer(conf.release(), false);
  }
  for (auto xi = 0; xi < dimX; ++xi) {
    for (auto yi = 0; yi < dimY; ++yi) {
      for (auto zi = 0; zi < dimZ; ++zi) {
        double tempVal;
        inStrm >> tempVal;
        grd.setVal(grd.getGridIndex(xi, yi, zi), tempVal);
      }
    }
  }
  return molecule;
}

std::unique_ptr<RDKit::RWMol> readFromCubeFile(
    RDGeom::UniformRealValueGrid3D &grd, const std::string &filename) {
  std::ifstream ifStrm(filename.c_str());
  if (ifStrm.bad()) {
    std::ostringstream errout;
    errout << "Bad input file " << filename;
    throw RDKit::BadFileException(errout.str());
  };

  return readFromCubeStream(grd, ifStrm);
}
}  // namespace RDMIF