File: RGroupFingerprintScore.cpp

package info (click to toggle)
rdkit 202209.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 203,880 kB
  • sloc: cpp: 334,239; python: 80,247; ansic: 24,579; java: 7,667; sql: 2,123; yacc: 1,884; javascript: 1,358; lex: 1,260; makefile: 576; xml: 229; fortran: 183; cs: 181; sh: 101
file content (345 lines) | stat: -rw-r--r-- 11,102 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
//
//  Copyright (C) 2020 Gareth Jones, Glysade LLC
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//

#include "RGroupFingerprintScore.h"
#include "GraphMol/Fingerprints/Fingerprints.h"
#include "GraphMol//Fingerprints/MorganFingerprints.h"
#include <GraphMol/SmilesParse/SmilesParse.h>
#include "../../../External/GA/util/Util.h"
#include <memory>
#include <utility>
#include <vector>
#include <map>
#ifdef RDK_BUILD_THREADSAFE_SSS
#include <mutex>
#endif

// #define DEBUG

namespace RDKit {

namespace detail {
// Create a fingerprint for empty or missing R groups
// that is the same as a hydrogen R group
RData dummyHydrogenFingerprint(int label) {
  static RData fp = nullptr;
  if (fp == nullptr) {
    fp = boost::make_shared<RGroupData>();
    auto mol = ROMOL_SPTR(SmilesToMol("*[H]"));
    std::vector<int> attachments{label};
    fp->add(mol, attachments);
  }
  fp->attachments.clear();
  fp->attachments.insert(label);
  return fp;
}
}  // namespace detail

static const int fingerprintSize = 512;
static const bool useTopologicalFingerprints = false;

// Add fingerprint information to RGroupData
void addFingerprintToRGroupData(RGroupData *rgroupData) {
  if (rgroupData->fingerprint == nullptr) {
    RWMol mol(*rgroupData->combinedMol);
    for (auto atom : mol.atoms()) {
      // replace attachment atom by Boron
      // TODO- Handle multiple attachments differently?
      if (atom->getAtomicNum() == 0) {
        atom->setAtomicNum(5);
        if (atom->getIsotope() > 0) {
          atom->setIsotope(0);
        }
      }
    }
    try {
      MolOps::sanitizeMol(mol);
    } catch (MolSanitizeException &) {
      BOOST_LOG(rdWarningLog)
          << "Failed to sanitize RGroup fingerprint mol for "
          << rgroupData->smiles << std::endl;
    }
#ifdef DEBUG
    std::cerr << "Fingerprint mol smiles " << MolToSmiles(mol) << " ";
#endif
    auto fingerprint = useTopologicalFingerprints
                           ? RDKFingerprintMol(mol, 1, 7, fingerprintSize)
                           : MorganFingerprints::getFingerprintAsBitVect(
                                 mol, 2, fingerprintSize);
    fingerprint->getOnBits(rgroupData->fingerprintOnBits);
    rgroupData->fingerprint.reset(fingerprint);
  }
#ifdef DEBUG
  std::cerr << "Combined mol smiles " << MolToSmiles(*rgroupData->combinedMol)
            << std::endl;
#endif
}

// Adds or subtracts a molecule match to the rgroup fingerprint bit counts
// vectors
void FingerprintVarianceScoreData::modifyVarianceData(
    int matchNumber, int permutationNumber,
    const std::vector<std::vector<RGroupMatch>> &matches,
    const std::set<int> &labels, bool add) {
  // For each label (group)
  const auto &match = matches.at(matchNumber).at(permutationNumber);
  for (int l : labels) {
    auto rg = match.rgroups.find(l);
    std::shared_ptr<VarianceDataForLabel> variableDataForLabel;
    RData rgroupData;
    if (rg != match.rgroups.end()) {
      rgroupData = rg->second;
    } else {
      rgroupData = detail::dummyHydrogenFingerprint(l);
    }
    auto df = labelsToVarianceData.find(l);
    if (df == labelsToVarianceData.end()) {
      variableDataForLabel = std::make_shared<VarianceDataForLabel>(l);
      labelsToVarianceData.emplace(l, variableDataForLabel);
    } else {
      variableDataForLabel = df->second;
    }
    if (add) {
#ifdef DEBUG
      std::cerr << "Label " << l << " ";
#endif
      variableDataForLabel->addRgroupData(rgroupData.get());
    } else {
      variableDataForLabel->removeRgroupData(rgroupData.get());
    }
  }
  auto rgroupsMissing = match.numberMissingUserRGroups;
  if (add) {
    numberOfMissingUserRGroups += rgroupsMissing;
    numberOfMolecules++;
  } else {
    numberOfMissingUserRGroups -= rgroupsMissing;
    numberOfMolecules--;
  }
}

// Adds a molecule match to the rgroup fingerprint bit counts
// vectors
void FingerprintVarianceScoreData::addVarianceData(
    int matchNumber, int permutationNumber,
    const std::vector<std::vector<RGroupMatch>> &matches,
    const std::set<int> &labels) {
  modifyVarianceData(matchNumber, permutationNumber, matches, labels, true);
}

// Subtracts a molecule match from the rgroup fingerprint bit counts
// vectors
void FingerprintVarianceScoreData::removeVarianceData(
    int matchNumber, int permutationNumber,
    const std::vector<std::vector<RGroupMatch>> &matches,
    const std::set<int> &labels) {
  modifyVarianceData(matchNumber, permutationNumber, matches, labels, false);
}

// fingerprint variance score
// The arithmetic mean of the mean fingerprint bit variances for the
// fingerprints at each rgroup position.
double fingerprintVarianceScore(
    const std::vector<size_t> &permutation,
    const std::vector<std::vector<RGroupMatch>> &matches,
    const std::set<int> &labels,
    FingerprintVarianceScoreData *fingerprintVarianceScoreData) {
#ifdef DEBUG
  std::cerr << "---------------------------------------------------"
            << std::endl;
  std::cerr << "Fingerprint Scoring permutation "
            << " num matches: " << matches.size() << std::endl;
#endif
  CHECK_INVARIANT(permutation.size() <= matches.size(), "");
  FingerprintVarianceScoreData fingerprintVarianceScoreData2;
  if (!fingerprintVarianceScoreData) {
    fingerprintVarianceScoreData = &fingerprintVarianceScoreData2;
  }
  auto &labelsToVarianceData =
      fingerprintVarianceScoreData->labelsToVarianceData;

  // For each label (group)
  for (int l : labels) {
#ifdef DEBUG
    std::cerr << "Label: " << l << " ";
#endif

    std::shared_ptr<VarianceDataForLabel> variableDataForLabel;
    auto d = labelsToVarianceData.find(l);
    if (d == labelsToVarianceData.end()) {
      variableDataForLabel = std::make_shared<VarianceDataForLabel>(l);
      labelsToVarianceData.emplace(l, variableDataForLabel);
    } else {
      variableDataForLabel = d->second;
    }

    for (size_t m = 0; m < permutation.size(); ++m) {  // for each molecule
      const auto &match = matches[m].at(permutation[m]);
      auto rg = match.rgroups.find(l);
      RData rgroupData;
      if (rg != match.rgroups.end()) {
        rgroupData = rg->second;
      } else {
        rgroupData = detail::dummyHydrogenFingerprint(l);
      }
#ifdef DEBUG
      std::cerr << rgroupData->smiles << ", ";
#endif
      variableDataForLabel->addRgroupData(rgroupData.get());
    }
#ifdef DEBUG
    std::cerr << std::endl;
#endif
  }

  size_t numberMissingRGroups = 0;
  for (size_t m = 0; m < permutation.size(); ++m) {  // for each molecule
    numberMissingRGroups +=
        matches[m].at(permutation[m]).numberMissingUserRGroups;
  }
  fingerprintVarianceScoreData->numberOfMissingUserRGroups +=
      numberMissingRGroups;
  fingerprintVarianceScoreData->numberOfMolecules += permutation.size();

  return fingerprintVarianceScoreData->fingerprintVarianceGroupScore();
}

// calculates fingerprint variance score from rgroup bit counts
double FingerprintVarianceScoreData::fingerprintVarianceGroupScore() {
  // arithmetic mean of scores for each label
#ifdef DEBUG
  std::cerr << "fingerprint variance score: ";
#endif
  auto sum = std::accumulate(
      labelsToVarianceData.cbegin(), labelsToVarianceData.cend(), 0.0,
      [](double sum,
         std::pair<int, std::shared_ptr<VarianceDataForLabel>> pair) {
        auto variance = pair.second->variance();
#ifdef DEBUG
        std::cerr << variance << ',';
#endif
        return sum + variance;
      });

  // Heuristic correction of missing user r_groups - equivalent to a variance
  // penalty of 1 for each missing user R-group across the entire dataset
  CHECK_INVARIANT(numberOfMolecules > 0, "No compounds to be scored!");
  double rgroupPenalty =
      (double)numberOfMissingUserRGroups / (double)numberOfMolecules;
  // double the penalty to catch systems like
  // https://github.com/rdkit/rdkit/issues/3896

  auto rootSum = sqrt(sum);
  auto score = rootSum + 2.0 * rgroupPenalty;
  score = rootSum;

#ifdef DEBUG
  std::cerr << " sum " << sum << " root sum " << rootSum << " rgroup penalty "
            << rgroupPenalty << " score " << score << std::endl;
#endif
  // want to minimize this score
  return -score;
}

VarianceDataForLabel::VarianceDataForLabel(const int &label,
                                           int numberFingerprints,
                                           std::vector<int> bitCounts)
    : label(label),
      numberFingerprints(numberFingerprints),
      bitCounts(std::move(bitCounts)) {}

VarianceDataForLabel::VarianceDataForLabel(const int &label) : label(label) {
  numberFingerprints = 0;
  bitCounts = std::vector<int>(fingerprintSize, 0.0);
}

#ifdef RDK_BUILD_THREADSAFE_SSS
static std::mutex groupMutex;
#endif

// add an rgroup structure to a bit counts array
void VarianceDataForLabel::addRgroupData(RGroupData *rgroupData) {
  {
#ifdef RDK_BUILD_THREADSAFE_SSS
    const std::lock_guard<std::mutex> lock(groupMutex);
#endif
    if (rgroupData->fingerprint == nullptr) {
      addFingerprintToRGroupData(rgroupData);
    }
  }

  ++numberFingerprints;
  const auto &onBits = rgroupData->fingerprintOnBits;
  for (int b : onBits) {
    ++bitCounts[b];
  }
}

// remove an rgroup structure to a bit counts array
void VarianceDataForLabel::removeRgroupData(RGroupData *rgroupData) {
  if (rgroupData->fingerprint == nullptr) {
    addFingerprintToRGroupData(rgroupData);
  }
  --numberFingerprints;
  const auto &onBits = rgroupData->fingerprintOnBits;
  for (int b : onBits) {
    --bitCounts[b];
  }
}

// calculate the mean variance for a bit counts array
double VarianceDataForLabel::variance() const {
  auto lambda = [this](double sum, int bitCount) {
    if (bitCount == 0) {
      return sum;
    }
    auto dNumberFingerprints = (double)numberFingerprints;
    auto dBitCount = (double)bitCount;
    // variance calculation because fingerprint is binary:
    // sum  == squared sum == bit count
    // ss = sqrSum - (sum * sum) / cnt;
    // correction to bit count:
    dBitCount = dNumberFingerprints / 2.0 + dBitCount / 2.0;
    auto ss = dBitCount - (dBitCount * dBitCount) / dNumberFingerprints;
    double variancePerBit = ss / dNumberFingerprints;
#ifdef DEBUG
    std::cerr << variancePerBit << ',';
#endif

    return sum + variancePerBit;
  };

#ifdef DEBUG
  std::cerr << label << ": Bitcounts "
            << GarethUtil::collectionToString(bitCounts, ",") << std::endl;
  std::cerr << "Variance per bit ";
#endif
  auto totalVariance =
      std::accumulate(bitCounts.cbegin(), bitCounts.cend(), 0.0, lambda);

#ifdef DEBUG
  std::cerr << std::endl;
#endif
#ifdef DEBUG
  auto rmsVariance = sqrt(totalVariance);
  std::cerr << "Total Variance " << totalVariance << " RMS Variance "
            << rmsVariance << std::endl;
#endif

  return totalVariance;
}

void FingerprintVarianceScoreData::clear() {
  numberOfMissingUserRGroups = 0;
  numberOfMolecules = 0;
  labelsToVarianceData.clear();
}

}  // namespace RDKit