File: DCLV.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 (884 lines) | stat: -rw-r--r-- 25,150 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
/*=================================================================*/
/* Copyright (C)  2024  Greg Landrum and other RDKit contributors  */
/* Contributed by NextMove Software, Cambridge, UK.                */
/*                                                                 */
/*                                                                 */
/* @@ All Rights Reserved @@                                       */
/* The contents are covered by the terms of the                    */
/* BSD license, which is included in the file                      */
/* license.txt.                                                    */
/*=================================================================*/
#define _USE_MATH_DEFINES

#include <iostream>
#include <limits>
#include <string>
#include <list>
#include <cmath>

#include <GraphMol/GraphMol.h>
#include <GraphMol/MolOps.h>
#include <GraphMol/MonomerInfo.h>
#include <Geometry/point.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/FileParsers/FileParsers.h>

#include "DCLV.h"

using RDGeom::Point3D;

namespace RDKit {
namespace Descriptors {

constexpr int VOXORDER = 16;
constexpr int CHECKMAX = 20;
constexpr int ATOMPOOL = 16;
constexpr int maxDepth = 8;
constexpr int maxDensity = 1000;

constexpr unsigned int HetAtmFlag = 0x01;
constexpr unsigned int WaterFlag = 0x10;

struct CheckType {
  const char *name;
  const unsigned int count;
};

static const CheckType residueCheck[CHECKMAX] = {
    {"ALA", 5},  /*  0 */
    {"GLY", 4},  /*  1 */
    {"LEU", 8},  /*  2 */
    {"SER", 6},  /*  3 */
    {"VAL", 7},  /*  4 */
    {"THR", 7},  /*  5 */
    {"LYS", 9},  /*  6 */
    {"ASP", 8},  /*  7 */
    {"ILE", 8},  /*  8 */
    {"ASN", 8},  /*  9 */
    {"GLU", 9},  /* 10 */
    {"PRO", 7},  /* 11 */
    {"ARG", 11}, /* 12 */
    {"PHE", 11}, /* 13 */
    {"GLN", 9},  /* 14 */
    {"TYR", 12}, /* 15 */
    {"HIS", 10}, /* 16 */
    {"CYS", 6},  /* 17 */
    {"MET", 8},  /* 18 */
    {"TRP", 14}  /* 19 */
};

struct DotStruct {
  Point3D v;
  double area;
};

struct ElemStruct {
  std::vector<DotStruct> dots;
  double radius2;
  double radius;
  long count;
};

class AtomRecord {
 public:
  float radius; /* VdW */
  unsigned short atmSerNo;
  unsigned short resSerNo;
  float bFactor;
  Point3D pos;
  std::string atmName;
  std::string resName;
  std::string insert;
  std::string chain;
  int hetAtmFlag;
  bool solventFlag;
  char flag;
  ElemStruct *elem;

  bool isSolvent() {
    switch (resName[0]) {
      case 'D':
        return resName == "DOD" || resName == "D20";

      case 'H':
        return resName == "HOH" || resName == "H20";

      case 'S':
        return resName == "SOL" || resName == "SO4" || resName == "SUL";

      case 'W':
        return resName == "WAT";
      case 'T':
        return resName == "TIP";
      case 'P':
        return resName == "P04";
      default:
        return false;
    }
  }

  void initFlag() {
    flag = 0;  // initialise flag
    if (isSolvent()) {
      flag |= HetAtmFlag | WaterFlag;
    } else if (hetAtmFlag) {
      flag |= HetAtmFlag;
    }
  };

  // constructor to populate record
  AtomRecord(const Atom &atm, const Conformer cnf) {
    const AtomMonomerInfo *info = atm.getMonomerInfo();
    unsigned int i;
    solventFlag = false;

    if (info) {
      atmName = info->getName();
      resName = ((AtomPDBResidueInfo *)info)->getResidueName();

      if (isSolvent()) {
        solventFlag = true;
        return;
      }

      atmSerNo = ((AtomPDBResidueInfo *)info)->getSerialNumber();
      resSerNo = ((AtomPDBResidueInfo *)info)->getResidueNumber();
      pos = cnf.getAtomPos(atm.getIdx());
      insert = ((AtomPDBResidueInfo *)info)->getInsertionCode();
      chain = ((AtomPDBResidueInfo *)info)->getChainId();

      hetAtmFlag = 1;
      for (i = 0; i < CHECKMAX; i++) {
        if (residueCheck[i].name == resName) {
          hetAtmFlag = 0;
        }
      }
    } else {  // Molecule not from PDB (Ligand only)
      atmName = " " + atm.getSymbol();
      resName = "UNK";

      if (isSolvent()) {
        solventFlag = true;
        return;
      }

      atmSerNo = 1 + atm.getIdx();
      resSerNo = 0;
      pos = cnf.getAtomPos(atm.getIdx());
      hetAtmFlag = 1;
    }
  }
};

struct AtomList {
  const AtomRecord *ptr[ATOMPOOL];
  AtomList *next;
  unsigned int count;

  AtomList() : next(nullptr) {}
};

static void normalise(double *v) {
  double len = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
  v[0] /= len;
  v[1] /= len;
  v[2] /= len;
}

static double triangleArea(const Point3D &p, const Point3D &q,
                           const Point3D &r) {
  auto a = q - p;
  auto b = r - p;
  auto c = a.crossProduct(b);
  return (0.5 * c.length());
}

static int within(const AtomRecord &src, const AtomRecord *dst, double dist) {
  return (src.pos - dst->pos).lengthSq() < dist * dist;
}

static void checkResidue(const AtomRecord *ptr, unsigned int count) {
  for (unsigned int i = 0; i < CHECKMAX; i++) {
    if (ptr->resName.compare(0, 3, residueCheck[i].name, 0, 3) == 0) {
      if (residueCheck[i].count != count) {
        std::cout << "Warning: Atom Count for residue " + ptr->resName +
                         std::to_string(ptr->resSerNo) + ptr->chain +
                         " does not match expected count"
                  << std::endl;
      }
      return;
    }
  }
}

static bool sameResidue(const AtomRecord *ptr1, const AtomRecord *ptr2) {
  if ((ptr1->flag | ptr2->flag) & HetAtmFlag) return (false);

  return ((ptr1->resSerNo == ptr2->resSerNo) &&
          (ptr1->resName.compare(0, 3, ptr2->resName, 0, 3) == 0) &&
          (ptr1->insert == ptr2->insert) && (ptr1->chain == ptr2->chain));
}

static double calculateCompactness(double d_surfaceArea, double d_totalVolume) {
  return d_surfaceArea / cbrt(36.0 * M_PI * d_totalVolume * d_totalVolume);
};

struct State {
  ElemStruct elemA;  // Alpha Carbon               //
  ElemStruct elemC;  // Peptide Carbon    Carbon   //
  ElemStruct elemN;  // Peptide Nitrogen  Nitrogen //
  ElemStruct elemO;  // Peptide Oxygen    Oxygen   //
  ElemStruct elemS;  //                   Sulphur  //
  ElemStruct elemX;  // Sidechain Atom    Unknown  //

  AtomList *grid[VOXORDER][VOXORDER][VOXORDER];
  AtomList *freeList;

  AtomList *neighbours;
  const AtomRecord *recordCache;

  unsigned long totalDots;
  ElemStruct standardDots;
  double standardArea;

  double voxX;
  double voxY;
  double voxZ;
  double voxU;
  double voxV;
  double voxW;
  double cenX;
  double cenY;
  double cenZ;

  void tesselate(const Point3D &p, const Point3D &q, const Point3D &r,
                 unsigned int d) {
    Point3D u, v, w;

    if (d--) {
      u = p + q;
      v = q + r;
      w = r + p;
      u.normalize();
      v.normalize();
      w.normalize();

      tesselate(u, v, w, d);
      tesselate(p, u, w, d);
      tesselate(u, q, v, d);
      tesselate(w, v, r, d);
    } else {
      double area = triangleArea(p, q, r);
      standardDots.dots[standardDots.count].area = area;
      standardArea += area;
      auto &n = standardDots.dots[standardDots.count++].v;

      n = p + q + r;
      n.normalize();
    }
  }

  void generateElemPoints(ElemStruct *elem, double rad, double probeRadius,
                          int dotDensity) {
    double x, y, z, p, q, xy;
    unsigned int vert;

    elem->radius = rad;
    rad = rad + probeRadius;
    elem->radius2 = rad * rad;

    if (dotDensity) {
      long count = ((4.0 * M_PI) * rad * rad * dotDensity);
      std::vector<DotStruct> dots(count);

      unsigned int equat = sqrt(M_PI * count);
      if (!(vert = equat >> 1)) vert = 1;

      unsigned int i = 0;
      for (unsigned int j = 0; (i < count) && (j < vert); j++) {
        p = (M_PI * j) / (double)vert;
        z = cos(p);
        xy = sin(p);
        unsigned int horz = (equat * xy);
        if (!horz) {
          horz = 1;
        }

        for (unsigned int k = 0; (i < count) && (k < horz); k++) {
          q = (2.0 * M_PI * k) / (double)horz;
          x = xy * sin(q);
          y = xy * cos(q);

          dots[i].v.x = rad * x;
          dots[i].v.y = rad * y;
          dots[i].v.z = rad * z;
          i++;
        }
      }

      count = i;
      double area = ((4.0 * M_PI) * elem->radius2) / count;
      for (DotStruct &dot : dots) {
        dot.area = area;
      }

      elem->count = count;
    } else {
      elem->count = standardDots.count;
      elem->dots = standardDots.dots;
    }
  }

  void insertAtomList(AtomList **list, const AtomRecord *ptr) {
    while (*list && ((*list)->count == ATOMPOOL)) {
      list = &(*list)->next;
    }

    if (!(*list)) {
      if (freeList) {
        *list = freeList;
        freeList = (*list)->next;
        (*list)->next = nullptr;
        (*list)->count = 0;
      } else {
        (*list) = (AtomList *)malloc(sizeof(AtomList));
        (*list)->next = nullptr;
        (*list)->count = 0;
      }
    }
    (*list)->ptr[(*list)->count++] = ptr;
  }

  void freeAtomList(AtomList *ptr) {
    while (ptr) {
      AtomList *next = ptr->next;
      free(ptr);
      ptr = next;
    }
  }

  void freeGrid() {
    for (unsigned int x = 0; x < VOXORDER; x++) {
      for (unsigned int y = 0; y < VOXORDER; y++) {
        for (unsigned int z = 0; z < VOXORDER; z++) {
          freeAtomList(grid[x][y][z]);
          grid[x][y][z] = nullptr;
        }
      }
    }
  }

  ElemStruct *getAtomElem(std::string atmName, bool typeFlag) {
    const char *name = atmName.c_str();

    if (typeFlag) { /* Only Recognise Backbone Atoms! */
      if ((name[1] == 'C') && (name[2] == 'A')) {
        return &elemA;
      } else if (name[2] == ' ')
        switch (name[1]) {
          case 'C':
            return &elemC;
          case 'N':
            return &elemN;
          case 'O':
            return &elemO;
        }
    } else { /* RasMol */
      switch (name[1]) {
        case 'C':
          return &elemC;
        case 'N':
          return &elemN;
        case 'O':
          return &elemO;
        case 'S':
          return &elemS;
      }
    }
    return (&elemX);
  }

  AtomList *findNeighbours(const AtomRecord &atom, double range) {
    double maxRadius = 1.87;
    double maxDist = range + maxRadius;

    int lx = voxX * (atom.pos.x - maxDist - voxU);
    if (lx < 0) {
      lx = 0;
    }
    int ly = voxY * (atom.pos.y - maxDist - voxV);
    if (ly < 0) {
      ly = 0;
    }
    int lz = voxZ * (atom.pos.z - maxDist - voxW);
    if (lz < 0) {
      lz = 0;
    }

    int ux = voxX * (atom.pos.x + maxDist - voxU);
    if (ux >= VOXORDER) {
      ux = VOXORDER - 1;
    }
    int uy = voxY * (atom.pos.y + maxDist - voxV);
    if (uy >= VOXORDER) {
      uy = VOXORDER - 1;
    }
    int uz = voxZ * (atom.pos.z + maxDist - voxW);
    if (uz >= VOXORDER) {
      uz = VOXORDER - 1;
    }

    AtomList *neighbourList = nullptr;
    for (int x = lx; x <= ux; x++) {
      for (int y = ly; y <= uy; y++) {
        for (int z = lz; z <= uz; z++) {
          for (AtomList *list = grid[x][y][z]; list; list = list->next) {
            for (unsigned int i = 0; i < list->count; i++) {
              const AtomRecord *temp = list->ptr[i];
              if (temp != &atom) {
                maxDist = range + temp->radius;
                if (within(atom, temp, maxDist)) {
                  insertAtomList(&neighbourList, temp);
                }
              }
            }
          }
        }
      }
    }

    return neighbourList;
  }

  bool testPoint(double *vect, double solvrad) {
    if (recordCache) {
      double dist = recordCache->radius + solvrad;
      double dx = recordCache->pos.x - vect[0];
      double dy = recordCache->pos.y - vect[1];
      double dz = recordCache->pos.z - vect[2];
      if ((dx * dx + dy * dy + dz * dz) < (dist * dist)) {
        return false;
      }
      recordCache = nullptr;
    }

    for (const AtomList *list = neighbours; list; list = list->next) {
      for (unsigned int i = 0; i < list->count; i++) {
        const AtomRecord *ptr = list->ptr[i];
        double dist = ptr->radius + solvrad;
        double dx = ptr->pos.x - vect[0];
        double dy = ptr->pos.y - vect[1];
        double dz = ptr->pos.z - vect[2];
        if ((dx * dx + dy * dy + dz * dz) < (dist * dist)) {
          recordCache = ptr;
          return false;
        }
      }
    }

    totalDots++;
    return true;
  }

  void determineCentreOfGravity(std::vector<AtomRecord> &memberAtoms) {
    double cx, cy, cz;

    cx = cy = cz = 0.0;
    for (const AtomRecord &atom : memberAtoms) {
      cx += atom.pos.x;
      cy += atom.pos.y;
      cz += atom.pos.z;
    }

    unsigned int atomCount = memberAtoms.size();
    cenX = cx / atomCount;
    cenY = cy / atomCount;
    cenZ = cz / atomCount;
  }

  void generateStandardDots(int depth) {
    // Vertex co-ordinates of a unit icosahedron
    static const Point3D Vertices[12] = {{0.00000000, -0.85065081, -0.52573111},
                                         {-0.52573111, 0.00000000, -0.85065081},
                                         {-0.85065081, -0.52573111, 0.00000000},
                                         {0.00000000, -0.85065081, 0.52573111},
                                         {0.52573111, 0.00000000, -0.85065081},
                                         {-0.85065081, 0.52573111, 0.00000000},
                                         {0.00000000, 0.85065081, -0.52573111},
                                         {-0.52573111, 0.00000000, 0.85065081},
                                         {0.85065081, -0.52573111, 0.00000000},
                                         {0.00000000, 0.85065081, 0.52573111},
                                         {0.52573111, 0.00000000, 0.85065081},
                                         {0.85065081, 0.52573111, 0.00000000}};

    // Face list of a unit icosahedron
    static const int Faces[20][4] = {
        {0, 1, 2},  {0, 1, 4},  {0, 2, 3},  {0, 3, 8},  {0, 4, 8},
        {1, 2, 5},  {1, 4, 6},  {1, 5, 6},  {2, 3, 7},  {2, 5, 7},
        {4, 8, 11}, {4, 6, 11}, {3, 8, 10}, {3, 7, 10}, {8, 10, 11},
        {5, 7, 9},  {5, 6, 9},  {6, 9, 11}, {7, 9, 10}, {9, 10, 11}};

    /* Count = 20*(4^Depth); */
    const unsigned long count = (20) * pow(4, depth);
    std::vector<DotStruct> dots(count);

    standardDots.radius = 1.0;
    standardDots.dots = dots;
    standardDots.count = 0;

    standardArea = 0.0;
    for (unsigned int i = 0; i < 20; i++)
      tesselate(Vertices[Faces[i][0]], Vertices[Faces[i][1]],
                Vertices[Faces[i][2]], depth);
  }

  void generateSurfacePoints(int depth, bool typeFlag, double probeRadius,
                             int dotDensity) {
    if (!dotDensity) {
      generateStandardDots(depth);
    }

    if (typeFlag) {
      generateElemPoints(&elemA, 1.87, probeRadius, dotDensity);
      generateElemPoints(&elemC, 1.76, probeRadius, dotDensity);
      generateElemPoints(&elemN, 1.65, probeRadius, dotDensity);
      generateElemPoints(&elemO, 1.4, probeRadius, dotDensity);
      generateElemPoints(&elemX, 1.8, probeRadius, dotDensity);
    } else {
      generateElemPoints(&elemC, 1.87, probeRadius, dotDensity);
      generateElemPoints(&elemN, 1.5, probeRadius, dotDensity);
      generateElemPoints(&elemO, 1.4, probeRadius, dotDensity);
      generateElemPoints(&elemS, 1.84, probeRadius, dotDensity);
      generateElemPoints(&elemX, 1.44, probeRadius, dotDensity);
    }
  }

  void createVoxelGrid(int mask, std::vector<AtomRecord> &memberAtoms) {
    double minx, miny, minz;
    double maxx, maxy, maxz;

    minx = miny = minz = std::numeric_limits<double>::infinity();
    maxx = maxy = maxz = -std::numeric_limits<double>::infinity();

    freeList = nullptr;
    for (unsigned int x = 0; x < VOXORDER; x++) {
      for (unsigned int y = 0; y < VOXORDER; y++) {
        for (unsigned int z = 0; z < VOXORDER; z++) {
          grid[x][y][z] = nullptr;
        }
      }
    }
    // loop over atoms to find min + max x, y + z
    bool init = false;
    for (const AtomRecord &atom : memberAtoms) {
      if (!(atom.flag & mask)) {
        if (init) {
          if (atom.pos.x > maxx) {
            maxx = atom.pos.x;
          } else if (atom.pos.x < minx) {
            minx = atom.pos.x;
          }

          if (atom.pos.y > maxy) {
            maxy = atom.pos.y;
          } else if (atom.pos.y < miny) {
            miny = atom.pos.y;
          }

          if (atom.pos.z > maxz) {
            maxz = atom.pos.z;
          } else if (atom.pos.z < minz) {
            minz = atom.pos.z;
          }
        } else {
          maxx = minx = atom.pos.x;
          maxy = miny = atom.pos.y;
          maxz = minz = atom.pos.z;
          init = true;
        }
      }
    }

    if (!init) return;

    voxX = VOXORDER / ((maxx - minx) + 0.1);
    voxU = minx;
    voxY = VOXORDER / ((maxy - miny) + 0.1);
    voxV = miny;
    voxZ = VOXORDER / ((maxz - minz) + 0.1);
    voxW = minz;

    for (AtomRecord &atom : memberAtoms) {
      if (atom.flag & mask) {
        continue;
      }

      // get grid positions and add to list
      unsigned int x = voxX * (atom.pos.x - voxU);
      unsigned int y = voxY * (atom.pos.y - voxV);
      unsigned int z = voxZ * (atom.pos.z - voxW);
      insertAtomList(&grid[x][y][z], &atom);
    }
  }

  double surfaceArea(const AtomRecord &atom, const double solvrad,
                     const int dotDensity) {
    neighbours = findNeighbours(atom, atom.elem->radius + solvrad + solvrad);
    recordCache = nullptr;

    double surfacearea = 0.0;
    double vect[3];

    if (dotDensity) {
      for (const DotStruct &dot : atom.elem->dots) {
        vect[0] = atom.pos.x + dot.v.x;
        vect[1] = atom.pos.y + dot.v.y;
        vect[2] = atom.pos.z + dot.v.z;
        if (testPoint(vect, solvrad)) {
          surfacearea += dot.area;
        }
      }
    } else {
      double factor = atom.elem->radius + solvrad;

      for (const DotStruct &dot : atom.elem->dots) {
        vect[0] = atom.pos.x + factor * dot.v.x;
        vect[1] = atom.pos.y + factor * dot.v.y;
        vect[2] = atom.pos.z + factor * dot.v.z;

        if (testPoint(vect, solvrad)) {
          surfacearea += dot.area;
        }
      }
      surfacearea *= ((4.0 * M_PI) * atom.elem->radius2) / standardArea;
    }

    freeAtomList(neighbours);

    return surfacearea;
  }

  double calculateAccessibility(bool isProtein, double probeRadius,
                                int dotDensity,
                                std::vector<AtomRecord> &memberAtoms) {
    AtomRecord *ptr = nullptr;
    AtomRecord *prev = nullptr;
    unsigned int count = 0;
    double area = 0;

    totalDots = 0;
    double totalArea = 0.0;
    unsigned int atomCount = memberAtoms.size();

    bool init = false;

    if (isProtein) {
      for (unsigned int i = 0; i < atomCount; i++) {
        ptr = &memberAtoms[i];

        if (ptr->flag & (WaterFlag)) {
          ptr->bFactor = 0.0;
        } else if (!init) {
          if (!(ptr->flag & HetAtmFlag)) {
            init = true;
            prev = ptr;
            area = surfaceArea(*ptr, probeRadius, dotDensity);

            if (ptr->atmName != " OXT") {
              count = 1;
            } else {
              count = 0;
            }
            ptr->bFactor = (float)area;
          } else {
            ptr->bFactor = (float)0.0;
          }
        } else if (!sameResidue(ptr, prev)) {
          totalArea += area;
          checkResidue(prev, count);
          while (prev != ptr) {
            if (!(prev->flag & (HetAtmFlag))) {
              prev->bFactor = (float)area;
            }
            prev++;
          }

          if (!(ptr->flag & HetAtmFlag)) {
            area = surfaceArea(*ptr, probeRadius, dotDensity);
            if (ptr->atmName != " OXT") {
              count = 1;
            } else {
              count = 0;
            }
            ptr->bFactor = (float)area;
            prev = ptr;

          } else {
            ptr->bFactor = (float)0.0;
            init = false;
          }
        } else if (!(ptr->flag & HetAtmFlag)) {
          ptr->bFactor = (float)surfaceArea(*ptr, probeRadius, dotDensity);

          area += ptr->bFactor;
          if (ptr->atmName.compare(0, 4, " OXT") != 0) {
            count++;
          }
        }
      }

      if (init) {
        totalArea += area;
        checkResidue(prev, count);
        while (prev != ptr) {
          if (!(prev->flag & (HetAtmFlag))) {
            prev->bFactor = (float)area;
          }
          prev++;
        }
      }
    } else {
      for (const AtomRecord &atom : memberAtoms) {
        area = surfaceArea(atom, probeRadius, dotDensity);
        totalArea += area;
      }
    }
    return totalArea;
  };

  double partialVolume(const AtomRecord &atom, const double solvrad) {
    double rad = atom.elem->radius + solvrad;
    neighbours = findNeighbours(atom, rad + solvrad);
    recordCache = nullptr;

    unsigned int count = 0;

    double px, py, pz;
    px = py = pz = 0.0;

    double vect[3];
    for (const DotStruct &dot : atom.elem->dots) {
      vect[0] = atom.pos.x + rad * dot.v.x;
      vect[1] = atom.pos.y + rad * dot.v.y;
      vect[2] = atom.pos.z + rad * dot.v.z;
      if (testPoint(vect, solvrad)) {
        px += dot.v.x;
        py += dot.v.y;
        pz += dot.v.z;
        count++;
      }
    }
    freeAtomList(neighbours);

    /* Calculate Volume with Gauss-Ostrogradskii Theorem */
    double partialvol = (atom.pos.x - cenX) * px + (atom.pos.y - cenY) * py +
                        (atom.pos.z - cenZ) * pz;
    partialvol = rad * rad * (partialvol + rad * count);

    return partialvol;
  }

  double calculateVolume(const double probeRadius,
                         const std::vector<AtomRecord> &memberAtoms) {
    double totalvol = 0.0;
    for (const AtomRecord &atom : memberAtoms) {
      totalvol += partialVolume(atom, probeRadius);
    }
    totalvol *= ((4.0 / 3) * M_PI) / standardDots.count;

    return totalvol;
  };
};

// constructor definition
DoubleCubicLatticeVolume::DoubleCubicLatticeVolume(const ROMol &mol,
                                                   bool isProtein,
                                                   bool includeLigand,
                                                   double probeRadius,
                                                   int depth, int dotDensity) {
  //! Class for calculation of the Shrake and Rupley surface area and volume
  //! using the Double Cubic Lattice Method.
  //!
  //! Frank Eisenhaber, Philip Lijnzaad, Patrick Argos, Chris Sander and
  //! Michael Scharf, "The Double Cubic Lattice Method: Efficient Approaches
  //! to Numerical Integration of Surface Area and Volume and to Dot Surface
  //! Contouring of Molecular Assemblies", Journal of Computational Chemistry,
  //! Vol. 16, No. 3, pp. 273-284, 1995.

  /*!

    \param mol: input molecule or protein
    \param isProtein: flag to calculate burried surface area of a protein ligand
    complex [default=false, free ligand]
    \param includeLigand: flag to trigger
    inclusion of bound ligand in surface area and volume calculations where
    molecule is a protein [default=true]
    \param probeRadius: radius of the
    sphere representing the probe solvent atom
    \param depth: controls the number
    of dots per atom
    \param dotDensity: controls density of dots per atom
    \return class
    object
  */

  if (depth > maxDepth) {
    throw std::range_error("Error: supplied depth exceeds maximum");
  }

  if (dotDensity > maxDensity) {
    throw std::range_error("Error: supplied density exceeds maximum");
  }

  if (depth < 0) {
    depth = 0;
  }

  if (probeRadius < 0.0) {
    probeRadius = (isProtein) ? 1.4 : 1.2;
  }

  // if not protein, includeLigand should always be true
  if (!isProtein) {
    includeLigand = true;
  }

  // default 5120 faces, ligand
  if (isProtein && probeRadius == 1.2 && depth == 4) {
    probeRadius = 1.4;
    depth = 2;  // 320 faces, protein
  }

  std::unique_ptr<ROMol> nmol{MolOps::removeAllHs(mol, false)};

  State s;
  s.generateSurfacePoints(depth, isProtein, probeRadius, dotDensity);

  const Conformer &conf = nmol->getConformer();

  std::vector<AtomRecord> memberAtoms;

  for (const auto atom : nmol->atoms()) {
    AtomRecord curr_atom(*atom, conf);
    curr_atom.initFlag();
    if (!curr_atom.solventFlag) {
      curr_atom.elem = s.getAtomElem(curr_atom.atmName, isProtein);
      curr_atom.radius = curr_atom.elem->radius;
      memberAtoms.push_back(curr_atom);
    }
  }

  int mask = includeLigand ? WaterFlag : HetAtmFlag;
  s.determineCentreOfGravity(memberAtoms);
  s.createVoxelGrid(mask, memberAtoms);
  surfaceArea =
      s.calculateAccessibility(isProtein, probeRadius, dotDensity, memberAtoms);
  totalVolume = s.calculateVolume(probeRadius, memberAtoms);
  vdwVolume = s.calculateVolume(0.0, memberAtoms);
  compactness = calculateCompactness(surfaceArea, totalVolume);
  packingDensity = (vdwVolume / totalVolume);
  s.freeGrid();
}

}  // namespace Descriptors
}  // namespace RDKit