diff --git a/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp b/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp index 3955cfe00..f533c196a 100644 --- a/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp +++ b/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp @@ -79,14 +79,14 @@ PyObject *getEuclideanDistMat(python::object descripMat) { // grab a pointer to the data in the array so that we can directly put // values in there // and avoid copying : - double *dMat = (double *)PyArray_DATA(distRes); + auto *dMat = (double *)PyArray_DATA(distRes); PyArrayObject *copy; copy = (PyArrayObject *)PyArray_ContiguousFromObject( descMatObj, PyArray_DESCR((PyArrayObject *)descMatObj)->type_num, 2, 2); // if we have double array if (PyArray_DESCR((PyArrayObject *)descMatObj)->type_num == NPY_DOUBLE) { - double *desc = (double *)PyArray_DATA((PyArrayObject *)descMatObj); + auto *desc = (double *)PyArray_DATA((PyArrayObject *)descMatObj); // REVIEW: create an adaptor object to hold a double * and support // operator[]() so that we don't have to do this stuff: @@ -110,7 +110,7 @@ PyObject *getEuclideanDistMat(python::object descripMat) { // if we have a float array else if (PyArray_DESCR((PyArrayObject *)descMatObj)->type_num == NPY_FLOAT) { - float *desc = (float *)PyArray_DATA(copy); + auto *desc = (float *)PyArray_DATA(copy); auto **desc2D = new float *[nrows]; for (i = 0; i < nrows; i++) { desc2D[i] = desc; @@ -155,7 +155,7 @@ PyObject *getEuclideanDistMat(python::object descripMat) { npy_intp dMatLen = nrows * (nrows - 1) / 2; distRes = (PyArrayObject *)PyArray_SimpleNew(1, &dMatLen, NPY_DOUBLE); - double *dMat = (double *)PyArray_DATA(distRes); + auto *dMat = (double *)PyArray_DATA(distRes); // assume that we a have a list of list of values (that can be extracted to // double) @@ -198,9 +198,8 @@ PyObject *getTanimotoDistMat(python::object bitVectList) { } npy_intp dMatLen = nrows * (nrows - 1) / 2; - PyArrayObject *simRes = - (PyArrayObject *)PyArray_SimpleNew(1, &dMatLen, NPY_DOUBLE); - double *sMat = (double *)PyArray_DATA(simRes); + auto *simRes = (PyArrayObject *)PyArray_SimpleNew(1, &dMatLen, NPY_DOUBLE); + auto *sMat = (double *)PyArray_DATA(simRes); if (ebvWorks.check()) { PySequenceHolder dData(bitVectList); @@ -234,9 +233,8 @@ PyObject *getTanimotoSimMat(python::object bitVectList) { } npy_intp dMatLen = nrows * (nrows - 1) / 2; - PyArrayObject *simRes = - (PyArrayObject *)PyArray_SimpleNew(1, &dMatLen, NPY_DOUBLE); - double *sMat = (double *)PyArray_DATA(simRes); + auto *simRes = (PyArrayObject *)PyArray_SimpleNew(1, &dMatLen, NPY_DOUBLE); + auto *sMat = (double *)PyArray_DATA(simRes); if (ebvWorks.check()) { PySequenceHolder dData(bitVectList); diff --git a/Code/DataStructs/BitOps.cpp b/Code/DataStructs/BitOps.cpp index fe13a8ca7..e927a279b 100644 --- a/Code/DataStructs/BitOps.cpp +++ b/Code/DataStructs/BitOps.cpp @@ -110,12 +110,18 @@ bool AllProbeBitsMatch(const char* probe, const char* ref) { while (nProbeOn) { while (currRefBit < currProbeBit && nRefOn > 0) { - if (refFormat == 2) currRefBit++; + if (refFormat == 2) { + currRefBit++; + } currRefBit = getBitId(ref, refFormat, refSize, currRefBit); nRefOn--; } - if (currRefBit != currProbeBit) return false; - if (probeFormat == 2) currProbeBit++; + if (currRefBit != currProbeBit) { + return false; + } + if (probeFormat == 2) { + currProbeBit++; + } currProbeBit = getBitId(probe, probeFormat, probeSize, currProbeBit); nProbeOn--; } @@ -154,11 +160,15 @@ bool AllProbeBitsMatch(const T1& probe, const std::string& pkl) { // if(probe.getBit(i)){ for (std::vector::const_iterator i = obl.begin(); i != obl.end(); i++) { while (currBit < *i && nOn > 0) { - if (format == 2) currBit++; + if (format == 2) { + currBit++; + } currBit = getBitId(text, format, size, currBit); nOn--; } - if (currBit != *i) return false; + if (currBit != *i) { + return false; + } //} } return true; @@ -208,15 +218,19 @@ const bool canUseBitmapHack = bool EBVToBitmap(const ExplicitBitVect& bv, const unsigned char*& fp, unsigned int& nBytes) { - if (!canUseBitmapHack) return false; - const bitset_impl* p1 = (const bitset_impl*)(const void*)bv.dp_bits; + if (!canUseBitmapHack) { + return false; + } + const auto* p1 = (const bitset_impl*)(const void*)bv.dp_bits; // Run-time sanity check (just in case) if (p1->m_num_bits != bv.dp_bits->size()) { return false; } fp = (const unsigned char*)p1->m_bits.data(); nBytes = (unsigned int)p1->m_num_bits / 8; - if (p1->m_num_bits % 8) ++nBytes; + if (p1->m_num_bits % 8) { + ++nBytes; + } return true; } } // end of local namespace @@ -254,10 +268,13 @@ int NumOnBitsInCommon(const ExplicitBitVect& bv1, const ExplicitBitVect& bv2) { // """ ------------------------------------------------------- template double TanimotoSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } unsigned int total = bv1.getNumOnBits() + bv2.getNumOnBits(); - if (total == 0) return 1.0; + if (total == 0) { + return 1.0; + } unsigned int common = NumOnBitsInCommon(bv1, bv2); return (double)common / (double)(total - common); } @@ -266,22 +283,25 @@ template double TverskySimilarity(const T1& bv1, const T2& bv2, double a, double b) { RANGE_CHECK(0, a, 1); RANGE_CHECK(0, b, 1); - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } double x = NumOnBitsInCommon(bv1, bv2); double y = bv1.getNumOnBits(); double z = bv2.getNumOnBits(); double denom = a * y + b * z + (1 - a - b) * x; - if (denom == 0.0) + if (denom == 0.0) { return 1.0; - else + } else { return x / denom; + } } template double CosineSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } double x = NumOnBitsInCommon(bv1, bv2); double y = bv1.getNumOnBits(); double z = bv2.getNumOnBits(); @@ -295,8 +315,9 @@ double CosineSimilarity(const T1& bv1, const T2& bv2) { template double KulczynskiSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } double x = NumOnBitsInCommon(bv1, bv2); double y = bv1.getNumOnBits(); double z = bv2.getNumOnBits(); @@ -310,8 +331,9 @@ double KulczynskiSimilarity(const T1& bv1, const T2& bv2) { template double DiceSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } double x = NumOnBitsInCommon(bv1, bv2); double y = bv1.getNumOnBits(); double z = bv2.getNumOnBits(); @@ -325,8 +347,9 @@ double DiceSimilarity(const T1& bv1, const T2& bv2) { template double SokalSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } double x = NumOnBitsInCommon(bv1, bv2); double y = bv1.getNumOnBits(); double z = bv2.getNumOnBits(); @@ -336,8 +359,9 @@ double SokalSimilarity(const T1& bv1, const T2& bv2) { template double McConnaugheySimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } double x = NumOnBitsInCommon(bv1, bv2); double y = bv1.getNumOnBits(); double z = bv2.getNumOnBits(); @@ -351,20 +375,25 @@ double McConnaugheySimilarity(const T1& bv1, const T2& bv2) { template inline T tmin(T v1, T v2) { - if (v1 < v2) return v1; + if (v1 < v2) { + return v1; + } return v2; } template inline T tmax(T v1, T v2) { - if (v1 > v2) return v1; + if (v1 > v2) { + return v1; + } return v2; } template double AsymmetricSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } double x = NumOnBitsInCommon(bv1, bv2); double y = bv1.getNumOnBits(); double z = bv2.getNumOnBits(); @@ -378,8 +407,9 @@ double AsymmetricSimilarity(const T1& bv1, const T2& bv2) { template double BraunBlanquetSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } double x = NumOnBitsInCommon(bv1, bv2); double y = bv1.getNumOnBits(); double z = bv2.getNumOnBits(); @@ -393,25 +423,28 @@ double BraunBlanquetSimilarity(const T1& bv1, const T2& bv2) { template double RusselSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } double x = NumOnBitsInCommon(bv1, bv2); return x / bv1.getNumBits(); } template double RogotGoldbergSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } double x = NumOnBitsInCommon(bv1, bv2); double y = bv1.getNumOnBits(); double z = bv2.getNumOnBits(); double l = bv1.getNumBits(); double d = l - y - z + x; - if ((x == l) || (d == l)) + if ((x == l) || (d == l)) { return 1.0; - else + } else { return (x / (y + z) + (d) / (2 * l - y - z)); + } } // """ ------------------------------------------------------- @@ -428,8 +461,9 @@ double RogotGoldbergSimilarity(const T1& bv1, const T2& bv2) { // """ ------------------------------------------------------- template double OnBitSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } double num = NumOnBitsInCommon(bv1, bv2); double denom = (bv1 | bv2).getNumOnBits(); @@ -456,8 +490,9 @@ double OnBitSimilarity(const T1& bv1, const T2& bv2) { // """ ------------------------------------------------------- template int NumBitsInCommon(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } return bv1.getNumBits() - (bv1 ^ bv2).getNumOnBits(); } @@ -483,8 +518,9 @@ int NumBitsInCommon(const ExplicitBitVect& bv1, const ExplicitBitVect& bv2) { // """ ------------------------------------------------------- template double AllBitSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } return double(NumBitsInCommon(bv1, bv2)) / bv1.getNumBits(); } @@ -505,8 +541,9 @@ double AllBitSimilarity(const T1& bv1, const T2& bv2) { // """ ------------------------------------------------------- template IntVect OnBitsInCommon(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } IntVect res; (bv1 & bv2).getOnBits(res); return res; @@ -528,8 +565,9 @@ IntVect OnBitsInCommon(const T1& bv1, const T2& bv2) { // """ ------------------------------------------------------- template IntVect OffBitsInCommon(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } IntVect res; (~(bv1 | bv2)).getOnBits(res); return res; @@ -562,8 +600,9 @@ IntVect OffBitsInCommon(const T1& bv1, const T2& bv2) { // """ ------------------------------------------------------- template DoubleVect OnBitProjSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } DoubleVect res(2, 0.0); double num = NumOnBitsInCommon(bv1, bv2); if (num) { @@ -600,8 +639,9 @@ DoubleVect OnBitProjSimilarity(const T1& bv1, const T2& bv2) { // """ ------------------------------------------------------- template DoubleVect OffBitProjSimilarity(const T1& bv1, const T2& bv2) { - if (bv1.getNumBits() != bv2.getNumBits()) + if (bv1.getNumBits() != bv2.getNumBits()) { throw ValueErrorException("BitVects must be same length"); + } DoubleVect res(2, 0.0); double num = (bv1 | bv2).getNumOffBits(); if (num) { @@ -613,8 +653,9 @@ DoubleVect OffBitProjSimilarity(const T1& bv1, const T2& bv2) { template T1* FoldFingerprint(const T1& bv1, unsigned int factor) { - if (factor <= 0 || factor >= bv1.getNumBits()) + if (factor <= 0 || factor >= bv1.getNumBits()) { throw ValueErrorException("invalid fold factor"); + } int initSize = bv1.getNumBits(); int resSize = initSize / factor; @@ -633,7 +674,9 @@ template std::string BitVectToText(const T1& bv1) { std::string res(bv1.getNumBits(), '0'); for (unsigned int i = 0; i < bv1.getNumBits(); i++) { - if (bv1.getBit(i)) res[i] = '1'; + if (bv1.getBit(i)) { + res[i] = '1'; + } } return res; } @@ -706,7 +749,9 @@ void UpdateBitVectFromFPSText(T1& bv1, const std::string& fps) { } for (unsigned int bit = 0; bit < 8 && bitIdx < bv1.getNumBits(); ++bit, ++bitIdx) { - if (c & (1 << bit)) bv1.setBit(bitIdx); + if (c & (1 << bit)) { + bv1.setBit(bitIdx); + } } } } @@ -719,7 +764,9 @@ void UpdateBitVectFromBinaryText(T1& bv1, const std::string& fps) { unsigned short c = fps[i]; for (unsigned int bit = 0; bit < 8 && bitIdx < bv1.getNumBits(); ++bit, ++bitIdx) { - if (c & (1 << bit)) bv1.setBit(bitIdx); + if (c & (1 << bit)) { + bv1.setBit(bitIdx); + } } } } diff --git a/Code/DataStructs/DiscreteValueVect.cpp b/Code/DataStructs/DiscreteValueVect.cpp index 9bde64bb7..92f13a04c 100644 --- a/Code/DataStructs/DiscreteValueVect.cpp +++ b/Code/DataStructs/DiscreteValueVect.cpp @@ -92,8 +92,8 @@ unsigned int computeL1Norm(const DiscreteValueVect &v1, if (valType <= DiscreteValueVect::EIGHTBITVALUE) { DiscreteDistMat *dmat = getDiscreteDistMat(); - unsigned char *cd1 = (unsigned char *)(data1); - unsigned char *cd2 = (unsigned char *)(data2); + auto *cd1 = (unsigned char *)(data1); + auto *cd2 = (unsigned char *)(data2); const unsigned char *cend = cd1 + (v1.getNumInts() * 4); while (cd1 != cend) { if (*cd1 == *cd2) { diff --git a/Code/DataStructs/ExplicitBitVect.cpp b/Code/DataStructs/ExplicitBitVect.cpp index 612920ce2..8b8ba2410 100644 --- a/Code/DataStructs/ExplicitBitVect.cpp +++ b/Code/DataStructs/ExplicitBitVect.cpp @@ -52,7 +52,9 @@ ExplicitBitVect::ExplicitBitVect(const ExplicitBitVect &other) }; ExplicitBitVect &ExplicitBitVect::operator=(const ExplicitBitVect &other) { - if (this == &other) return *this; + if (this == &other) { + return *this; + } d_size = other.d_size; delete dp_bits; dp_bits = new boost::dynamic_bitset<>(*(other.dp_bits)); @@ -169,10 +171,14 @@ unsigned int ExplicitBitVect::getNumOffBits() const { // the contents of v are blown out void ExplicitBitVect::getOnBits(IntVect &v) const { unsigned int nOn = getNumOnBits(); - if (!v.empty()) IntVect().swap(v); + if (!v.empty()) { + IntVect().swap(v); + } v.reserve(nOn); for (unsigned int i = 0; i < d_size; i++) { - if ((bool)(*dp_bits)[i]) v.push_back(i); + if ((bool)(*dp_bits)[i]) { + v.push_back(i); + } } }; diff --git a/Code/DataStructs/FPBReader.cpp b/Code/DataStructs/FPBReader.cpp index 0dc64f1ac..37d489778 100644 --- a/Code/DataStructs/FPBReader.cpp +++ b/Code/DataStructs/FPBReader.cpp @@ -73,11 +73,13 @@ void extractPopCounts(FPBReader_impl *dp_impl, boost::uint64_t sz, /* this section of the FPB format is under-documented in Andrew's code, * fortunately it looks pretty simple */ - if (sz % 4) + if (sz % 4) { throw ValueErrorException("POPC chunk size must be a multiple of 4 bytes"); + } unsigned int nEntries = sz / 4; - if (nEntries < 9) + if (nEntries < 9) { throw ValueErrorException("POPC must contain at least 9 offsets"); + } dp_impl->popCountOffsets.reserve(nEntries); for (unsigned int i = 0; i < nEntries; ++i) { @@ -128,9 +130,10 @@ void extractArenaDetails(FPBReader_impl *dp_impl, boost::uint64_t sz) { // streamRead(*dp_impl->istrm, spacer); // now move forward the length of the spacer - if (spacer) + if (spacer) { dp_impl->istrm->seekg(static_cast(spacer), std::ios_base::cur); + } dp_impl->fpDataOffset = dp_impl->istrm->tellg(); dp_impl->istrm->seekg( static_cast(numBytesStoredPerFingerprint * dp_impl->len), @@ -205,7 +208,7 @@ RDKIT_DATASTRUCTS_EXPORT boost::dynamic_bitset<> *bytesToBitset(const boost::uin if (!(nBytes % sizeof(boost::dynamic_bitset<>::block_type))) { // I believe this could be faster (needs to be verified of course) unsigned int nBlocks = nBytes / sizeof(boost::dynamic_bitset<>::block_type); - const boost::dynamic_bitset<>::block_type *fpBlocks = + const auto *fpBlocks = reinterpret_cast::block_type *>(fpData); return new boost::dynamic_bitset<>(fpBlocks, fpBlocks + nBlocks); } else { @@ -234,7 +237,9 @@ ExplicitBitVect *extractFP(const FPBReader_impl *dp_impl, unsigned int which) { } extractBytes(dp_impl, which, fpData); boost::dynamic_bitset<> *resDBS = bytesToBitset(fpData, dp_impl->nBits); - if (dp_impl->df_lazy) delete[] fpData; + if (dp_impl->df_lazy) { + delete[] fpData; + } return new ExplicitBitVect(resDBS); }; @@ -252,7 +257,9 @@ double tanimoto(const FPBReader_impl *dp_impl, unsigned int which, extractBytes(dp_impl, which, fpData); double res = CalcBitmapTanimoto(fpData, bv, dp_impl->numBytesStoredPerFingerprint); - if (dp_impl->df_lazy) delete[] fpData; + if (dp_impl->df_lazy) { + delete[] fpData; + } return res; }; @@ -270,7 +277,9 @@ double tversky(const FPBReader_impl *dp_impl, unsigned int which, extractBytes(dp_impl, which, fpData); double res = CalcBitmapTversky(fpData, bv, dp_impl->numBytesStoredPerFingerprint, ca, cb); - if (dp_impl->df_lazy) delete[] fpData; + if (dp_impl->df_lazy) { + delete[] fpData; + } return res; }; @@ -434,7 +443,7 @@ void tanimotoNeighbors(const FPBReader_impl *dp_impl, const boost::uint8_t *bv, // Searches of Chemical Fingerprints in Linear and Sublinear Time. J. Chem. // Inf. Model. 47, 302–317 (2007). // http://pubs.acs.org/doi/abs/10.1021/ci600358f - boost::uint32_t minDbCount = + auto minDbCount = static_cast(floor(threshold * probeCount)); boost::uint32_t maxDbCount = (threshold > 1e-6) @@ -465,7 +474,9 @@ void tanimotoNeighbors(const FPBReader_impl *dp_impl, const boost::uint8_t *bv, } } } - if (dp_impl->df_lazy) delete[] dbv; + if (dp_impl->df_lazy) { + delete[] dbv; + } } void tverskyNeighbors(const FPBReader_impl *dp_impl, const boost::uint8_t *bv, @@ -487,7 +498,7 @@ void tverskyNeighbors(const FPBReader_impl *dp_impl, const boost::uint8_t *bv, // Searches of Chemical Fingerprints in Linear and Sublinear Time. J. Chem. // Inf. Model. 47, 302–317 (2007). // http://pubs.acs.org/doi/abs/10.1021/ci600358f - boost::uint32_t minDbCount = static_cast(floor( + auto minDbCount = static_cast(floor( (threshold * probeCount * ca) / (1. - threshold + threshold * ca))); boost::uint32_t maxDbCount = ((threshold * cb) > 1e-6) @@ -516,7 +527,9 @@ void tverskyNeighbors(const FPBReader_impl *dp_impl, const boost::uint8_t *bv, res.push_back(std::make_pair(sim, i)); } } - if (dp_impl->df_lazy) delete[] dbv; + if (dp_impl->df_lazy) { + delete[] dbv; + } } void containingNeighbors(const FPBReader_impl *dp_impl, @@ -544,14 +557,18 @@ void containingNeighbors(const FPBReader_impl *dp_impl, res.push_back(i); } } - if (dp_impl->df_lazy) delete[] dbv; + if (dp_impl->df_lazy) { + delete[] dbv; + } } } // end of detail namespace void FPBReader::init() { PRECONDITION(dp_istrm, "no stream"); - if (df_init) return; + if (df_init) { + return; + } dp_impl = new detail::FPBReader_impl; dp_impl->istrm = dp_istrm; @@ -563,7 +580,9 @@ void FPBReader::init() { throw BadFileException("Invalid FPB magic"); } while (1) { - if (dp_istrm->eof()) throw BadFileException("EOF hit before FEND record"); + if (dp_istrm->eof()) { + throw BadFileException("EOF hit before FEND record"); + } std::string chunkNm; boost::uint64_t chunkSz; boost::uint8_t *chunk = nullptr; @@ -604,11 +623,13 @@ void FPBReader::init() { } } if ((!df_lazyRead && !dp_impl->dp_arenaChunk) || - (df_lazyRead && !dp_impl->fpDataOffset)) + (df_lazyRead && !dp_impl->fpDataOffset)) { throw BadFileException("No AREN record found"); + } if ((!df_lazyRead && !dp_impl->dp_idChunk) || - (df_lazyRead && !dp_impl->idDataOffset)) + (df_lazyRead && !dp_impl->idDataOffset)) { throw BadFileException("No FPID record found"); + } df_init = true; }; diff --git a/Code/DataStructs/MultiFPBReader.cpp b/Code/DataStructs/MultiFPBReader.cpp index 8e6975ca3..6ddb7c6de 100644 --- a/Code/DataStructs/MultiFPBReader.cpp +++ b/Code/DataStructs/MultiFPBReader.cpp @@ -70,7 +70,9 @@ struct sim_args { void tversky_helper(unsigned int threadId, unsigned int numThreads, const sim_args *args) { for (unsigned int i = threadId; i < args->readers.size(); i += numThreads) { - if (args->initOnSearch) args->readers[i]->init(); + if (args->initOnSearch) { + args->readers[i]->init(); + } std::vector> r_res = args->readers[i]->getTverskyNeighbors(args->bv, args->ca, args->cb, args->threshold); @@ -87,7 +89,9 @@ void tversky_helper(unsigned int threadId, unsigned int numThreads, void tani_helper(unsigned int threadId, unsigned int numThreads, const sim_args *args) { for (unsigned int i = threadId; i < args->readers.size(); i += numThreads) { - if (args->initOnSearch) args->readers[i]->init(); + if (args->initOnSearch) { + args->readers[i]->init(); + } std::vector> r_res = args->readers[i]->getTanimotoNeighbors(args->bv, args->threshold); (*args->res)[i].clear(); @@ -157,7 +161,9 @@ void contain_helper(unsigned int threadId, unsigned int numThreads, std::vector> *accum, bool initOnSearch) { for (unsigned int i = threadId; i < readers->size(); i += numThreads) { - if (initOnSearch) (*readers)[i]->init(); + if (initOnSearch) { + (*readers)[i]->init(); + } (*accum)[i] = (*readers)[i]->getContainingNeighbors(bv); } } @@ -209,8 +215,9 @@ void MultiFPBReader::init() { if (!nBits) { nBits = rdr->nBits(); } else { - if (rdr->nBits() != nBits) + if (rdr->nBits() != nBits) { throw ValueErrorException("bit lengths of child readers don't match"); + } } } df_init = true; diff --git a/Code/DataStructs/SparseBitVect.cpp b/Code/DataStructs/SparseBitVect.cpp index 6c6a63017..c96915bcc 100644 --- a/Code/DataStructs/SparseBitVect.cpp +++ b/Code/DataStructs/SparseBitVect.cpp @@ -62,10 +62,11 @@ bool SparseBitVect::operator[](const unsigned int which) const { if (which >= d_size) { throw IndexErrorException(which); } - if (dp_bits->count(which)) + if (dp_bits->count(which)) { return true; - else + } else { return false; + } } // """ ------------------------------------------------------- @@ -75,7 +76,9 @@ bool SparseBitVect::operator[](const unsigned int which) const { // // """ ------------------------------------------------------- SparseBitVect &SparseBitVect::operator=(const SparseBitVect &other) { - if (this == &other) return *this; + if (this == &other) { + return *this; + } IntSet *bv = other.dp_bits; delete dp_bits; d_size = other.getNumBits(); @@ -136,7 +139,9 @@ SparseBitVect SparseBitVect::operator^(const SparseBitVect &other) const { SparseBitVect SparseBitVect::operator~() const { SparseBitVect ans(d_size); for (unsigned int i = 0; i < d_size; i++) { - if (!getBit(i)) ans.setBit(i); + if (!getBit(i)) { + ans.setBit(i); + } } return (ans); @@ -152,10 +157,11 @@ bool SparseBitVect::getBit(const unsigned int which) const { if (which >= d_size) { throw IndexErrorException(which); } - if (dp_bits->count(which)) + if (dp_bits->count(which)) { return true; - else + } else { return false; + } } // """ ------------------------------------------------------- @@ -168,10 +174,11 @@ bool SparseBitVect::getBit(const IntVectIter which) const { if (*which < 0 || static_cast(*which) >= d_size) { throw IndexErrorException(*which); } - if (dp_bits->count(*which)) + if (dp_bits->count(*which)) { return true; - else + } else { return false; + } } // """ ------------------------------------------------------- @@ -184,10 +191,11 @@ bool SparseBitVect::getBit(const IntSetIter which) const { if (*which < 0 || static_cast(*which) >= d_size) { throw IndexErrorException(*which); } - if (dp_bits->count(*which)) + if (dp_bits->count(*which)) { return true; - else + } else { return false; + } } // """ ------------------------------------------------------- @@ -266,7 +274,9 @@ void SparseBitVect::getOnBits(IntVect &v) const { throw ValueErrorException("BitVect not properly initialized."); } unsigned int nOn = getNumOnBits(); - if (!v.empty()) IntVect().swap(v); + if (!v.empty()) { + IntVect().swap(v); + } v.reserve(nOn); v.resize(nOn); std::copy(dp_bits->begin(), dp_bits->end(), v.begin()); diff --git a/Code/DataStructs/Utils.cpp b/Code/DataStructs/Utils.cpp index e09375197..333fb668b 100644 --- a/Code/DataStructs/Utils.cpp +++ b/Code/DataStructs/Utils.cpp @@ -34,7 +34,9 @@ void FromDaylightString(T &sbv, const std::string &s) { size_t length = s.length(); size_t nBits; - if (s[length - 1] == '\n') length -= 1; + if (s[length - 1] == '\n') { + length -= 1; + } // 4 bytes in the ascii correspond to 3 bytes in the binary // plus there's one extra ascii byte for the pad marker @@ -81,7 +83,9 @@ void FromBitString(T &sbv, const std::string &s) { PRECONDITION(s.length() <= sbv.getNumBits(), "bad bitvect length"); sbv.clearBits(); for (unsigned int i = 0; i < sbv.getNumBits(); ++i) { - if (s[i] == '1') sbv.setBit(i); + if (s[i] == '1') { + sbv.setBit(i); + } } } @@ -322,16 +326,17 @@ void a2b(const char *a4, char *b3) { *** b3: |000000111111222222333333 *** |=====+=====+=====+=====| *********************************************/ - if (i == 0) + if (i == 0) { b3[0] = (byte << 2); /*** 6 bits into 1st byte ***/ - else if (i == 1) { + } else if (i == 1) { b3[0] |= ((b = byte) >> 4); /*** 2 bits into 1st byte ***/ b3[1] = ((b = byte) << 4); /*** 4 bits into 2nd byte ***/ } else if (i == 2) { b3[1] |= ((b = byte) >> 2); /*** 4 bits into 2nd byte ***/ b3[2] = ((b = byte) << 6); /*** 2 bits into 3rd byte ***/ - } else if (i == 3) + } else if (i == 3) { b3[2] |= byte; /*** 6 bits into 3rd byte ***/ + } } return; } diff --git a/Code/DataStructs/Wrap/DataStructs.cpp b/Code/DataStructs/Wrap/DataStructs.cpp index 7f55a1077..cfef4713b 100644 --- a/Code/DataStructs/Wrap/DataStructs.cpp +++ b/Code/DataStructs/Wrap/DataStructs.cpp @@ -37,7 +37,7 @@ void convertToNumpyArray(const T &v, python::object destArray) { if (!PyArray_Check(destArray.ptr())) { throw_value_error("Expecting a Numeric array object"); } - PyArrayObject *destP = (PyArrayObject *)destArray.ptr(); + auto *destP = (PyArrayObject *)destArray.ptr(); npy_intp ndims[1]; ndims[0] = v.size(); PyArray_Dims dims; diff --git a/Code/DataStructs/Wrap/wrap_FPB.cpp b/Code/DataStructs/Wrap/wrap_FPB.cpp index 4331881ac..82e67c67d 100644 --- a/Code/DataStructs/Wrap/wrap_FPB.cpp +++ b/Code/DataStructs/Wrap/wrap_FPB.cpp @@ -19,8 +19,7 @@ using namespace RDKit; namespace { python::tuple taniNbrHelper(const FPBReader *self, const std::string &bytes, double threshold) { - const std::uint8_t *bv = - reinterpret_cast(bytes.c_str()); + const auto *bv = reinterpret_cast(bytes.c_str()); std::vector> nbrs = self->getTanimotoNeighbors(bv, threshold); python::list result; @@ -31,8 +30,7 @@ python::tuple taniNbrHelper(const FPBReader *self, const std::string &bytes, } python::tuple tverskyNbrHelper(const FPBReader *self, const std::string &bytes, double ca, double cb, double threshold) { - const std::uint8_t *bv = - reinterpret_cast(bytes.c_str()); + const auto *bv = reinterpret_cast(bytes.c_str()); std::vector> nbrs = self->getTverskyNeighbors(bv, ca, cb, threshold); python::list result; @@ -43,8 +41,7 @@ python::tuple tverskyNbrHelper(const FPBReader *self, const std::string &bytes, } python::tuple containingNbrHelper(const FPBReader *self, const std::string &bytes) { - const std::uint8_t *bv = - reinterpret_cast(bytes.c_str()); + const auto *bv = reinterpret_cast(bytes.c_str()); std::vector nbrs = self->getContainingNeighbors(bv); python::list result; for (auto &nbr : nbrs) { @@ -56,8 +53,7 @@ python::tuple containingNbrHelper(const FPBReader *self, python::tuple multiTaniNbrHelper(const MultiFPBReader *self, const std::string &bytes, double threshold, unsigned int numThreads) { - const std::uint8_t *bv = - reinterpret_cast(bytes.c_str()); + const auto *bv = reinterpret_cast(bytes.c_str()); std::vector nbrs = self->getTanimotoNeighbors(bv, threshold, numThreads); python::list result; @@ -70,8 +66,7 @@ python::tuple multiTverskyNbrHelper(const MultiFPBReader *self, const std::string &bytes, double ca, double cb, double threshold, unsigned int numThreads) { - const std::uint8_t *bv = - reinterpret_cast(bytes.c_str()); + const auto *bv = reinterpret_cast(bytes.c_str()); std::vector nbrs = self->getTverskyNeighbors(bv, ca, cb, threshold, numThreads); python::list result; @@ -83,8 +78,7 @@ python::tuple multiTverskyNbrHelper(const MultiFPBReader *self, python::tuple multiContainingNbrHelper(const MultiFPBReader *self, const std::string &bytes, unsigned int numThreads) { - const std::uint8_t *bv = - reinterpret_cast(bytes.c_str()); + const auto *bv = reinterpret_cast(bytes.c_str()); std::vector> nbrs = self->getContainingNeighbors(bv, numThreads); python::list result; @@ -104,8 +98,7 @@ python::object getBytesHelper(const FPBReader *self, unsigned int which) { double getTaniHelper(const FPBReader *self, unsigned int which, const std::string &bytes) { - const std::uint8_t *bv = - reinterpret_cast(bytes.c_str()); + const auto *bv = reinterpret_cast(bytes.c_str()); return self->getTanimoto(which, bv); } python::tuple getItemHelper(const FPBReader *self, unsigned int which) { @@ -114,8 +107,7 @@ python::tuple getItemHelper(const FPBReader *self, unsigned int which) { } double getTverskyHelper(const FPBReader *self, unsigned int which, const std::string &bytes, double ca, double cb) { - const std::uint8_t *bv = - reinterpret_cast(bytes.c_str()); + const auto *bv = reinterpret_cast(bytes.c_str()); return self->getTversky(which, bv, ca, cb); } } diff --git a/Code/DataStructs/base64.cpp b/Code/DataStructs/base64.cpp index cd2cd4660..118aa897e 100644 --- a/Code/DataStructs/base64.cpp +++ b/Code/DataStructs/base64.cpp @@ -50,7 +50,9 @@ char *Base64Encode(const unsigned char *inText, const unsigned int inLen) { char *res; int resSize; resSize = (4 * inLen) / 3; - while (resSize % 4) resSize++; + while (resSize % 4) { + resSize++; + } res = new char[resSize + 1]; unsigned int i = 0; int pos = 0; @@ -91,9 +93,15 @@ char *Base64Decode(const char *inText, unsigned int *size) { for (i = 0; i < 255; i++) { transTable[i] = 0x80; } - for (i = 'A'; i <= 'Z'; i++) transTable[i] = (unsigned char)i - 'A'; - for (i = 'a'; i <= 'z'; i++) transTable[i] = (unsigned char)i - 'a' + 26; - for (i = '0'; i <= '9'; i++) transTable[i] = (unsigned char)i - '0' + 52; + for (i = 'A'; i <= 'Z'; i++) { + transTable[i] = (unsigned char)i - 'A'; + } + for (i = 'a'; i <= 'z'; i++) { + transTable[i] = (unsigned char)i - 'a' + 26; + } + for (i = '0'; i <= '9'; i++) { + transTable[i] = (unsigned char)i - '0' + 52; + } transTable[static_cast('+')] = 62; transTable[static_cast('/')] = 63; diff --git a/Code/DataStructs/testDatastructs.cpp b/Code/DataStructs/testDatastructs.cpp index 5e79365cf..d693ca845 100644 --- a/Code/DataStructs/testDatastructs.cpp +++ b/Code/DataStructs/testDatastructs.cpp @@ -185,7 +185,9 @@ void ProbeTest(T &arg) { T t1(sz), t2(sz); for (int i = 0; i < sz; i += 2) { t1.setBit(i); - if (i < 3 * sz / 4) t2.setBit(i); + if (i < 3 * sz / 4) { + t2.setBit(i); + } } std::string pkl = t1.toString(); TEST_ASSERT(AllProbeBitsMatch(t1, pkl)); diff --git a/Code/DistGeom/DistGeomUtils.cpp b/Code/DistGeom/DistGeomUtils.cpp index 1014260c6..59ee3a4b0 100644 --- a/Code/DistGeom/DistGeomUtils.cpp +++ b/Code/DistGeom/DistGeomUtils.cpp @@ -258,10 +258,11 @@ ForceFields::ForceField *construct3DForceField( int j = etkdgDetails.expTorsionAtoms[t][1]; int k = etkdgDetails.expTorsionAtoms[t][2]; int l = etkdgDetails.expTorsionAtoms[t][3]; - if (i < j) + if (i < j) { atomPairs[i * N + j] = 1; - else + } else { atomPairs[j * N + i] = 1; + } // etkdgDetails.expTorsionAngles[t][0] = (signs, V's) auto *contrib = new ForceFields::CrystalFF::TorsionAngleContribM6( field, i, j, k, l, etkdgDetails.expTorsionAngles[t].second, @@ -307,10 +308,11 @@ ForceFields::ForceField *construct3DForceField( for (const auto &bnd : etkdgDetails.bonds) { unsigned int i = bnd.first; unsigned int j = bnd.second; - if (i < j) + if (i < j) { atomPairs[i * N + j] = 1; - else + } else { atomPairs[j * N + i] = 1; + } double d = ((*positions[i]) - (*positions[j])).length(); double l = d - 0.01; double u = d + 0.01; @@ -324,10 +326,11 @@ ForceFields::ForceField *construct3DForceField( unsigned int i = angle[0]; unsigned int j = angle[1]; unsigned int k = angle[2]; - if (i < j) + if (i < j) { atomPairs[i * N + j] = 1; - else + } else { atomPairs[j * N + i] = 1; + } // check for triple bonds if (angle[3]) { auto *contrib = new ForceFields::UFF::AngleConstraintContrib( @@ -382,10 +385,11 @@ ForceFields::ForceField *constructPlain3DForceField( int j = etkdgDetails.expTorsionAtoms[t][1]; int k = etkdgDetails.expTorsionAtoms[t][2]; int l = etkdgDetails.expTorsionAtoms[t][3]; - if (i < j) + if (i < j) { atomPairs[i * N + j] = 1; - else + } else { atomPairs[j * N + i] = 1; + } // etkdgDetails.expTorsionAngles[t][0] = (signs, V's) auto *contrib = new ForceFields::CrystalFF::TorsionAngleContribM6( field, i, j, k, l, etkdgDetails.expTorsionAngles[t].second, @@ -398,10 +402,11 @@ ForceFields::ForceField *constructPlain3DForceField( for (const auto &bnd : etkdgDetails.bonds) { unsigned int i = bnd.first; unsigned int j = bnd.second; - if (i < j) + if (i < j) { atomPairs[i * N + j] = 1; - else + } else { atomPairs[j * N + i] = 1; + } double d = ((*positions[i]) - (*positions[j])).length(); double l = d - 0.01; double u = d + 0.01; @@ -414,10 +419,11 @@ ForceFields::ForceField *constructPlain3DForceField( for (unsigned int a = 1; a < etkdgDetails.angles.size(); ++a) { unsigned int i = etkdgDetails.angles[a][0]; unsigned int j = etkdgDetails.angles[a][2]; - if (i < j) + if (i < j) { atomPairs[i * N + j] = 1; - else + } else { atomPairs[j * N + i] = 1; + } double d = ((*positions[i]) - (*positions[j])).length(); double l = d - 0.01; double u = d + 0.01; diff --git a/Code/DistGeom/Wrap/DistGeom.cpp b/Code/DistGeom/Wrap/DistGeom.cpp index e39ed97e2..57cba0b2b 100644 --- a/Code/DistGeom/Wrap/DistGeom.cpp +++ b/Code/DistGeom/Wrap/DistGeom.cpp @@ -35,21 +35,27 @@ namespace python = boost::python; namespace RDKit { bool doTriangleSmoothing(python::object boundsMatArg, double tol) { PyObject *boundsMatObj = boundsMatArg.ptr(); - if (!PyArray_Check(boundsMatObj)) + if (!PyArray_Check(boundsMatObj)) { throw_value_error("Argument isn't an array"); + } - PyArrayObject *boundsMat = reinterpret_cast(boundsMatObj); + auto *boundsMat = reinterpret_cast(boundsMatObj); // get the dimensions of the array int nrows = PyArray_DIM(boundsMat, 0); int ncols = PyArray_DIM(boundsMat, 1); - if (nrows != ncols) throw_value_error("The array has to be square"); - if (nrows <= 0) throw_value_error("The array has to have a nonzero size"); - if (PyArray_DESCR(boundsMat)->type_num != NPY_DOUBLE) + if (nrows != ncols) { + throw_value_error("The array has to be square"); + } + if (nrows <= 0) { + throw_value_error("The array has to have a nonzero size"); + } + if (PyArray_DESCR(boundsMat)->type_num != NPY_DOUBLE) { throw_value_error("Only double arrays are currently supported"); + } unsigned int dSize = nrows * nrows; auto *cData = new double[dSize]; - double *inData = reinterpret_cast(PyArray_DATA(boundsMat)); + auto *inData = reinterpret_cast(PyArray_DATA(boundsMat)); memcpy(static_cast(cData), static_cast(inData), dSize * sizeof(double)); DistGeom::BoundsMatrix::DATA_SPTR sdata(cData); @@ -67,21 +73,27 @@ PyObject *embedBoundsMatrix(python::object boundsMatArg, int maxIters = 10, python::list weights = python::list(), int randomSeed = -1) { PyObject *boundsMatObj = boundsMatArg.ptr(); - if (!PyArray_Check(boundsMatObj)) + if (!PyArray_Check(boundsMatObj)) { throw_value_error("Argument isn't an array"); + } - PyArrayObject *boundsMat = reinterpret_cast(boundsMatObj); + auto *boundsMat = reinterpret_cast(boundsMatObj); // get the dimensions of the array unsigned int nrows = PyArray_DIM(boundsMat, 0); unsigned int ncols = PyArray_DIM(boundsMat, 1); - if (nrows != ncols) throw_value_error("The array has to be square"); - if (nrows <= 0) throw_value_error("The array has to have a nonzero size"); - if (PyArray_DESCR(boundsMat)->type_num != NPY_DOUBLE) + if (nrows != ncols) { + throw_value_error("The array has to be square"); + } + if (nrows <= 0) { + throw_value_error("The array has to have a nonzero size"); + } + if (PyArray_DESCR(boundsMat)->type_num != NPY_DOUBLE) { throw_value_error("Only double arrays are currently supported"); + } unsigned int dSize = nrows * nrows; auto *cData = new double[dSize]; - double *inData = reinterpret_cast(PyArray_DATA(boundsMat)); + auto *inData = reinterpret_cast(PyArray_DATA(boundsMat)); memcpy(static_cast(cData), static_cast(inData), dSize * sizeof(double)); @@ -108,7 +120,9 @@ PyObject *embedBoundsMatrix(python::object boundsMatArg, int maxIters = 10, distMat, posPtrs, randomizeOnFailure, numZeroFail, randomSeed); // update the seed: - if (randomSeed >= 0) randomSeed += iter * 999; + if (randomSeed >= 0) { + randomSeed += iter * 999; + } } if (gotCoords) { @@ -145,8 +159,8 @@ PyObject *embedBoundsMatrix(python::object boundsMatArg, int maxIters = 10, npy_intp dims[2]; dims[0] = nrows; dims[1] = 3; - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); - double *resData = reinterpret_cast(PyArray_DATA(res)); + auto *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); + auto *resData = reinterpret_cast(PyArray_DATA(res)); for (unsigned int i = 0; i < nrows; i++) { unsigned int iTab = i * 3; for (unsigned int j = 0; j < 3; ++j) { diff --git a/Code/ForceField/ForceField.cpp b/Code/ForceField/ForceField.cpp index ca6b195f8..2e36ad895 100644 --- a/Code/ForceField/ForceField.cpp +++ b/Code/ForceField/ForceField.cpp @@ -18,11 +18,13 @@ namespace RDKit { namespace ForceFieldsHelper { void normalizeAngleDeg(double &angleDeg) { double normFactor = 360.0; - if (angleDeg < 0.0) + if (angleDeg < 0.0) { normFactor = -normFactor; + } angleDeg = fmod(angleDeg, normFactor); - if (fabs(angleDeg) > 180.0) + if (fabs(angleDeg) > 180.0) { angleDeg -= normFactor; + } } void computeDihedral(const RDGeom::PointPtrVect &pos, unsigned int idx1, @@ -61,12 +63,15 @@ void computeDihedral(const RDGeom::Point3D *p1, const RDGeom::Point3D *p2, RDGeom::Point3D rLocal[4]; RDGeom::Point3D tLocal[2]; double dLocal[2]; - if (!r) + if (!r) { r = rLocal; - if (!t) + } + if (!t) { t = tLocal; - if (!d) + } + if (!d) { d = dLocal; + } r[0] = *p1 - *p2; r[1] = *p3 - *p2; r[2] = -r[1]; @@ -79,8 +84,9 @@ void computeDihedral(const RDGeom::Point3D *p1, const RDGeom::Point3D *p2, d[1] = (std::max)(t[1].length(), 1.0e-5); t[1] /= d[1]; double cosPhiLocal; - if (!cosPhi) + if (!cosPhi) { cosPhi = &cosPhiLocal; + } *cosPhi = (std::max)(-1.0, (std::min)(t[0].dotProduct(t[1]), 1.0)); // we want a signed dihedral, that's why we use atan2 instead of acos if (dihedral) { @@ -123,7 +129,9 @@ class calcGradient { for (unsigned int i = 0; i < mp_ffHolder->numPoints() * mp_ffHolder->dimension(); i++) { grad[i] *= gradScale; - if (grad[i] > maxGrad) maxGrad = grad[i]; + if (grad[i] > maxGrad) { + maxGrad = grad[i]; + } } // this is a continuation of the same hack to avoid // some potential numeric instabilities: @@ -269,7 +277,9 @@ int ForceField::minimize(unsigned int snapshotFreq, PRECONDITION(df_init, "not initialized"); PRECONDITION(static_cast(d_numPoints) == d_positions.size(), "size mismatch"); - if (d_contribs.empty()) return 0; + if (d_contribs.empty()) { + return 0; + } unsigned int numIters = 0; unsigned int dim = this->d_numPoints * d_dimension; @@ -292,7 +302,9 @@ int ForceField::minimize(unsigned int snapshotFreq, double ForceField::calcEnergy(std::vector *contribs) const { PRECONDITION(df_init, "not initialized"); double res = 0.0; - if (d_contribs.empty()) return res; + if (d_contribs.empty()) { + return res; + } if (contribs) { contribs->clear(); contribs->reserve(d_contribs.size()); @@ -319,7 +331,9 @@ double ForceField::calcEnergy(double *pos) { double res = 0.0; this->initDistanceMatrix(); - if (d_contribs.empty()) return res; + if (d_contribs.empty()) { + return res; + } // now loop over the contribs for (ContribPtrVect::const_iterator contrib = d_contribs.begin(); @@ -333,7 +347,9 @@ double ForceField::calcEnergy(double *pos) { void ForceField::calcGrad(double *grad) const { PRECONDITION(df_init, "not initialized"); PRECONDITION(grad, "bad gradient vector"); - if (d_contribs.empty()) return; + if (d_contribs.empty()) { + return; + } unsigned int N = d_positions.size(); auto *pos = new double[d_dimension * N]; @@ -356,7 +372,9 @@ void ForceField::calcGrad(double *pos, double *grad) { PRECONDITION(df_init, "not initialized"); PRECONDITION(pos, "bad position vector"); PRECONDITION(grad, "bad gradient vector"); - if (d_contribs.empty()) return; + if (d_contribs.empty()) { + return; + } for (ContribPtrVect::const_iterator contrib = d_contribs.begin(); contrib != d_contribs.end(); contrib++) { diff --git a/Code/ForceField/MMFF/AngleConstraint.cpp b/Code/ForceField/MMFF/AngleConstraint.cpp index f5c6184c3..1bd4db0fc 100644 --- a/Code/ForceField/MMFF/AngleConstraint.cpp +++ b/Code/ForceField/MMFF/AngleConstraint.cpp @@ -22,8 +22,12 @@ namespace MMFF { void _pretreatAngles(double &minAngleDeg, double &maxAngleDeg) { minAngleDeg = fmod(minAngleDeg, 360.0); maxAngleDeg = fmod(maxAngleDeg, 360.0); - if (minAngleDeg > 180.0) minAngleDeg -= 360.0; - if (maxAngleDeg > 180.0) maxAngleDeg -= 360.0; + if (minAngleDeg > 180.0) { + minAngleDeg -= 360.0; + } + if (maxAngleDeg > 180.0) { + maxAngleDeg -= 360.0; + } if ((minAngleDeg < 0.0) && (!(maxAngleDeg < 0.0))) { maxAngleDeg = std::max(fabs(maxAngleDeg), fabs(minAngleDeg)); minAngleDeg = 0.0; diff --git a/Code/ForceField/MMFF/Params.cpp b/Code/ForceField/MMFF/Params.cpp index a9ed50258..1b16a0d77 100644 --- a/Code/ForceField/MMFF/Params.cpp +++ b/Code/ForceField/MMFF/Params.cpp @@ -4879,11 +4879,11 @@ MMFFDfsbCollection::MMFFDfsbCollection(std::string mmffDfsb) { tokenizer tokens(inLine, tabSep); tokenizer::iterator token = tokens.begin(); - unsigned int iAtomicNum = boost::lexical_cast(*token); + auto iAtomicNum = boost::lexical_cast(*token); ++token; - unsigned int jAtomicNum = boost::lexical_cast(*token); + auto jAtomicNum = boost::lexical_cast(*token); ++token; - unsigned int kAtomicNum = boost::lexical_cast(*token); + auto kAtomicNum = boost::lexical_cast(*token); ++token; mmffStbnObj.kbaIJK = boost::lexical_cast(*token); ++token; diff --git a/Code/ForceField/MMFF/TorsionAngle.cpp b/Code/ForceField/MMFF/TorsionAngle.cpp index 669cfc931..31f1ca8a1 100644 --- a/Code/ForceField/MMFF/TorsionAngle.cpp +++ b/Code/ForceField/MMFF/TorsionAngle.cpp @@ -145,7 +145,7 @@ void TorsionAngleContrib::getGrad(double *pos, double *grad) const { double d[2]; double cosPhi; RDKit::ForceFieldsHelper::computeDihedral( - pos, d_at1Idx, d_at2Idx, d_at3Idx, d_at4Idx, NULL, &cosPhi, r, t, d); + pos, d_at1Idx, d_at2Idx, d_at3Idx, d_at4Idx, nullptr, &cosPhi, r, t, d); double sinPhiSq = 1.0 - cosPhi * cosPhi; double sinPhi = ((sinPhiSq > 0.0) ? sqrt(sinPhiSq) : 0.0); double sin2Phi = 2.0 * sinPhi * cosPhi; diff --git a/Code/ForceField/MMFF/testMMFFForceField.cpp b/Code/ForceField/MMFF/testMMFFForceField.cpp index 5c7290719..714ef62a4 100644 --- a/Code/ForceField/MMFF/testMMFFForceField.cpp +++ b/Code/ForceField/MMFF/testMMFFForceField.cpp @@ -1673,8 +1673,8 @@ M END ForceFields::ForceField *field = RDKit::MMFF::constructForceField(*mol, &mmffMolProperties); TEST_ASSERT(field); field->initialize(); - ForceFields::MMFF::TorsionConstraintContrib *tc = - new ForceFields::MMFF::TorsionConstraintContrib(field, 0, 3, 6, 9, d, d, 1.0e6); + auto *tc = new ForceFields::MMFF::TorsionConstraintContrib(field, 0, 3, 6, + 9, d, d, 1.0e6); field->contribs().push_back(ForceFields::ContribPtr(tc)); field->minimize(); e.push_back(field->calcEnergy()); diff --git a/Code/ForceField/UFF/AngleConstraint.cpp b/Code/ForceField/UFF/AngleConstraint.cpp index e58424e8c..37111b8aa 100644 --- a/Code/ForceField/UFF/AngleConstraint.cpp +++ b/Code/ForceField/UFF/AngleConstraint.cpp @@ -22,8 +22,12 @@ namespace UFF { void _pretreatAngles(double &minAngleDeg, double &maxAngleDeg) { minAngleDeg = fmod(minAngleDeg, 360.0); maxAngleDeg = fmod(maxAngleDeg, 360.0); - if (minAngleDeg > 180.0) minAngleDeg -= 360.0; - if (maxAngleDeg > 180.0) maxAngleDeg -= 360.0; + if (minAngleDeg > 180.0) { + minAngleDeg -= 360.0; + } + if (maxAngleDeg > 180.0) { + maxAngleDeg -= 360.0; + } if ((minAngleDeg < 0.0) && (!(maxAngleDeg < 0.0))) { maxAngleDeg = std::max(fabs(maxAngleDeg), fabs(minAngleDeg)); minAngleDeg = 0.0; diff --git a/Code/ForceField/UFF/Nonbonded.cpp b/Code/ForceField/UFF/Nonbonded.cpp index 6768bca5a..e1fabf55d 100644 --- a/Code/ForceField/UFF/Nonbonded.cpp +++ b/Code/ForceField/UFF/Nonbonded.cpp @@ -56,7 +56,9 @@ double vdWContrib::getEnergy(double *pos) const { PRECONDITION(pos, "bad vector"); double dist = dp_forceField->distance(d_at1Idx, d_at2Idx, pos); - if (dist > d_thresh || dist <= 0.0) return 0.0; + if (dist > d_thresh || dist <= 0.0) { + return 0.0; + } double r = d_xij / dist; double r6 = int_pow<6>(r); @@ -72,7 +74,9 @@ void vdWContrib::getGrad(double *pos, double *grad) const { PRECONDITION(grad, "bad vector"); double dist = dp_forceField->distance(d_at1Idx, d_at2Idx, pos); - if (dist > d_thresh) return; + if (dist > d_thresh) { + return; + } if (dist <= 0) { for (int i = 0; i < 3; i++) { diff --git a/Code/ForceField/UFF/Params.cpp b/Code/ForceField/UFF/Params.cpp index f465d0aa5..89bd24457 100644 --- a/Code/ForceField/UFF/Params.cpp +++ b/Code/ForceField/UFF/Params.cpp @@ -38,7 +38,9 @@ ParamCollection *ParamCollection::getParams(const std::string ¶mData) { } ParamCollection::ParamCollection(std::string paramData) { - if (paramData.empty()) paramData = defaultParamData; + if (paramData.empty()) { + paramData = defaultParamData; + } std::istringstream inStream(paramData); std::string inLine = RDKit::getLine(inStream); diff --git a/Code/ForceField/UFF/TorsionAngle.cpp b/Code/ForceField/UFF/TorsionAngle.cpp index 500549b3a..85eec6496 100644 --- a/Code/ForceField/UFF/TorsionAngle.cpp +++ b/Code/ForceField/UFF/TorsionAngle.cpp @@ -130,8 +130,12 @@ void TorsionAngleContrib::calcTorsionParams(double bondOrder23, int atNum2, if (bondOrder23 == 1.0 && Utils::isInGroup6(atNum2) && Utils::isInGroup6(atNum3)) { double V2 = 6.8, V3 = 6.8; - if (atNum2 == 8) V2 = 2.0; - if (atNum3 == 8) V3 = 2.0; + if (atNum2 == 8) { + V2 = 2.0; + } + if (atNum3 == 8) { + V3 = 2.0; + } d_forceConstant = sqrt(V2 * V3); d_order = 2; d_cosTerm = -1; // phi0=90 @@ -223,7 +227,7 @@ void TorsionAngleContrib::getGrad(double *pos, double *grad) const { double d[2]; double cosPhi; RDKit::ForceFieldsHelper::computeDihedral( - pos, d_at1Idx, d_at2Idx, d_at3Idx, d_at4Idx, NULL, &cosPhi, r, t, d); + pos, d_at1Idx, d_at2Idx, d_at3Idx, d_at4Idx, nullptr, &cosPhi, r, t, d); double sinPhiSq = 1.0 - cosPhi * cosPhi; double sinPhi = ((sinPhiSq > 0.0) ? sqrt(sinPhiSq) : 0.0); diff --git a/Code/ForceField/Wrap/ForceField.cpp b/Code/ForceField/Wrap/ForceField.cpp index a58c76010..dfec7190c 100644 --- a/Code/ForceField/Wrap/ForceField.cpp +++ b/Code/ForceField/Wrap/ForceField.cpp @@ -128,15 +128,17 @@ double PyForceField::calcEnergyWithPos(const python::object &pos) { if (pos != python::object()) { size_t s = this->field->dimension() * this->field->numPoints(); size_t numElements = python::extract(pos.attr("__len__")()); - if (s != numElements) + if (s != numElements) { throw ValueErrorException("The Python container must have length equal to Dimension() * NumPoints()"); + } std::vector c(s); - for (size_t i = 0; i < s; ++i) + for (size_t i = 0; i < s; ++i) { c[i] = python::extract(pos[i]); + } return this->field->calcEnergy(c.data()); - } - else + } else { return this->field->calcEnergy(); + } } PyObject *PyForceField::positions() { @@ -162,15 +164,17 @@ PyObject *PyForceField::calcGradWithPos(const python::object &pos) { PyObject *gradTuple = PyTuple_New(s); if (pos != python::object()) { size_t numElements = python::extract(pos.attr("__len__")()); - if (s != numElements) + if (s != numElements) { throw ValueErrorException("The Python container must have length equal to Dimension() * NumPoints()"); + } std::vector c(s); - for (size_t i = 0; i < s; ++i) + for (size_t i = 0; i < s; ++i) { c[i] = python::extract(pos[i]); + } this->field->calcGrad(c.data(), g.data()); - } - else + } else { this->field->calcGrad(g.data()); + } for (size_t i = 0; i < s; ++i) { PyObject *coordItem = PyFloat_FromDouble(g[i]); PyTuple_SetItem(gradTuple, i, coordItem); @@ -184,8 +188,10 @@ python::tuple PyForceField::minimizeTrajectory(unsigned int snapshotFreq, int ma int resInt = this->field->minimize(snapshotFreq, &snapshotVect, maxIts, forceTol, energyTol); python::list l; - for (RDKit::SnapshotVect::const_iterator it = snapshotVect.begin(); it != snapshotVect.end(); ++it) + for (RDKit::SnapshotVect::const_iterator it = snapshotVect.begin(); + it != snapshotVect.end(); ++it) { l.append(new RDKit::Snapshot(*it)); + } return python::make_tuple(resInt, l); } diff --git a/Code/Geometry/UniformGrid3D.cpp b/Code/Geometry/UniformGrid3D.cpp index e19664506..c5f8896a1 100644 --- a/Code/Geometry/UniformGrid3D.cpp +++ b/Code/Geometry/UniformGrid3D.cpp @@ -32,7 +32,9 @@ UniformGrid3D::UniformGrid3D(const UniformGrid3D &other) : Grid3D(other) { } UniformGrid3D &UniformGrid3D::operator=(const UniformGrid3D &other) { - if (&other == this) return *this; + if (&other == this) { + return *this; + } PRECONDITION(other.dp_storage, "cannot copy an uninitialized grid"); delete dp_storage; auto *data = new RDKit::DiscreteValueVect(*other.dp_storage); @@ -168,10 +170,18 @@ void UniformGrid3D::setVal(unsigned int pointId, unsigned int val) { } bool UniformGrid3D::compareParams(const UniformGrid3D &other) const { - if (d_numX != other.getNumX()) return false; - if (d_numY != other.getNumY()) return false; - if (d_numZ != other.getNumZ()) return false; - if (fabs(d_spacing - other.getSpacing()) > SPACING_TOL) return false; + if (d_numX != other.getNumX()) { + return false; + } + if (d_numY != other.getNumY()) { + return false; + } + if (d_numZ != other.getNumZ()) { + return false; + } + if (fabs(d_spacing - other.getSpacing()) > SPACING_TOL) { + return false; + } Point3D dOffset = d_offSet; dOffset -= other.getOffset(); if (dOffset.lengthSq() > OFFSET_TOL) { @@ -423,7 +433,7 @@ void writeGridToStream(const UniformGrid3D &grid, std::ostream &outStrm) { void writeGridToFile(const UniformGrid3D &grid, const std::string &filename) { // std::ofstream ofStrm(filename.c_str()); auto *ofStrm = new std::ofstream(filename.c_str()); - std::ostream *oStrm = static_cast(ofStrm); + auto *oStrm = static_cast(ofStrm); writeGridToStream(grid, *oStrm); delete ofStrm; } diff --git a/Code/Geometry/Wrap/Point.cpp b/Code/Geometry/Wrap/Point.cpp index 42b558137..c947d07bb 100644 --- a/Code/Geometry/Wrap/Point.cpp +++ b/Code/Geometry/Wrap/Point.cpp @@ -61,16 +61,22 @@ double point3Ddist(const Point3D &pt1, const Point3D &pt2) { } double pointNdGetItem(const PointND &self, int idx) { if (idx >= static_cast(self.dimension()) || - idx < -1 * static_cast(self.dimension())) + idx < -1 * static_cast(self.dimension())) { throw IndexErrorException(idx); - if (idx < 0) idx = self.dimension() + idx; + } + if (idx < 0) { + idx = self.dimension() + idx; + } return self[idx]; } double pointNdSetItem(PointND &self, int idx, double val) { if (idx >= static_cast(self.dimension()) || - idx < -1 * static_cast(self.dimension())) + idx < -1 * static_cast(self.dimension())) { throw IndexErrorException(idx); - if (idx < 0) idx = self.dimension() + idx; + } + if (idx < 0) { + idx = self.dimension() + idx; + } self[idx] = val; return val; } diff --git a/Code/Geometry/point.cpp b/Code/Geometry/point.cpp index c2cc52783..d85f6741e 100644 --- a/Code/Geometry/point.cpp +++ b/Code/Geometry/point.cpp @@ -26,7 +26,9 @@ double computeSignedDihedralAngle(const Point3D& pt1, const Point3D& pt2, // now calculate the sign: Point3D crs3 = crs1.crossProduct(crs2); double dot = crs3.dotProduct(begEndVec); - if (dot < 0.0) ang *= -1; + if (dot < 0.0) { + ang *= -1; + } return ang; } diff --git a/Code/Geometry/testTransforms.cpp b/Code/Geometry/testTransforms.cpp index ceac8cc41..7cfa84b65 100644 --- a/Code/Geometry/testTransforms.cpp +++ b/Code/Geometry/testTransforms.cpp @@ -32,7 +32,7 @@ bool ptEq(const Point2D pt1, const Point2D pt2, double val = 1.e-8) { } double randNum(double x = 5) { - double res = (double)rand(); + auto res = (double)rand(); res /= RAND_MAX; res *= x; return res; diff --git a/Code/GraphMol/AddHs.cpp b/Code/GraphMol/AddHs.cpp index 403e00393..492abf51a 100644 --- a/Code/GraphMol/AddHs.cpp +++ b/Code/GraphMol/AddHs.cpp @@ -112,10 +112,11 @@ void setHydrogenCoords(ROMol *mol, unsigned int hydIdx, unsigned int heavyIdx) { switch (heavyAtom->getHybridization()) { case Atom::SP3: // get a perpendicular to nbr1Vect: - if ((*cfi)->is3D()) + if ((*cfi)->is3D()) { perpVect = nbr1Vect.getPerpendicular(); - else + } else { perpVect.z = 1.0; + } // and move off it: tform.SetRotation((180 - 109.471) * M_PI / 180., perpVect); dirVect = tform * nbr1Vect; @@ -165,10 +166,11 @@ void setHydrogenCoords(ROMol *mol, unsigned int hydIdx, unsigned int heavyIdx) { boost::tie(nbrIdx, endNbrs) = mol->getAtomNeighbors(heavyAtom); while (nbrIdx != endNbrs) { if (*nbrIdx != hydIdx) { - if (!nbr1) + if (!nbr1) { nbr1 = mol->getAtomWithIdx(*nbrIdx); - else + } else { nbr2 = mol->getAtomWithIdx(*nbrIdx); + } } ++nbrIdx; } @@ -355,7 +357,7 @@ void AssignHsResidueInfo(RWMol &mol) { int max_serial = 0; unsigned int stopIdx = mol.getNumAtoms(); for (unsigned int aidx = 0; aidx < stopIdx; ++aidx) { - AtomPDBResidueInfo *info = + auto *info = (AtomPDBResidueInfo *)(mol.getAtomWithIdx(aidx)->getMonomerInfo()); if (info && info->getMonomerType() == AtomMonomerInfo::PDBRESIDUE && info->getSerialNumber() > max_serial) { @@ -363,11 +365,11 @@ void AssignHsResidueInfo(RWMol &mol) { } } - AtomPDBResidueInfo *current_info = 0; + AtomPDBResidueInfo *current_info = nullptr; int current_h_id = 0; for (unsigned int aidx = 0; aidx < stopIdx; ++aidx) { Atom *newAt = mol.getAtomWithIdx(aidx); - AtomPDBResidueInfo *info = (AtomPDBResidueInfo *)(newAt->getMonomerInfo()); + auto *info = (AtomPDBResidueInfo *)(newAt->getMonomerInfo()); if (info && info->getMonomerType() == AtomMonomerInfo::PDBRESIDUE) { ROMol::ADJ_ITER begin, end; boost::tie(begin, end) = mol.getAtomNeighbors(newAt); @@ -376,11 +378,12 @@ void AssignHsResidueInfo(RWMol &mol) { // Make all Hs unique - increment id even for existing ++current_h_id; // skip if hydrogen already has PDB info - AtomPDBResidueInfo *h_info = - (AtomPDBResidueInfo *)mol.getAtomWithIdx(*begin) - ->getMonomerInfo(); - if (h_info && h_info->getMonomerType() == AtomMonomerInfo::PDBRESIDUE) + auto *h_info = (AtomPDBResidueInfo *)mol.getAtomWithIdx(*begin) + ->getMonomerInfo(); + if (h_info && + h_info->getMonomerType() == AtomMonomerInfo::PDBRESIDUE) { continue; + } // the hydrogens have unique names on residue basis (H1, H2, ...) if (!current_info || current_info->getResidueNumber() != info->getResidueNumber() || @@ -388,10 +391,13 @@ void AssignHsResidueInfo(RWMol &mol) { current_h_id = 1; current_info = info; } - std::string h_label = boost::lexical_cast(current_h_id); - if (h_label.length() > 3) + std::string h_label = std::to_string(current_h_id); + if (h_label.length() > 3) { h_label = h_label.substr(h_label.length() - 3, 3); - while (h_label.length() < 3) h_label = h_label + " "; + } + while (h_label.length() < 3) { + h_label = h_label + " "; + } h_label = "H" + h_label; // wrap around id to '3H12' h_label = h_label.substr(3, 1) + h_label.substr(0, 3); @@ -459,7 +465,9 @@ void addHs(RWMol &mol, bool explicitOnly, bool addCoords, newIdx = mol.addAtom(new Atom(1), false, true); mol.addBond(aidx, newIdx, Bond::SINGLE); mol.getAtomWithIdx(newIdx)->updatePropertyCache(); - if (addCoords) setHydrogenCoords(&mol, newIdx, aidx); + if (addCoords) { + setHydrogenCoords(&mol, newIdx, aidx); + } } // clear the local property newAt->setNumExplicitHs(0); @@ -474,7 +482,9 @@ void addHs(RWMol &mol, bool explicitOnly, bool addCoords, // off later if need be. mol.getAtomWithIdx(newIdx)->setProp(common_properties::isImplicit, 1); mol.getAtomWithIdx(newIdx)->updatePropertyCache(); - if (addCoords) setHydrogenCoords(&mol, newIdx, aidx); + if (addCoords) { + setHydrogenCoords(&mol, newIdx, aidx); + } } // be very clear about implicits not being allowed in this representation newAt->setProp(common_properties::origNoImplicit, newAt->getNoImplicit(), @@ -486,7 +496,9 @@ void addHs(RWMol &mol, bool explicitOnly, bool addCoords, newAt->updatePropertyCache(false); } // take care of AtomPDBResidueInfo for Hs if root atom has it - if (addResidueInfo) AssignHsResidueInfo(mol); + if (addResidueInfo) { + AssignHsResidueInfo(mol); + } } ROMol *addHs(const ROMol &mol, bool explicitOnly, bool addCoords, @@ -504,10 +516,14 @@ bool adjustStereoAtomsIfRequired(RWMol &mol, const Atom *atom, PRECONDITION(heavyAtom != nullptr, "bad heavy atom"); // nothing we can do if the degree is only 2 (and we should have covered // that earlier anyway) - if (heavyAtom->getDegree() == 2) return false; + if (heavyAtom->getDegree() == 2) { + return false; + } const auto &cbnd = mol.getBondBetweenAtoms(atom->getIdx(), heavyAtom->getIdx()); - if (!cbnd) return false; + if (!cbnd) { + return false; + } for (const auto &nbri : boost::make_iterator_range(mol.getAtomBonds(heavyAtom))) { Bond *bnd = mol[nbri]; @@ -523,8 +539,9 @@ bool adjustStereoAtomsIfRequired(RWMol &mol, const Atom *atom, for (const auto &nbri : boost::make_iterator_range(mol.getAtomNeighbors(heavyAtom))) { const auto &nbr = mol[nbri]; - if (nbr->getIdx() == dblNbrIdx || nbr->getIdx() == atom->getIdx()) + if (nbr->getIdx() == dblNbrIdx || nbr->getIdx() == atom->getIdx()) { continue; + } *sAtomIt = nbr->getIdx(); bool madeAdjustment = true; switch (bnd->getStereo()) { @@ -959,7 +976,7 @@ void mergeQueryHs(RWMol &mol, bool mergeUnmappedOnly) { if (atom->hasQuery()) { // std::cerr<<" q: "<getQuery()->getDescription()<getQuery()->getDescription() == "RecursiveStructure") { - RWMol *rqm = static_cast(const_cast( + auto *rqm = static_cast(const_cast( static_cast(atom->getQuery()) ->getQueryMol())); mergeQueryHs(*rqm, mergeUnmappedOnly); @@ -974,7 +991,7 @@ void mergeQueryHs(RWMol &mol, bool mergeUnmappedOnly) { // std::cerr<<" child: "<getDescription()<getDescription() == "RecursiveStructure") { // std::cerr<<" recurse"<(const_cast( + auto *rqm = static_cast(const_cast( static_cast(qry.get()) ->getQueryMol())); mergeQueryHs(*rqm, mergeUnmappedOnly); diff --git a/Code/GraphMol/AdjustQuery.cpp b/Code/GraphMol/AdjustQuery.cpp index 8a13b876f..3384c172a 100644 --- a/Code/GraphMol/AdjustQuery.cpp +++ b/Code/GraphMol/AdjustQuery.cpp @@ -187,7 +187,9 @@ void adjustQueryProperties(RWMol &mol, const AdjustQueryParameters *inParams) { qa = static_cast(at); } ATOM_EQUALS_QUERY *nq = makeAtomInRingQuery(); - if (!nRings) nq->setNegation(true); + if (!nRings) { + nq->setNegation(true); + } qa->expandQuery(nq); } // end of adjust ring chain } // end of loop over atoms diff --git a/Code/GraphMol/Aromaticity.cpp b/Code/GraphMol/Aromaticity.cpp index efe1148ad..5fc020218 100644 --- a/Code/GraphMol/Aromaticity.cpp +++ b/Code/GraphMol/Aromaticity.cpp @@ -97,10 +97,14 @@ void makeRingNeighborMap(const VECT_INT_VECT &brings, } for (i = 0; i < nrings; i++) { - if (maxSize && brings[i].size() > maxSize) continue; + if (maxSize && brings[i].size() > maxSize) { + continue; + } ring1 = brings[i]; for (j = i + 1; j < nrings; j++) { - if (maxSize && brings[j].size() > maxSize) continue; + if (maxSize && brings[j].size() > maxSize) { + continue; + } INT_VECT inter; Intersect(ring1, brings[j], inter); if (inter.size() > 0 && @@ -293,7 +297,9 @@ bool incidentMultipleBond(const Atom *at) { boost::tie(beg, end) = at->getOwningMol().getAtomBonds(at); while (beg != end) { Bond *bond = at->getOwningMol()[*beg]; - if (!std::lround(bond->getValenceContrib(at))) --deg; + if (!std::lround(bond->getValenceContrib(at))) { + --deg; + } ++beg; } return at->getExplicitValence() != static_cast(deg); @@ -302,7 +308,9 @@ bool incidentMultipleBond(const Atom *at) { bool applyHuckel(ROMol &mol, const INT_VECT &ring, const VECT_EDON_TYPE &edon, unsigned int minRingSize) { RDUNUSED_PARAM(mol); - if (ring.size() < minRingSize) return false; + if (ring.size() < minRingSize) { + return false; + } int atlw, atup, rlw, rup, rie; bool aromatic = false; rlw = 0; @@ -349,7 +357,7 @@ void applyHuckelToFused( INT_VECT aromRings; aromRings.resize(0); - unsigned int nrings = rdcast(fused.size()); + auto nrings = rdcast(fused.size()); INT_VECT curRs; INT_VECT_CI mri; curRs.push_back(fused.front()); @@ -359,7 +367,7 @@ void applyHuckelToFused( pos = -1; INT_VECT unionAtms; Union(srings, unionAtms); - unsigned int nAtms = rdcast(unionAtms.size()); + auto nAtms = rdcast(unionAtms.size()); std::set doneAtoms; while (1) { if (pos == -1) { @@ -431,9 +439,12 @@ bool isAtomCandForArom(const Atom *at, const ElectronDonorType edon, bool allowHigherExceptions = true, bool onlyCorN = false, bool allowExocyclicMultipleBonds = true) { PRECONDITION(at, "bad atom"); - if (onlyCorN && at->getAtomicNum() != 6 && at->getAtomicNum() != 7) + if (onlyCorN && at->getAtomicNum() != 6 && at->getAtomicNum() != 7) { return false; - if (!allowThirdRow && at->getAtomicNum() > 10) return false; + } + if (!allowThirdRow && at->getAtomicNum() > 10) { + return false; + } // limit aromaticity to: // - the first two rows of the periodic table @@ -489,7 +500,9 @@ bool isAtomCandForArom(const Atom *at, const ElectronDonorType edon, ++nMult; break; case Bond::TRIPLE: - if (!allowTripleBonds) return false; + if (!allowTripleBonds) { + return false; + } ++nMult; break; default: @@ -498,10 +511,14 @@ bool isAtomCandForArom(const Atom *at, const ElectronDonorType edon, // just bail... I have no good answer for them. break; } - if (nMult > 1) break; + if (nMult > 1) { + break; + } ++beg; } - if (nMult > 1) return (false); + if (nMult > 1) { + return (false); + } } if (!allowExocyclicMultipleBonds) { @@ -512,8 +529,9 @@ bool isAtomCandForArom(const Atom *at, const ElectronDonorType edon, const Bond *bnd = mol[*beg]; if ((bnd->getBondType() == Bond::DOUBLE || bnd->getBondType() == Bond::TRIPLE) && - !queryIsBondInRing(bnd)) + !queryIsBondInRing(bnd)) { return false; + } ++beg; } } @@ -680,7 +698,9 @@ int mdlAromaticityHelper(RWMol &mol, const VECT_INT_VECT &srings) { } if (aseen[firstIdx]) { - if (!acands[firstIdx]) allAromatic = false; + if (!acands[firstIdx]) { + allAromatic = false; + } continue; } aseen[firstIdx] = 1; @@ -703,7 +723,9 @@ int mdlAromaticityHelper(RWMol &mol, const VECT_INT_VECT &srings) { acands[firstIdx] = isAtomCandForArom( at, edon[firstIdx], allowThirdRow, allowTripleBonds, allowHigherExceptions, onlyCorN, allowExocyclicMultipleBonds); - if (!acands[firstIdx]) allAromatic = false; + if (!acands[firstIdx]) { + allAromatic = false; + } } if (allAromatic && !allDummy) { cRings.push_back(sring); @@ -773,8 +795,9 @@ int aromaticityHelper(RWMol &mol, const VECT_INT_VECT &srings, size_t ringSz = sring.size(); // test ring size: if ((minRingSize && ringSz < minRingSize) || - (maxRingSize && ringSz > maxRingSize)) + (maxRingSize && ringSz > maxRingSize)) { continue; + } bool allAromatic = true; bool allDummy = true; @@ -786,7 +809,9 @@ int aromaticityHelper(RWMol &mol, const VECT_INT_VECT &srings, } if (aseen[firstIdx]) { - if (!acands[firstIdx]) allAromatic = false; + if (!acands[firstIdx]) { + allAromatic = false; + } continue; } aseen[firstIdx] = 1; @@ -797,7 +822,9 @@ int aromaticityHelper(RWMol &mol, const VECT_INT_VECT &srings, // the Huckel rule later edon[firstIdx] = getAtomDonorTypeArom(at); acands[firstIdx] = isAtomCandForArom(at, edon[firstIdx]); - if (!acands[firstIdx]) allAromatic = false; + if (!acands[firstIdx]) { + allAromatic = false; + } } if (allAromatic && !allDummy) { cRings.push_back(sring); diff --git a/Code/GraphMol/Atom.cpp b/Code/GraphMol/Atom.cpp index 30cd4ecb8..28716640a 100644 --- a/Code/GraphMol/Atom.cpp +++ b/Code/GraphMol/Atom.cpp @@ -89,7 +89,9 @@ void Atom::initFromOther(const Atom &other) { Atom::Atom(const Atom &other) : RDProps() { initFromOther(other); } Atom &Atom::operator=(const Atom &other) { - if (this == &other) return *this; + if (this == &other) { + return *this; + } initFromOther(other); return *this; } @@ -166,7 +168,9 @@ unsigned int Atom::getTotalNumHs(bool includeNeighbors) const { boost::tie(begin, end) = parent->getAtomNeighbors(this); while (begin != end) { const Atom *at = parent->getAtomWithIdx(*begin); - if (at->getAtomicNum() == 1) res++; + if (at->getAtomicNum() == 1) { + res++; + } ++begin; } } @@ -174,7 +178,9 @@ unsigned int Atom::getTotalNumHs(bool includeNeighbors) const { } unsigned int Atom::getNumImplicitHs() const { - if (df_noImplicit) return 0; + if (df_noImplicit) { + return 0; + } PRECONDITION(d_implicitValence > -1, "getNumImplicitHs() called without preceding call to " @@ -215,10 +221,13 @@ int Atom::calcExplicitValence(bool strict) { // check accum is greater than the default valence unsigned int dv = PeriodicTable::getTable()->getDefaultValence(d_atomicNum); int chr = getFormalCharge(); - if (isEarlyAtom(d_atomicNum)) + if (isEarlyAtom(d_atomicNum)) { chr *= -1; // <- the usual correction for early atoms + } // special case for carbon - see GitHub #539 - if (d_atomicNum == 6 && chr > 0) chr = -chr; + if (d_atomicNum == 6 && chr > 0) { + chr = -chr; + } if (accum > (dv + chr) && this->getIsAromatic()) { // this needs some explanation : if the atom is aromatic and // accum > (dv + chr) we assume that no hydrogen can be added @@ -247,7 +256,9 @@ int Atom::calcExplicitValence(bool strict) { // the valence is 3 or the bridging N in c1ccn2cncc2c1, which starts // with a valence of 4.5, but can be happily kekulized down to a valence // of 3 - if (accum - pval <= 1.5) accum = pval; + if (accum - pval <= 1.5) { + accum = pval; + } } // despite promising to not to blame it on him - this a trick Greg // came up with: if we have a bond order sum of x.5 (i.e. 1.5, 2.5 @@ -298,7 +309,9 @@ int Atom::calcExplicitValence(bool strict) { int Atom::getImplicitValence() const { PRECONDITION(dp_mol, "valence not defined for atoms not associated with molecules"); - if (df_noImplicit) return 0; + if (df_noImplicit) { + return 0; + } return d_implicitValence; } @@ -307,8 +320,12 @@ int Atom::getImplicitValence() const { int Atom::calcImplicitValence(bool strict) { PRECONDITION(dp_mol, "valence not defined for atoms not associated with molecules"); - if (df_noImplicit) return 0; - if (d_explicitValence == -1) this->calcExplicitValence(strict); + if (df_noImplicit) { + return 0; + } + if (d_explicitValence == -1) { + this->calcExplicitValence(strict); + } // this is basically the difference between the allowed valence of // the atom and the explicit valence already specified - tells how // many Hs to add @@ -372,7 +389,9 @@ int Atom::calcImplicitValence(bool strict) { chg *= -1; } // special case for carbon - see GitHub #539 - if (d_atomicNum == 6 && chg > 0) chg = -chg; + if (d_atomicNum == 6 && chg > 0) { + chg = -chg; + } // if we have an aromatic case treat it differently if (getIsAromatic()) { @@ -443,7 +462,9 @@ double Atom::getMass() const { if (d_isotope) { double res = PeriodicTable::getTable()->getMassForIsotope(d_atomicNum, d_isotope); - if (d_atomicNum != 0 && res == 0.0) res = d_isotope; + if (d_atomicNum != 0 && res == 0.0) { + res = d_isotope; + } return res; } else { return PeriodicTable::getTable()->getAtomicWeight(d_atomicNum); diff --git a/Code/GraphMol/AtomIterators.cpp b/Code/GraphMol/AtomIterators.cpp index 611e85a81..59ea31cca 100644 --- a/Code/GraphMol/AtomIterators.cpp +++ b/Code/GraphMol/AtomIterators.cpp @@ -43,13 +43,17 @@ AtomIterator_ &AtomIterator_::operator=( template AtomIterator_ &AtomIterator_::operator+=(int val) { _pos += val; - if (_pos < 0 || _pos > _max) _pos = _max; + if (_pos < 0 || _pos > _max) { + _pos = _max; + } return *this; } template AtomIterator_ &AtomIterator_::operator-=(int val) { _pos -= val; - if (_pos < 0 || _pos > _max) _pos = _max; + if (_pos < 0 || _pos > _max) { + _pos = _max; + } return *this; } template @@ -144,10 +148,11 @@ AtomIterator_ &AtomIterator_::operator--() { template AtomIterator_ AtomIterator_::operator--(int) { AtomIterator_ res(*this); - if (_pos - 1 < 0) + if (_pos - 1 < 0) { _pos = _max; - else + } else { _pos--; + } return res; } @@ -241,10 +246,11 @@ HeteroatomIterator_ HeteroatomIterator_::operator--( template int HeteroatomIterator_::_findNext(int from) { while (from < _end) { - if (_qA->Match((*_mol)[from])) + if (_qA->Match((*_mol)[from])) { break; - else + } else { from++; + } } return from; } @@ -252,12 +258,15 @@ int HeteroatomIterator_::_findNext(int from) { template int HeteroatomIterator_::_findPrev(int from) { while (from > 0) { - if (_qA->Match((*_mol)[from])) + if (_qA->Match((*_mol)[from])) { break; - else + } else { from--; + } + } + if (from < 0) { + from = _end; } - if (from < 0) from = _end; return from; } @@ -346,10 +355,11 @@ operator--(int) { template int AromaticAtomIterator_::_findNext(int from) { while (from < _end) { - if ((*_mol)[from]->getIsAromatic()) + if ((*_mol)[from]->getIsAromatic()) { break; - else + } else { from++; + } } return from; } @@ -357,12 +367,15 @@ int AromaticAtomIterator_::_findNext(int from) { template int AromaticAtomIterator_::_findPrev(int from) { while (from > 0) { - if ((*_mol)[from]->getIsAromatic()) + if ((*_mol)[from]->getIsAromatic()) { break; - else + } else { from--; + } + } + if (from < 0) { + from = _end; } - if (from < 0) from = _end; return from; } @@ -398,10 +411,11 @@ QueryAtomIterator_::QueryAtomIterator_( _mol = other._mol; _pos = other._pos; _end = other._end; - if (other._qA) + if (other._qA) { _qA = static_cast(other._qA->copy()); - else + } else { _qA = nullptr; + } } template @@ -412,10 +426,11 @@ QueryAtomIterator_ &QueryAtomIterator_::operator=( _pos = other._pos; _end = other._end; delete _qA; - if (other._qA) + if (other._qA) { _qA = static_cast(other._qA->copy()); - else + } else { _qA = nullptr; + } } return *this; } @@ -466,10 +481,11 @@ int QueryAtomIterator_::_findNext(int from) { PRECONDITION(_mol != nullptr, "no molecule"); PRECONDITION(_qA != nullptr, "no query set"); while (from < _end) { - if (_qA->Match((*_mol)[from])) + if (_qA->Match((*_mol)[from])) { break; - else + } else { from++; + } } return from; } @@ -479,12 +495,15 @@ int QueryAtomIterator_::_findPrev(int from) { PRECONDITION(_mol != nullptr, "no molecule"); PRECONDITION(_qA != nullptr, "no query set"); while (from > 0) { - if (_qA->Match((*_mol)[from])) + if (_qA->Match((*_mol)[from])) { break; - else + } else { from--; + } + } + if (from < 0) { + from = _end; } - if (from < 0) from = _end; return from; } @@ -582,10 +601,11 @@ int MatchingAtomIterator_::_findNext(int from) { PRECONDITION(_mol != nullptr, "no molecule"); PRECONDITION(_qF != nullptr, "no query set"); while (from < _end) { - if (_qF((*_mol)[from])) + if (_qF((*_mol)[from])) { break; - else + } else { ++from; + } } return from; } @@ -595,12 +615,15 @@ int MatchingAtomIterator_::_findPrev(int from) { PRECONDITION(_mol != nullptr, "no molecule"); PRECONDITION(_qF != nullptr, "no query set"); while (from > 0) { - if (_qF((*_mol)[from])) + if (_qF((*_mol)[from])) { break; - else + } else { --from; + } + } + if (from < 0) { + from = _end; } - if (from < 0) from = _end; return from; } diff --git a/Code/GraphMol/Bond.cpp b/Code/GraphMol/Bond.cpp index 0e8fec7f0..20e777357 100644 --- a/Code/GraphMol/Bond.cpp +++ b/Code/GraphMol/Bond.cpp @@ -42,7 +42,9 @@ Bond::Bond(const Bond &other) : RDProps(other) { Bond::~Bond() { delete dp_stereoAtoms; } Bond &Bond::operator=(const Bond &other) { - if (this == &other) return *this; + if (this == &other) { + return *this; + } dp_mol = other.dp_mol; d_bondType = other.d_bondType; d_beginAtomIdx = other.d_beginAtomIdx; @@ -75,21 +77,26 @@ void Bond::setOwningMol(ROMol *other) { unsigned int Bond::getOtherAtomIdx(const unsigned int thisIdx) const { PRECONDITION(d_beginAtomIdx == thisIdx || d_endAtomIdx == thisIdx, "bad index"); - if (d_beginAtomIdx == thisIdx) + if (d_beginAtomIdx == thisIdx) { return d_endAtomIdx; - else if (d_endAtomIdx == thisIdx) + } else if (d_endAtomIdx == thisIdx) { return d_beginAtomIdx; + } // we cannot actually get down here return 0; } void Bond::setBeginAtomIdx(unsigned int what) { - if (dp_mol) URANGE_CHECK(what, getOwningMol().getNumAtoms()); + if (dp_mol) { + URANGE_CHECK(what, getOwningMol().getNumAtoms()); + } d_beginAtomIdx = what; }; void Bond::setEndAtomIdx(unsigned int what) { - if (dp_mol) URANGE_CHECK(what, getOwningMol().getNumAtoms()); + if (dp_mol) { + URANGE_CHECK(what, getOwningMol().getNumAtoms()); + } d_endAtomIdx = what; }; @@ -214,16 +221,18 @@ double Bond::getValenceContrib(const Atom *atom) const { return 1.5; break; case DATIVEONE: - if (atom->getIdx() == getEndAtomIdx()) + if (atom->getIdx() == getEndAtomIdx()) { return 1.0; - else + } else { return 0.0; + } break; case DATIVE: - if (atom->getIdx() == getEndAtomIdx()) + if (atom->getIdx() == getEndAtomIdx()) { return 1.0; - else + } else { return 0.0; + } break; default: UNDER_CONSTRUCTION("Bad bond type"); @@ -297,7 +306,9 @@ std::ostream &operator<<(std::ostream &target, const RDKit::Bond &bond) { target << bond.getIdx() << " "; target << bond.getBeginAtomIdx() << "->" << bond.getEndAtomIdx(); target << " order: " << bond.getBondType(); - if (bond.getBondDir()) target << " dir: " << bond.getBondDir(); + if (bond.getBondDir()) { + target << " dir: " << bond.getBondDir(); + } if (bond.getStereo()) { target << " stereo: " << bond.getStereo(); if (bond.getStereoAtoms().size() == 2) { diff --git a/Code/GraphMol/BondIterators.cpp b/Code/GraphMol/BondIterators.cpp index d43bf69bb..86934c494 100644 --- a/Code/GraphMol/BondIterators.cpp +++ b/Code/GraphMol/BondIterators.cpp @@ -60,18 +60,20 @@ BondIterator_ BondIterator_::operator++(int) { } // pre-decrement BondIterator_ &BondIterator_::operator--() { - if (_pos == _beg) + if (_pos == _beg) { _pos = _end; - else + } else { _pos--; + } return *this; } BondIterator_ BondIterator_::operator--(int) { BondIterator_ res(*this); - if (_pos == _beg) + if (_pos == _beg) { _pos = _end; - else + } else { _pos--; + } return res; } @@ -125,18 +127,20 @@ ConstBondIterator_ ConstBondIterator_::operator++(int) { } // pre-decrement ConstBondIterator_ &ConstBondIterator_::operator--() { - if (_pos == _beg) + if (_pos == _beg) { _pos = _end; - else + } else { _pos--; + } return *this; } ConstBondIterator_ ConstBondIterator_::operator--(int) { ConstBondIterator_ res(*this); - if (_pos == _beg) + if (_pos == _beg) { _pos = _end; - else + } else { _pos--; + } return res; } } diff --git a/Code/GraphMol/Canon.cpp b/Code/GraphMol/Canon.cpp index 62d97896f..e205a8be7 100644 --- a/Code/GraphMol/Canon.cpp +++ b/Code/GraphMol/Canon.cpp @@ -25,7 +25,9 @@ bool isUnsaturated(const Atom *atom, const ROMol &mol) { while (beg != end) { const Bond *bond = mol[*beg]; ++beg; - if (bond->getBondType() != Bond::SINGLE) return true; + if (bond->getBondType() != Bond::SINGLE) { + return true; + } } return false; } @@ -46,7 +48,9 @@ bool hasSingleHQuery(const Atom::QUERYATOM_QUERY *q) { return false; } else if (descr == "AtomAnd") { res = hasSingleHQuery((*cIt).get()); - if (res) return true; + if (res) { + return true; + } } } } @@ -188,7 +192,9 @@ void canonicalizeDoubleBond(Bond *dblBond, INT_VECT &bondVisitOrders, dir1Set = true; } if (!firstFromAtom1 || bondVisitOrders[bondIdx] < firstVisitOrder) { - if (firstFromAtom1) secondFromAtom1 = firstFromAtom1; + if (firstFromAtom1) { + secondFromAtom1 = firstFromAtom1; + } firstFromAtom1 = mol[*atomBonds.first]; firstVisitOrder = bondVisitOrders[bondIdx]; } else { @@ -206,7 +212,9 @@ void canonicalizeDoubleBond(Bond *dblBond, INT_VECT &bondVisitOrders, dir2Set = true; } if (!firstFromAtom2 || bondVisitOrders[bondIdx] < firstVisitOrder) { - if (firstFromAtom2) secondFromAtom2 = firstFromAtom2; + if (firstFromAtom2) { + secondFromAtom2 = firstFromAtom2; + } firstFromAtom2 = mol[*atomBonds.first]; firstVisitOrder = bondVisitOrders[bondIdx]; } else { @@ -579,7 +587,9 @@ void dfsFindCycles(ROMol &mol, int atomIdx, int inBondIdx, while (bondsPair.first != bondsPair.second) { Bond *theBond = mol[*(bondsPair.first)]; bondsPair.first++; - if (bondsInPlay && !(*bondsInPlay)[theBond->getIdx()]) continue; + if (bondsInPlay && !(*bondsInPlay)[theBond->getIdx()]) { + continue; + } if (inBondIdx < 0 || theBond->getIdx() != static_cast(inBondIdx)) { int otherIdx = theBond->getOtherAtomIdx(atomIdx); @@ -706,7 +716,9 @@ void dfsBuildStack(ROMol &mol, int atomIdx, int inBondIdx, colors[atomIdx] = GREY_NODE; INT_LIST travList; - if (inBondIdx >= 0) travList.push_back(inBondIdx); + if (inBondIdx >= 0) { + travList.push_back(inBondIdx); + } // --------------------- // @@ -767,7 +779,9 @@ void dfsBuildStack(ROMol &mol, int atomIdx, int inBondIdx, while (bondsPair.first != bondsPair.second) { Bond *theBond = mol[*(bondsPair.first)]; bondsPair.first++; - if (bondsInPlay && !(*bondsInPlay)[theBond->getIdx()]) continue; + if (bondsInPlay && !(*bondsInPlay)[theBond->getIdx()]) { + continue; + } if (inBondIdx < 0 || theBond->getIdx() != static_cast(inBondIdx)) { int otherIdx = theBond->getOtherAtomIdx(atomIdx); @@ -1041,7 +1055,9 @@ void canonicalizeFragment(ROMol &mol, int atomIdx, INT_VECT cyclesAvailable(MAX_CYCLES, 1); VECT_INT_VECT cycles(nAtoms); - for (auto &cycle : cycles) cycle.resize(0); + for (auto &cycle : cycles) { + cycle.resize(0); + } boost::dynamic_bitset<> ringStereoChemAdjusted(nAtoms); diff --git a/Code/GraphMol/ChemReactions/Enumerate/Enumerate.cpp b/Code/GraphMol/ChemReactions/Enumerate/Enumerate.cpp index 7ecf1ae22..13d14c5c4 100644 --- a/Code/GraphMol/ChemReactions/Enumerate/Enumerate.cpp +++ b/Code/GraphMol/ChemReactions/Enumerate/Enumerate.cpp @@ -94,7 +94,9 @@ std::vector> EnumerateLibraryBase::nextSmiles() { for (size_t i = 0; i < mols.size(); ++i) { result[i].resize(mols[i].size()); for (size_t j = 0; j < mols[i].size(); ++j) { - if (mols[i][j].get()) result[i][j] = MolToSmiles(*mols[i][j], doisomeric); + if (mols[i][j].get()) { + result[i][j] = MolToSmiles(*mols[i][j], doisomeric); + } } } return result; @@ -146,7 +148,7 @@ BBS removeNonmatchingReagents(const ChemicalReaction &rxn, BBS bbs, int saneProducts = 0; for (auto &product_idx : partialProduct) { try { - RWMol *m = dynamic_cast(product_idx.get()); + auto *m = dynamic_cast(product_idx.get()); MolOps::sanitizeMol(*m); saneProducts++; } catch (...) { @@ -161,10 +163,11 @@ BBS removeNonmatchingReagents(const ChemicalReaction &rxn, BBS bbs, } } - if (removeReagent) + if (removeReagent) { removedCount++; - else + } else { result[reactant_idx].push_back(mol); + } } if (removedCount) { @@ -235,10 +238,11 @@ boost::uint64_t computeNumProducts(const RGROUPS &sizes) { myint *= size; } - if (myint < std::numeric_limits::max()) + if (myint < std::numeric_limits::max()) { return myint.convert_to(); - else + } else { return EnumerationStrategyBase::EnumerationOverflow; + } #else boost::uint64_t myint = 1; diff --git a/Code/GraphMol/ChemReactions/Enumerate/EnumerationPickler.cpp b/Code/GraphMol/ChemReactions/Enumerate/EnumerationPickler.cpp index b7c526bd6..28ecd9132 100644 --- a/Code/GraphMol/ChemReactions/Enumerate/EnumerationPickler.cpp +++ b/Code/GraphMol/ChemReactions/Enumerate/EnumerationPickler.cpp @@ -47,10 +47,15 @@ namespace RDKit { std::string GetClass(const EnumerationStrategyBase *en) { - if (dynamic_cast(en)) return "-->cartesian"; - if (dynamic_cast(en)) return "-->random"; - if (dynamic_cast(en)) + if (dynamic_cast(en)) { + return "-->cartesian"; + } + if (dynamic_cast(en)) { + return "-->random"; + } + if (dynamic_cast(en)) { return "-->randombbs"; + } return "Unknown!"; } diff --git a/Code/GraphMol/ChemReactions/Enumerate/EvenSamplePairs.cpp b/Code/GraphMol/ChemReactions/Enumerate/EvenSamplePairs.cpp index 85bff6a15..9a8efb7e9 100644 --- a/Code/GraphMol/ChemReactions/Enumerate/EvenSamplePairs.cpp +++ b/Code/GraphMol/ChemReactions/Enumerate/EvenSamplePairs.cpp @@ -73,8 +73,9 @@ void EvenSamplePairsStrategy::initializeStrategy(const ChemicalReaction &, /* Initialize random number generator */ /* Find modulus */ - for (M = 1; M < rdcast(m_numPermutations); M = 2 * M) + for (M = 1; M < rdcast(m_numPermutations); M = 2 * M) { ; + } /* Set factor */ a = 5; b = 7; @@ -105,7 +106,9 @@ bool EvenSamplePairsStrategy::try_add(boost::uint64_t iseed) { boost::uint64_t num_rgroups = m_permutationSizes.size(); for (boost::uint64_t i = 0; i < num_rgroups; ++i) { - if (var_used[i][digits[i]]) islack += var_used[i][digits[i]]; + if (var_used[i][digits[i]]) { + islack += var_used[i][digits[i]]; + } if (islack > nslack) { // add better heuristic here?? rejected_slack_condition += 1; @@ -119,11 +122,13 @@ bool EvenSamplePairsStrategy::try_add(boost::uint64_t iseed) { for (boost::uint64_t i = 0; i < num_rgroups; ++i) { boost::uint64_t joffset = 0; for (boost::uint64_t j = 0; j < num_rgroups; ++j) { - if (j == i) continue; + if (j == i) { + continue; + } boost::uint64_t ii = digits[i] + ioffset; boost::uint64_t jj = digits[j] + joffset; if (pair_used[ii][jj] > 0) { - double numer = (double)pair_used[ii][jj]; + auto numer = (double)pair_used[ii][jj]; double denom = sqrt((double)(rgroups[i]) * (double)(rgroups[j])); islack = (int)(numer / denom); } @@ -145,13 +150,16 @@ bool EvenSamplePairsStrategy::try_add(boost::uint64_t iseed) { var_used[i][digits[i]] += 1; if (used_count[i] == rdcast(rgroups[i])) { // complete variable scan => initialize - if (nslack > min_nslack && rgroups[i] > 1) // cleared slack on i + if (nslack > min_nslack && rgroups[i] > 1) { // cleared slack on i nslack = min_nslack; + } used_count[i] = 0; for (boost::uint64_t j = 0; j < rgroups[i]; ++j) { var_used[i][j]--; - if (var_used[i][j] > 0) used_count[i]++; + if (var_used[i][j] > 0) { + used_count[i]++; + } } } // end scan } @@ -226,43 +234,67 @@ std::string EvenSamplePairsStrategy::stats() const { ss << "#BEGIN# BBSTAT\n"; for (i = 0; i < npos; i++) { boost::uint64_t maxcount = 0; - if (nvars[i] == 1) continue; - for (j = 0; j < nvars[i]; j++) - if (maxcount < var_used[i][j]) maxcount = var_used[i][j]; - + if (nvars[i] == 1) { + continue; + } + for (j = 0; j < nvars[i]; j++) { + if (maxcount < var_used[i][j]) { + maxcount = var_used[i][j]; + } + } ss << boost::format("%lu\t%lu\t%6.2f") % (i + 1) % nvars[i] % ((double)m_numPermutationsProcessed / nvars[i]); for (l = 0; l <= maxcount; l++) { boost::uint64_t n = 0; - for (j = 0; j < nvars[i]; j++) - if (var_used[i][j] == l) n++; - if (n > 0) ss << boost::format("\t%lu|%lu") % l % n; + for (j = 0; j < nvars[i]; j++) { + if (var_used[i][j] == l) { + n++; + } + if (n > 0) { + ss << boost::format("\t%lu|%lu") % l % n; + } + } + ss << std::endl; } - ss << std::endl; } ss << "#END# BBSTAT\n"; ss << "#BEGIN# PAIRSTAT\n"; for (i = 0, ioffset = 0; i < npos; ioffset += nvars[i], i++) { - if (nvars[i] == 1) continue; + if (nvars[i] == 1) { + continue; + } for (j = 0, joffset = 0; j < npos; joffset += nvars[j], j++) { boost::uint64_t maxcount = 0; - if (nvars[j] == 1) continue; - if (j <= i) continue; - for (ii = 0; ii < nvars[i]; ii++) - for (jj = 0; jj < nvars[j]; jj++) - if (maxcount < pair_used[ii + ioffset][jj + joffset]) + if (nvars[j] == 1) { + continue; + } + if (j <= i) { + continue; + } + for (ii = 0; ii < nvars[i]; ii++) { + for (jj = 0; jj < nvars[j]; jj++) { + if (maxcount < pair_used[ii + ioffset][jj + joffset]) { maxcount = pair_used[ii + ioffset][jj + joffset]; + } + } + } ss << boost::format("%lu\t%lu\t%lu\t%lu\t%6.2f") % (i + 1) % (j + 1) % nvars[i] % nvars[j] % ((double)m_numPermutationsProcessed / (nvars[i] * nvars[j])); for (l = 0; l <= maxcount; l++) { int n = 0; - for (ii = 0; ii < nvars[i]; ii++) - for (jj = 0; jj < nvars[j]; jj++) - if (l == pair_used[ii + ioffset][jj + joffset]) n++; - if (n > 0) ss << boost::format("\t%ld|%d") % l % n; + for (ii = 0; ii < nvars[i]; ii++) { + for (jj = 0; jj < nvars[j]; jj++) { + if (l == pair_used[ii + ioffset][jj + joffset]) { + n++; + } + } + } + if (n > 0) { + ss << boost::format("\t%ld|%d") % l % n; + } } ss << boost::format("\n"); } diff --git a/Code/GraphMol/ChemReactions/Enumerate/testEnumerate.cpp b/Code/GraphMol/ChemReactions/Enumerate/testEnumerate.cpp index f12b68cbe..bfa3d1904 100644 --- a/Code/GraphMol/ChemReactions/Enumerate/testEnumerate.cpp +++ b/Code/GraphMol/ChemReactions/Enumerate/testEnumerate.cpp @@ -85,15 +85,18 @@ void pickleTest(EnumerationStrategyBase &en, size_t len) { void testSamplers() { EnumerationTypes::BBS bbs; bbs.resize(3); - for (int i = 0; i < 10; ++i) + for (int i = 0; i < 10; ++i) { bbs[0].push_back(boost::shared_ptr(SmilesToMol("C=CCN=C=S"))); + } - for (int i = 0; i < 5; ++i) + for (int i = 0; i < 5; ++i) { bbs[1].push_back(boost::shared_ptr(SmilesToMol("NCc1ncc(Cl)cc1Br"))); + } - for (int i = 0; i < 6; ++i) + for (int i = 0; i < 6; ++i) { bbs[2].push_back( boost::shared_ptr(SmilesToMol("NCCCc1ncc(Cl)cc1Br"))); + } ChemicalReaction rxn; CartesianProductStrategy cart; @@ -130,15 +133,18 @@ void testEvenSamplers() { boost::uint64_t R1 = 6000; boost::uint64_t R2 = 500; boost::uint64_t R3 = 10000; - for (unsigned long i = 0; i < R1; ++i) + for (unsigned long i = 0; i < R1; ++i) { bbs[0].push_back(boost::shared_ptr(SmilesToMol("C=CCN=C=S"))); + } - for (unsigned long i = 0; i < R2; ++i) + for (unsigned long i = 0; i < R2; ++i) { bbs[1].push_back(boost::shared_ptr(SmilesToMol("NCc1ncc(Cl)cc1Br"))); + } - for (unsigned long i = 0; i < R3; ++i) + for (unsigned long i = 0; i < R3; ++i) { bbs[2].push_back( boost::shared_ptr(SmilesToMol("NCCCc1ncc(Cl)cc1Br"))); + } ChemicalReaction rxn; EvenSamplePairsStrategy even; diff --git a/Code/GraphMol/ChemReactions/MDLParser.cpp b/Code/GraphMol/ChemReactions/MDLParser.cpp index 88c7c4de4..a6d300630 100644 --- a/Code/GraphMol/ChemReactions/MDLParser.cpp +++ b/Code/GraphMol/ChemReactions/MDLParser.cpp @@ -185,10 +185,8 @@ void ParseV3000RxnBlock(std::istream &inStream, unsigned int &line, if (tokens.size() < 3 || tokens[0] != "COUNTS") { throw ChemicalReactionParserException("bad counts line"); } - unsigned int nReacts = - FileParserUtils::stripSpacesAndCast(tokens[1]); - unsigned int nProds = - FileParserUtils::stripSpacesAndCast(tokens[2]); + auto nReacts = FileParserUtils::stripSpacesAndCast(tokens[1]); + auto nProds = FileParserUtils::stripSpacesAndCast(tokens[2]); unsigned int nAgents = 0; if (tokens.size() > 3) { nAgents = FileParserUtils::stripSpacesAndCast(tokens[3]); @@ -324,7 +322,9 @@ ChemicalReaction *RxnDataStreamToChemicalReaction(std::istream &inStream, throw ChemicalReactionParserException("$RXN header not found"); } int version = 2000; - if (tempStr.size() >= 10 && tempStr.substr(5, 5) == "V3000") version = 3000; + if (tempStr.size() >= 10 && tempStr.substr(5, 5) == "V3000") { + version = 3000; + } ChemicalReaction *res = nullptr; try { diff --git a/Code/GraphMol/ChemReactions/Reaction.cpp b/Code/GraphMol/ChemReactions/Reaction.cpp index 2bf36e87d..19f977db1 100644 --- a/Code/GraphMol/ChemReactions/Reaction.cpp +++ b/Code/GraphMol/ChemReactions/Reaction.cpp @@ -136,14 +136,18 @@ bool ChemicalReaction::validate(unsigned int &numWarnings, // misleading warnings for (ROMol::AtomIterator atomIt = (*molIter)->beginAtoms(); atomIt != (*molIter)->endAtoms(); ++atomIt) { - if ((*atomIt)->hasProp(common_properties::_QueryFormalCharge)) + if ((*atomIt)->hasProp(common_properties::_QueryFormalCharge)) { (*atomIt)->clearProp(common_properties::_QueryFormalCharge); - if ((*atomIt)->hasProp(common_properties::_QueryHCount)) + } + if ((*atomIt)->hasProp(common_properties::_QueryHCount)) { (*atomIt)->clearProp(common_properties::_QueryHCount); - if ((*atomIt)->hasProp(common_properties::_QueryMass)) + } + if ((*atomIt)->hasProp(common_properties::_QueryMass)) { (*atomIt)->clearProp(common_properties::_QueryMass); - if ((*atomIt)->hasProp(common_properties::_QueryIsotope)) + } + if ((*atomIt)->hasProp(common_properties::_QueryIsotope)) { (*atomIt)->clearProp(common_properties::_QueryIsotope); + } } bool thisMolMapped = false; for (ROMol::AtomIterator atomIt = (*molIter)->beginAtoms(); diff --git a/Code/GraphMol/ChemReactions/ReactionPickler.cpp b/Code/GraphMol/ChemReactions/ReactionPickler.cpp index 93464400c..de859b770 100644 --- a/Code/GraphMol/ChemReactions/ReactionPickler.cpp +++ b/Code/GraphMol/ChemReactions/ReactionPickler.cpp @@ -130,8 +130,12 @@ void ReactionPickler::_pickle(const ChemicalReaction *rxn, std::ostream &ss, streamWrite(ss, tmpInt); uint32_t flag = 0; - if (rxn->getImplicitPropertiesFlag()) flag |= 0x1; - if (rxn->df_needsInit) flag |= 0x2; + if (rxn->getImplicitPropertiesFlag()) { + flag |= 0x1; + } + if (rxn->df_needsInit) { + flag |= 0x2; + } streamWrite(ss, flag); // ------------------- @@ -173,7 +177,9 @@ void ReactionPickler::_pickle(const ChemicalReaction *rxn, std::ostream &ss, void ReactionPickler::_pickleProperties(std::ostream &ss, const RDProps &props, unsigned int pickleFlags) { - if (!pickleFlags) return; + if (!pickleFlags) { + return; + } streamWriteProps(ss, props, pickleFlags & PicklerOps::PrivateProps, pickleFlags & PicklerOps::ComputedProps); diff --git a/Code/GraphMol/ChemReactions/ReactionRunner.cpp b/Code/GraphMol/ChemReactions/ReactionRunner.cpp index 862352b7c..92f3050cd 100644 --- a/Code/GraphMol/ChemReactions/ReactionRunner.cpp +++ b/Code/GraphMol/ChemReactions/ReactionRunner.cpp @@ -384,7 +384,9 @@ RWMOL_SPTR convertTemplateToMol(const ROMOL_SPTR prodTemplateSptr) { // ignore it: int iFlag; if (oAtom->getPropIfPresent(common_properties::molInversionFlag, iFlag)) { - if (iFlag == 4) newAtom->setChiralTag(oAtom->getChiralTag()); + if (iFlag == 4) { + newAtom->setChiralTag(oAtom->getChiralTag()); + } } // check for properties we need to set: @@ -481,7 +483,9 @@ ReactantProductAtomMapping *getAtomMappingsReactantProduct( // don't care about that int a1mapidx = bond->getBeginAtom()->getAtomMapNum(); int a2mapidx = bond->getEndAtom()->getAtomMapNum(); - if (a1mapidx > a2mapidx) std::swap(a1mapidx, a2mapidx); + if (a1mapidx > a2mapidx) { + std::swap(a1mapidx, a2mapidx); + } mapping->reactantTemplateAtomBonds[std::make_pair(a1mapidx, a2mapidx)] = 1; ++firstB; @@ -860,7 +864,9 @@ void setReactantAtomPropertiesToProduct(Atom *productAtom, productAtom->setProp(WAS_DUMMY, true); } else { // remove bookkeeping labels (if present) - if (productAtom->hasProp(WAS_DUMMY)) productAtom->clearProp(WAS_DUMMY); + if (productAtom->hasProp(WAS_DUMMY)) { + productAtom->clearProp(WAS_DUMMY); + } } productAtom->setProp(common_properties::reactantAtomIdx, reactantAtom.getIdx()); @@ -1013,7 +1019,9 @@ void addReactantNeighborsToProduct( int a2mapidx = product->getAtomWithIdx(prodEndIdx) ->getProp(common_properties::reactionMapNum); - if (a1mapidx > a2mapidx) std::swap(a1mapidx, a2mapidx); + if (a1mapidx > a2mapidx) { + std::swap(a1mapidx, a2mapidx); + } if (mapping->reactantTemplateAtomBonds.find( std::make_pair(a1mapidx, a2mapidx)) == mapping->reactantTemplateAtomBonds.end()) { @@ -1081,7 +1089,9 @@ void checkAndCorrectChiralityOfMatchingAtomsInProduct( ++nUnknown; // if there's more than one bond in the product that doesn't correspond // to anything in the reactant, we're also doomed - if (nUnknown > 1) break; + if (nUnknown > 1) { + break; + } // otherwise, add a -1 to the bond order that we'll fill in later pOrder.push_back(-1); } else { @@ -1360,7 +1370,9 @@ generateOneProductSet(const ChemicalReaction &rxn, break; } } - if (doConfs && doBondDirs) break; + if (doConfs && doBondDirs) { + break; + } } MOL_SPTR_VECT res; @@ -1476,10 +1488,11 @@ std::vector run_Reactant(const ChemicalReaction &rxn, // assemble the reactants (use an empty mol for missing reactants) MOL_SPTR_VECT reactants(rxn.getNumReactantTemplates()); for (size_t i = 0; i < rxn.getNumReactantTemplates(); ++i) { - if (i == reactantIdx) + if (i == reactantIdx) { reactants[i] = reactant; - else + } else { reactants[i] = ROMOL_SPTR(new ROMol); + } } if (!ReactionRunnerUtils::getReactantMatches( @@ -1512,7 +1525,9 @@ int getAtomMapNo(ROMol::ATOM_BOOKMARK_MAP *map, Atom *atom) { for (ROMol::ATOM_BOOKMARK_MAP::const_iterator it = map->begin(); it != map->end(); ++it) { for (auto ait = it->second.begin(); ait != it->second.end(); ++ait) { - if (*ait == atom) return it->first; + if (*ait == atom) { + return it->first; + } } } } diff --git a/Code/GraphMol/ChemReactions/SanitizeRxn.cpp b/Code/GraphMol/ChemReactions/SanitizeRxn.cpp index c00ac5978..00a7b67b1 100644 --- a/Code/GraphMol/ChemReactions/SanitizeRxn.cpp +++ b/Code/GraphMol/ChemReactions/SanitizeRxn.cpp @@ -47,7 +47,9 @@ T getMaxProp(ChemicalReaction &rxn, const std::string &prop) { for (auto atom : (*it)->atoms()) { T map; if (atom->getPropIfPresent(prop, map)) { - if (map > max_atom) max_atom = map; + if (map > max_atom) { + max_atom = map; + } } } } @@ -57,7 +59,9 @@ T getMaxProp(ChemicalReaction &rxn, const std::string &prop) { for (auto atom : (*it)->atoms()) { T map; if (atom->getPropIfPresent(prop, map)) { - if (map > max_atom) max_atom = map; + if (map > max_atom) { + max_atom = map; + } } } } @@ -67,7 +71,9 @@ T getMaxProp(ChemicalReaction &rxn, const std::string &prop) { for (auto atom : (*it)->atoms()) { T map; if (atom->getPropIfPresent(prop, map)) { - if (map > max_atom) max_atom = map; + if (map > max_atom) { + max_atom = map; + } } } } @@ -102,9 +108,15 @@ struct AtomInfo { bool NeedsRLabel() { return atom->getAtomicNum() == 0 && rlabel == 0; } unsigned int bestGuessRLabel() { - if (rlabel) return rlabel; - if (isotope) return isotope; - if (atomMap) return atomMap; + if (rlabel) { + return rlabel; + } + if (isotope) { + return isotope; + } + if (atomMap) { + return atomMap; + } if (dummyLabel.size()) { try { return boost::lexical_cast( @@ -118,7 +130,7 @@ struct AtomInfo { void setRLabel(unsigned int rlabel) { PRECONDITION(atom, "Internal error in SanitizeRxn - null atom"); - RWMol &mol = dynamic_cast(atom->getOwningMol()); + auto &mol = dynamic_cast(atom->getOwningMol()); QueryAtom qatom(*atom); qatom.setProp(common_properties::_MolFileRLabel, rlabel); @@ -167,7 +179,9 @@ void fixRGroups(ChemicalReaction &rxn) { ++it, ++templateIdx) { for (auto atom : (*it)->atoms()) { AtomInfo at(atom, templateIdx); - if (at.NeedsRLabel()) reactantAtomsToFix.push_back(at); + if (at.NeedsRLabel()) { + reactantAtomsToFix.push_back(at); + } } } @@ -176,11 +190,15 @@ void fixRGroups(ChemicalReaction &rxn) { ++it, ++templateIdx) { for (auto atom : (*it)->atoms()) { AtomInfo at(atom, templateIdx); - if (at.NeedsRLabel()) productAtomsToFix.push_back(at); + if (at.NeedsRLabel()) { + productAtomsToFix.push_back(at); + } } } - if (!reactantAtomsToFix.size() && !productAtomsToFix.size()) return; + if (!reactantAtomsToFix.size() && !productAtomsToFix.size()) { + return; + } if (reactantAtomsToFix.size() > productAtomsToFix.size()) { std::ostringstream str; @@ -190,7 +208,7 @@ void fixRGroups(ChemicalReaction &rxn) { BOOST_LOG(rdWarningLog) << str.str() << std::endl; } - unsigned int max_rlabel = + auto max_rlabel = getMaxProp(rxn, common_properties::_MolFileRLabel); int max_atom_map = getMaxProp(rxn, common_properties::molAtomMapNumber); @@ -202,7 +220,9 @@ void fixRGroups(ChemicalReaction &rxn) { } BOOST_FOREACH (AtomInfo &pat, productAtomsToFix) { - if (!pat.atom) continue; + if (!pat.atom) { + continue; + } if (rat.bestGuessRLabel() == pat.bestGuessRLabel()) { // if the atomMaps don't match, this is bad, no atomMap is ok(==0) @@ -252,7 +272,9 @@ void fixAtomMaps(ChemicalReaction &rxn) { } } - if (!potential_mappings.size()) return; // everything is ok! + if (!potential_mappings.size()) { + return; // everything is ok! + } templateIdx = 0; for (auto it = rxn.beginProductTemplates(); it != rxn.endProductTemplates(); @@ -278,10 +300,10 @@ void fixReactantTemplateAromaticity(ChemicalReaction &rxn) { unsigned int ops; for (auto it = rxn.beginReactantTemplates(); it != rxn.endReactantTemplates(); ++it) { - RWMol *rw = dynamic_cast(it->get()); - if (rw) + auto *rw = dynamic_cast(it->get()); + if (rw) { sanitizeMol(*rw, ops, MolOps::SANITIZE_SETAROMATICITY); - else + } else PRECONDITION(rw, "Oops, not really a RWMol?"); } } @@ -336,7 +358,7 @@ void fixHs(ChemicalReaction &rxn) { const bool mergeUnmappedOnly = true; for (auto it = rxn.beginReactantTemplates(); it != rxn.endReactantTemplates(); ++it) { - RWMol *rw = dynamic_cast(it->get()); + auto *rw = dynamic_cast(it->get()); if (rw) { MolOps::mergeQueryHs(*rw, mergeUnmappedOnly); } else @@ -348,10 +370,10 @@ void adjustTemplates(ChemicalReaction &rxn, const MolOps::AdjustQueryParameters ¶ms) { for (auto it = rxn.beginReactantTemplates(); it != rxn.endReactantTemplates(); ++it) { - RWMol *rw = dynamic_cast(it->get()); - if (rw) + auto *rw = dynamic_cast(it->get()); + if (rw) { adjustQueryProperties(*rw, ¶ms); - else + } else PRECONDITION(rw, "Oops, not really a RWMol?"); } } diff --git a/Code/GraphMol/ChemReactions/Wrap/Enumerate.cpp b/Code/GraphMol/ChemReactions/Wrap/Enumerate.cpp index 37460da59..ce5131541 100644 --- a/Code/GraphMol/ChemReactions/Wrap/Enumerate.cpp +++ b/Code/GraphMol/ChemReactions/Wrap/Enumerate.cpp @@ -53,9 +53,9 @@ std::vector ConvertToVect(T bbs) { reacts.reserve(len1); for(unsigned int j=0;j(bbs[i][j]); - if(mol) + if (mol) { reacts.push_back(mol); - else { + } else { throw_value_error("reaction called with non molecule reactant"); } } diff --git a/Code/GraphMol/ChemReactions/Wrap/rdChemReactions.cpp b/Code/GraphMol/ChemReactions/Wrap/rdChemReactions.cpp index aec31a1d4..b6cac5d1d 100644 --- a/Code/GraphMol/ChemReactions/Wrap/rdChemReactions.cpp +++ b/Code/GraphMol/ChemReactions/Wrap/rdChemReactions.cpp @@ -100,7 +100,9 @@ PyObject *RunReactants(ChemicalReaction *self, T reactants, reacts.resize(len1); for (unsigned int i = 0; i < len1; ++i) { reacts[i] = python::extract(reactants[i]); - if (!reacts[i]) throw_value_error("reaction called with None reactants"); + if (!reacts[i]) { + throw_value_error("reaction called with None reactants"); + } } std::vector mols; { @@ -160,7 +162,7 @@ ROMol *GetProductTemplate(const ChemicalReaction *self, unsigned int which) { } auto iter = self->beginProductTemplates(); iter += which; - ROMol *res = const_cast(iter->get()); + auto *res = const_cast(iter->get()); return res; } ROMol *GetReactantTemplate(const ChemicalReaction *self, unsigned int which) { @@ -169,7 +171,7 @@ ROMol *GetReactantTemplate(const ChemicalReaction *self, unsigned int which) { } auto iter = self->beginReactantTemplates(); iter += which; - ROMol *res = const_cast(iter->get()); + auto *res = const_cast(iter->get()); return res; } ROMol *GetAgentTemplate(const ChemicalReaction *self, unsigned int which) { @@ -178,7 +180,7 @@ ROMol *GetAgentTemplate(const ChemicalReaction *self, unsigned int which) { } auto iter = self->beginAgentTemplates(); iter += which; - ROMol *res = const_cast(iter->get()); + auto *res = const_cast(iter->get()); return res; } @@ -388,7 +390,9 @@ RxnOps::SanitizeRxnFlags sanitizeReaction( try { RxnOps::sanitizeRxn(rxn, operationsThatFailed, sanitizeOps, params); } catch (...) { - if (!catchErrors) throw; + if (!catchErrors) { + throw; + } } return static_cast(operationsThatFailed); } @@ -454,7 +458,7 @@ Sample Usage: boost::python::type_id(); const boost::python::converter::registration *reg = boost::python::converter::registry::query(info); - if (reg == NULL || (*reg).m_to_python == NULL) { + if (reg == nullptr || (*reg).m_to_python == nullptr) { python::class_("MOL_SPTR_VECT") .def(python::vector_indexing_suite()); } diff --git a/Code/GraphMol/ChemReactions/testReaction.cpp b/Code/GraphMol/ChemReactions/testReaction.cpp index d572cee8a..4b195e9d5 100644 --- a/Code/GraphMol/ChemReactions/testReaction.cpp +++ b/Code/GraphMol/ChemReactions/testReaction.cpp @@ -317,8 +317,9 @@ void test3RingFormation() { for (unsigned int i = 0; i < prods.size(); i++) { unsigned int nDifferent = 0; for (unsigned int j = 0; j < prods.size(); j++) { - if (MolToSmiles(*prods[i][0]) != MolToSmiles(*prods[j][0])) + if (MolToSmiles(*prods[i][0]) != MolToSmiles(*prods[j][0])) { nDifferent += 1; + } } TEST_ASSERT(nDifferent == 2); } @@ -701,8 +702,9 @@ void test7MDLParser() { for (unsigned int i = 0; i < prods.size(); i++) { unsigned int nDifferent = 0; for (unsigned int j = 0; j < prods.size(); j++) { - if (MolToSmiles(*prods[i][0]) != MolToSmiles(*prods[j][0])) + if (MolToSmiles(*prods[i][0]) != MolToSmiles(*prods[j][0])) { nDifferent += 1; + } } TEST_ASSERT(nDifferent == 2); } @@ -2804,8 +2806,9 @@ void test26V3000MDLParser() { for (unsigned int i = 0; i < prods.size(); i++) { unsigned int nDifferent = 0; for (unsigned int j = 0; j < prods.size(); j++) { - if (MolToSmiles(*prods[i][0]) != MolToSmiles(*prods[j][0])) + if (MolToSmiles(*prods[i][0]) != MolToSmiles(*prods[j][0])) { nDifferent += 1; + } } TEST_ASSERT(nDifferent == 2); } @@ -4191,13 +4194,17 @@ void test45SmilesWriter() { std::string res = ""; for (MOL_SPTR_VECT::const_iterator iter = rxn->beginReactantTemplates(); iter != rxn->endReactantTemplates(); ++iter) { - if (iter != rxn->beginReactantTemplates()) res += "."; + if (iter != rxn->beginReactantTemplates()) { + res += "."; + } res += MolToSmiles(**iter, true); } res += ">>"; for (MOL_SPTR_VECT::const_iterator iter = rxn->beginProductTemplates(); iter != rxn->endProductTemplates(); ++iter) { - if (iter != rxn->beginProductTemplates()) res += "."; + if (iter != rxn->beginProductTemplates()) { + res += "."; + } res += MolToSmiles(**iter, true); } @@ -4227,13 +4234,17 @@ void test45SmilesWriter() { std::string res = ""; for (MOL_SPTR_VECT::const_iterator iter = rxn->beginReactantTemplates(); iter != rxn->endReactantTemplates(); ++iter) { - if (iter != rxn->beginReactantTemplates()) res += "."; + if (iter != rxn->beginReactantTemplates()) { + res += "."; + } res += MolToSmiles(**iter, true); } res += ">>"; for (MOL_SPTR_VECT::const_iterator iter = rxn->beginProductTemplates(); iter != rxn->endProductTemplates(); ++iter) { - if (iter != rxn->beginProductTemplates()) res += "."; + if (iter != rxn->beginProductTemplates()) { + res += "."; + } res += MolToSmiles(**iter, true); } @@ -4259,13 +4270,17 @@ void test45SmilesWriter() { std::string res = ""; for (MOL_SPTR_VECT::const_iterator iter = rxn->beginReactantTemplates(); iter != rxn->endReactantTemplates(); ++iter) { - if (iter != rxn->beginReactantTemplates()) res += "."; + if (iter != rxn->beginReactantTemplates()) { + res += "."; + } res += MolToSmiles(**iter, true); } res += ">>"; for (MOL_SPTR_VECT::const_iterator iter = rxn->beginProductTemplates(); iter != rxn->endProductTemplates(); ++iter) { - if (iter != rxn->beginProductTemplates()) res += "."; + if (iter != rxn->beginProductTemplates()) { + res += "."; + } res += MolToSmiles(**iter, true); } @@ -4777,7 +4792,7 @@ void test49ParensInProducts2() { TEST_ASSERT(prods[0][0]->getNumBonds() == 11); smi = "CCCOc1ccn(NC)c1"; - RWMol *p00 = static_cast(prods[0][0].get()); + auto *p00 = static_cast(prods[0][0].get()); MolOps::sanitizeMol(*p00); TEST_ASSERT(MolToSmiles(*p00) == smi); @@ -6677,7 +6692,7 @@ void testReactionProperties() { { std::string pkl; ReactionPickler::pickleReaction(rxn, pkl); - ChemicalReaction *lrxn = new ChemicalReaction(); + auto *lrxn = new ChemicalReaction(); ReactionPickler::reactionFromPickle(pkl, lrxn); TEST_ASSERT(!lrxn->hasProp("fooprop")); delete lrxn; @@ -6686,7 +6701,7 @@ void testReactionProperties() { { std::string pkl; ReactionPickler::pickleReaction(rxn, pkl, PicklerOps::AllProps); - ChemicalReaction *lrxn = new ChemicalReaction(); + auto *lrxn = new ChemicalReaction(); ReactionPickler::reactionFromPickle(pkl, lrxn); TEST_ASSERT(lrxn->hasProp("fooprop")); TEST_ASSERT(lrxn->getProp("fooprop") == 3); diff --git a/Code/GraphMol/ChemTransforms/ChemTransforms.cpp b/Code/GraphMol/ChemTransforms/ChemTransforms.cpp index a0c81053c..b5dc5da7c 100644 --- a/Code/GraphMol/ChemTransforms/ChemTransforms.cpp +++ b/Code/GraphMol/ChemTransforms/ChemTransforms.cpp @@ -55,7 +55,7 @@ void updateSubMolConfs(const ROMol &mol, RWMol &res, ROMol *deleteSubstructs(const ROMol &mol, const ROMol &query, bool onlyFrags, bool useChirality) { - RWMol *res = new RWMol(mol, false); + auto *res = new RWMol(mol, false); std::vector fgpMatches; std::vector::const_iterator mati; VECT_INT_VECT @@ -220,7 +220,7 @@ std::vector replaceSubstructs( if (replaceAll) { // remove the atoms from the delList: std::sort(delList.begin(), delList.end()); - RWMol *newMol = static_cast(res[0].get()); + auto *newMol = static_cast(res[0].get()); for (auto dri = delList.rbegin(); dri != delList.rend(); dri++) { removedAtoms.set(*dri); newMol->removeAtom(*dri); @@ -260,7 +260,7 @@ ROMol *replaceSidechains(const ROMol &mol, const ROMol &coreQuery, } std::vector keepList; - RWMol *newMol = new RWMol(mol); + auto *newMol = new RWMol(mol); unsigned int nDummies = 0; for (MatchVectType::const_iterator mvit = matchV.begin(); mvit != matchV.end(); mvit++) { @@ -337,12 +337,14 @@ ROMol *replaceCore(const ROMol &mol, const ROMol &core, std::vector matchingIndices(origNumAtoms, -1); std::vector allIndices(origNumAtoms, -1); for (const auto &mvit : matchV) { - if (mvit.first < 0 || mvit.first >= rdcast(core.getNumAtoms())) + if (mvit.first < 0 || mvit.first >= rdcast(core.getNumAtoms())) { throw ValueErrorException( "Supplied MatchVect indices out of bounds of the core molecule"); - if (mvit.second < 0 || mvit.second >= rdcast(mol.getNumAtoms())) + } + if (mvit.second < 0 || mvit.second >= rdcast(mol.getNumAtoms())) { throw ValueErrorException( "Supplied MatchVect indices out of bounds of the target molecule"); + } if (replaceDummies || core.getAtomWithIdx(mvit.first)->getAtomicNum() > 0) { matchingIndices[mvit.second] = mvit.first; @@ -350,7 +352,7 @@ ROMol *replaceCore(const ROMol &mol, const ROMol &core, allIndices[mvit.second] = mvit.first; } - RWMol *newMol = new RWMol(mol); + auto *newMol = new RWMol(mol); std::vector keepList; std::map dummyAtomMap; @@ -366,7 +368,7 @@ ROMol *replaceCore(const ROMol &mol, const ROMol &core, std::vector> dummies; for (unsigned int j = 0; j < origNumAtoms; ++j) { - unsigned int i = (unsigned)matchorder_atomidx[j].second; + auto i = (unsigned)matchorder_atomidx[j].second; if (matchingIndices[i] == -1) { Atom *sidechainAtom = newMol->getAtomWithIdx(i); @@ -444,7 +446,9 @@ ROMol *replaceCore(const ROMol &mol, const ROMol &core, // F[C@](N)(Cl)C -> F[C@](Cl)(C)X no // F[C@](Cl)(N)C -> F[C@@](Cl)(C)X yes // F[C@](Cl)(C)N -> F[C@](Cl)(C)X no - if (!(whichNbr % 2)) switchIt = true; + if (!(whichNbr % 2)) { + switchIt = true; + } break; case 3: // things are different in the degree three case because of the @@ -454,7 +458,9 @@ ROMol *replaceCore(const ROMol &mol, const ROMol &core, // [C@H](N)(F)C -> [C@H](F)(C)X no // F[C@H](N)C -> F[C@@H](C)X yes // F[C@H](C)N -> F[C@H](C)X no - if (whichNbr == 1) switchIt = true; + if (whichNbr == 1) { + switchIt = true; + } break; } if (switchIt) { @@ -521,9 +527,11 @@ ROMol *replaceCore(const ROMol &mol, const ROMol &core, } ROMol *MurckoDecompose(const ROMol &mol) { - RWMol *res = new RWMol(mol); + auto *res = new RWMol(mol); unsigned int nAtoms = res->getNumAtoms(); - if (!nAtoms) return res; + if (!nAtoms) { + return res; + } // start by getting the shortest paths matrix: MolOps::getDistanceMat(mol, false, false, true); @@ -533,7 +541,9 @@ ROMol *MurckoDecompose(const ROMol &mol) { boost::dynamic_bitset<> keepAtoms(nAtoms); const RingInfo *ringInfo = res->getRingInfo(); for (unsigned int i = 0; i < nAtoms; ++i) { - if (ringInfo->numAtomRings(i)) keepAtoms[i] = 1; + if (ringInfo->numAtomRings(i)) { + keepAtoms[i] = 1; + } } const VECT_INT_VECT &rings = ringInfo->atomRings(); // std::cerr<<" rings: "<hasProp(propName)) continue; + if (!at->hasProp(propName)) { + continue; + } std::string pval; at->getProp(propName, pval); std::string maybeSmarts = @@ -659,7 +673,7 @@ void addRecursiveQueries( (*reactantLabels).push_back(label); } - QueryAtom::QUERYATOM_QUERY *qToAdd = 0; + QueryAtom::QUERYATOM_QUERY *qToAdd = nullptr; bool notFound = false; if (pval.find(delim) != std::string::npos) { boost::tokenizer> tokens(pval, sep); @@ -687,10 +701,12 @@ void addRecursiveQueries( if (notFound) { // See if we are actually a smarts expression already - RWMol *m = 0; + RWMol *m = nullptr; try { m = SmartsToMol(maybeSmarts); - if (!m) throw KeyErrorException(pval); + if (!m) { + throw KeyErrorException(pval); + } qToAdd = new RecursiveStructureQuery(m); } catch (...) { throw KeyErrorException(pval); @@ -721,7 +737,9 @@ void parseQueryDefFile(std::istream *inStream, while (!inStream->eof() && !inStream->fail()) { line++; tempStr = getLine(inStream); - if (tempStr == "" || tempStr.find(comment) == 0) continue; + if (tempStr == "" || tempStr.find(comment) == 0) { + continue; + } boost::tokenizer> tokens(tempStr, sep); unsigned int tpos; boost::tokenizer>::iterator token; diff --git a/Code/GraphMol/ChemTransforms/MolFragmenter.cpp b/Code/GraphMol/ChemTransforms/MolFragmenter.cpp index 2ac085774..c7c9ccf41 100644 --- a/Code/GraphMol/ChemTransforms/MolFragmenter.cpp +++ b/Code/GraphMol/ChemTransforms/MolFragmenter.cpp @@ -55,7 +55,9 @@ void constructFragmenterAtomTypes( while (!inStream->eof() && !inStream->fail()) { ++line; std::string tempStr = getLine(inStream); - if (tempStr == "" || tempStr.find(comment) == 0) continue; + if (tempStr == "" || tempStr.find(comment) == 0) { + continue; + } std::vector tokens; boost::split(tokens, tempStr, boost::is_any_of(" \t"), boost::token_compress_on); @@ -64,7 +66,7 @@ void constructFragmenterAtomTypes( << "line " << line << " is too short" << std::endl; continue; } - unsigned int idx = boost::lexical_cast(tokens[0]); + auto idx = boost::lexical_cast(tokens[0]); if (defs.find(idx) != defs.end()) { BOOST_LOG(rdWarningLog) << "definition #" << idx @@ -144,7 +146,9 @@ void constructFragmenterBondTypes( while (!inStream->eof() && !inStream->fail()) { ++line; std::string tempStr = getLine(inStream); - if (tempStr == "" || tempStr.find(comment) == 0) continue; + if (tempStr == "" || tempStr.find(comment) == 0) { + continue; + } std::vector tokens; boost::split(tokens, tempStr, boost::is_any_of(" \t"), boost::token_compress_on); @@ -153,13 +157,13 @@ void constructFragmenterBondTypes( << "line " << line << " is too short" << std::endl; continue; } - unsigned int idx1 = boost::lexical_cast(tokens[0]); + auto idx1 = boost::lexical_cast(tokens[0]); if (atomTypes.find(idx1) == atomTypes.end()) { BOOST_LOG(rdWarningLog) << "atom type #" << idx1 << " not recognized." << std::endl; continue; } - unsigned int idx2 = boost::lexical_cast(tokens[1]); + auto idx2 = boost::lexical_cast(tokens[1]); if (atomTypes.find(idx2) == atomTypes.end()) { BOOST_LOG(rdWarningLog) << "atom type #" << idx2 << " not recognized." << std::endl; @@ -311,9 +315,12 @@ void fragmentOnSomeBonds( "bad dummyLabel vector"); PRECONDITION((!bondTypes || bondTypes->size() == bondIndices.size()), "bad bondType vector"); - if (bondIndices.size() > 63) + if (bondIndices.size() > 63) { throw ValueErrorException("currently can only fragment on up to 63 bonds"); - if (!maxToCut || !mol.getNumAtoms() || !bondIndices.size()) return; + } + if (!maxToCut || !mol.getNumAtoms() || !bondIndices.size()) { + return; + } boost::uint64_t state = (0x1L << maxToCut) - 1; boost::uint64_t stop = 0x1L << bondIndices.size(); @@ -332,8 +339,12 @@ void fragmentOnSomeBonds( for (unsigned int i = 0; i < bondIndices.size() && nSeen < maxToCut; ++i) { if (state & (0x1L << i)) { fragmentHere[nSeen] = bondIndices[i]; - if (dummyLabelsHere) (*dummyLabelsHere)[nSeen] = (*dummyLabels)[i]; - if (bondTypesHere) (*bondTypesHere)[nSeen] = (*bondTypes)[i]; + if (dummyLabelsHere) { + (*dummyLabelsHere)[nSeen] = (*dummyLabels)[i]; + } + if (bondTypesHere) { + (*bondTypesHere)[nSeen] = (*bondTypes)[i]; + } ++nSeen; } } @@ -391,7 +402,9 @@ void checkChiralityPostMove(const ROMol &mol, const Atom *oAt, Atom *nAt, // std::cerr<<"ccpm: "<getIdx()<<"->"<getIdx()<<" bond: // "<getIdx()<<" swaps: "<setChiralTag(oAt->getChiralTag()); - if (nSwaps % 2) nAt->invertChirality(); + if (nSwaps % 2) { + nAt->invertChirality(); + } } } // namespace @@ -411,7 +424,9 @@ ROMol *fragmentOnBonds( BOOST_FOREACH (unsigned int &nCuts, *nCutsPerAtom) { nCuts = 0; } } auto *res = new RWMol(mol); - if (!mol.getNumAtoms()) return res; + if (!mol.getNumAtoms()) { + return res; + } std::vector bondsToRemove; bondsToRemove.reserve(bondIndices.size()); @@ -442,13 +457,16 @@ ROMol *fragmentOnBonds( at2->setIsotope(eidx); } unsigned int idx1 = res->addAtom(at1, false, true); - if (bondTypes) bT = (*bondTypes)[i]; + if (bondTypes) { + bT = (*bondTypes)[i]; + } bondidx = res->addBond(at1->getIdx(), eidx, bT) - 1; // the dummy replaces the original start atom, so the // direction will be ok as long as it's one of the // states associated with double bond stereo - if (bD == Bond::ENDDOWNRIGHT || bD == Bond::ENDUPRIGHT) + if (bD == Bond::ENDDOWNRIGHT || bD == Bond::ENDUPRIGHT) { res->getBondWithIdx(bondidx)->setBondDir(bD); + } unsigned int idx2 = res->addAtom(at2, false, true); bondidx = res->addBond(bidx, at2->getIdx(), bT) - 1; @@ -526,8 +544,9 @@ ROMol *fragmentOnBonds(const ROMol &mol, continue; } if (atomEnvirons && - (!environsMatch[fbt.atom1Type] || !environsMatch[fbt.atom2Type])) + (!environsMatch[fbt.atom1Type] || !environsMatch[fbt.atom2Type])) { continue; + } // std::cerr<<" >>> "< bondMatches; SubstructMatch(mol, *fbt.query.get(), bondMatches); diff --git a/Code/GraphMol/ChemTransforms/testChemTransforms.cpp b/Code/GraphMol/ChemTransforms/testChemTransforms.cpp index 654ba812b..3453d99dc 100644 --- a/Code/GraphMol/ChemTransforms/testChemTransforms.cpp +++ b/Code/GraphMol/ChemTransforms/testChemTransforms.cpp @@ -1071,7 +1071,9 @@ void testMurckoDecomp() { std::string smi = testMolecules[i][0]; std::string tgt = testMolecules[i][1]; ++i; - if (smi == "EOS") break; + if (smi == "EOS") { + break; + } ROMol *mol = SmilesToMol(smi); ROMol *nMol = MurckoDecompose(*mol); TEST_ASSERT(nMol); @@ -1883,13 +1885,12 @@ void testGithubIssue429() { std::vector> fragMap; BOOST_FOREACH (ROMOL_SPTR romol, frags) { - RWMol *rwmol = (RWMol *)(romol.get()); + auto *rwmol = (RWMol *)(romol.get()); MolOps::sanitizeMol(*rwmol); } // we actually changed fragmentOnBonds(), check that too: - RWMol *nmol = - (RWMol *)MolFragmenter::fragmentOnBonds(*mol, bindices, false); + auto *nmol = (RWMol *)MolFragmenter::fragmentOnBonds(*mol, bindices, false); MolOps::sanitizeMol(*nmol); delete nmol; diff --git a/Code/GraphMol/Chirality.cpp b/Code/GraphMol/Chirality.cpp index 0486be99e..92f340a19 100644 --- a/Code/GraphMol/Chirality.cpp +++ b/Code/GraphMol/Chirality.cpp @@ -95,8 +95,9 @@ Atom::ChiralType atomChiralTypeFromBondDir(const ROMol &mol, const Bond *bond, bool hSeen = false; neighborBondIndices.push_back(bond->getIdx()); - if (bondAtom->getAtomicNum() == 1 && bondAtom->getIsotope() == 0) + if (bondAtom->getAtomicNum() == 1 && bondAtom->getIsotope() == 0) { hSeen = true; + } bool allSingle = true; ROMol::OEDGE_ITER beg, end; @@ -109,8 +110,9 @@ Atom::ChiralType atomChiralTypeFromBondDir(const ROMol &mol, const Bond *bond, } if (nbrBond != bond) { if ((nbrBond->getOtherAtom(atom)->getAtomicNum() == 1 && - nbrBond->getOtherAtom(atom)->getIsotope() == 0)) + nbrBond->getOtherAtom(atom)->getIsotope() == 0)) { hSeen = true; + } neighborBondIndices.push_back(nbrBond->getIdx()); } ++beg; @@ -153,7 +155,9 @@ Atom::ChiralType atomChiralTypeFromBondDir(const ROMol &mol, const Bond *bond, tmpPt.z = 0; atomVect0 = centerLoc.directionVector(tmpPt); angle0 = refVect.signedAngleTo(atomVect0); - if (angle0 < 0) angle0 += 2. * M_PI; + if (angle0 < 0) { + angle0 += 2. * M_PI; + } ++bondIter; bond2 = mol.getBondWithIdx(*bondIter); @@ -162,7 +166,9 @@ Atom::ChiralType atomChiralTypeFromBondDir(const ROMol &mol, const Bond *bond, tmpPt.z = 0; atomVect1 = centerLoc.directionVector(tmpPt); angle1 = refVect.signedAngleTo(atomVect1); - if (angle1 < 0) angle1 += 2. * M_PI; + if (angle1 < 0) { + angle1 += 2. * M_PI; + } // We proceed differently for 3 and 4 coordinate atoms: double firstAngle, secondAngle; @@ -176,7 +182,9 @@ Atom::ChiralType atomChiralTypeFromBondDir(const ROMol &mol, const Bond *bond, tmpPt.z = 0; atomVect2 = centerLoc.directionVector(tmpPt); angle2 = refVect.signedAngleTo(atomVect2); - if (angle2 < 0) angle2 += 2. * M_PI; + if (angle2 < 0) { + angle2 += 2. * M_PI; + } // find the lowest and second-lowest angle and keep track of // whether or not we have to do a non-cyclic permutation to @@ -226,7 +234,9 @@ Atom::ChiralType atomChiralTypeFromBondDir(const ROMol &mol, const Bond *bond, // (Table 10 in the InChi v1 technical manual) angle2 = atomVect0.signedAngleTo(atomVect1); - if (angle2 < 0) angle2 += 2. * M_PI; + if (angle2 < 0) { + angle2 += 2. * M_PI; + } // this one is never allowed: // 0 2 @@ -349,11 +359,14 @@ Atom::ChiralType atomChiralTypeFromBondDir(const ROMol &mol, const Bond *bond, // // ---------------- int nSwaps = atom->getPerturbationOrder(neighborBondIndices); - if (nSwaps % 2) isCCW = !isCCW; - if (isCCW) + if (nSwaps % 2) { + isCCW = !isCCW; + } + if (isCCW) { res = Atom::CHI_TETRAHEDRAL_CCW; - else + } else { res = Atom::CHI_TETRAHEDRAL_CW; + } } return res; @@ -433,13 +446,16 @@ void buildCIPInvariants(const ROMol &mol, DOUBLE_VECT &res) { mass = atom->getIsotope() - PeriodicTable::getTable()->getMostCommonIsotope(atom->getAtomicNum()); - if (mass >= 0) mass += 1; + if (mass >= 0) { + mass += 1; + } } mass += maxMass / 2; - if (mass < 0) + if (mass < 0) { mass = 0; - else + } else { mass = mass % maxMass; + } #if 0 // NOTE: the inclusion of hybridization in the invariant (as @@ -598,7 +614,7 @@ void iterateCIPRanks(const ROMol &mol, DOUBLE_VECT &invars, UINT_VECT &ranks, // pad the entries so that we compare rounds to themselves: // for (int &index : allIndices) { - unsigned int sz = rdcast(cipEntries[index].size()); + auto sz = rdcast(cipEntries[index].size()); if (sz < longestEntry) { cipEntries[index].insert(cipEntries[index].end(), longestEntry - sz, -1); @@ -634,7 +650,9 @@ void iterateCIPRanks(const ROMol &mol, DOUBLE_VECT &invars, UINT_VECT &ranks, void assignAtomCIPRanks(const ROMol &mol, UINT_VECT &ranks) { PRECONDITION((!ranks.size() || ranks.size() >= mol.getNumAtoms()), "bad ranks size"); - if (!ranks.size()) ranks.resize(mol.getNumAtoms()); + if (!ranks.size()) { + ranks.resize(mol.getNumAtoms()); + } unsigned int numAtoms = mol.getNumAtoms(); #ifndef USE_NEW_STEREOCHEMISTRY // get the initial invariants: @@ -673,8 +691,9 @@ void findAtomNeighborDirHelper(const ROMol &mol, const Atom *atom, if (bond->getBondDir() == Bond::UNKNOWN // there's a squiggle bond || (bond->getPropIfPresent(common_properties::_UnknownStereo, explicit_unknown_stereo) && - explicit_unknown_stereo)) + explicit_unknown_stereo)) { hasExplicitUnknownStereo = true; + } } Bond::BondDir dir = bond->getBondDir(); @@ -684,10 +703,11 @@ void findAtomNeighborDirHelper(const ROMol &mol, const Atom *atom, // If we're considering the bond "backwards", (i.e. from end // to beginning, reverse the effective direction: if (atom != bond->getBeginAtom()) { - if (dir == Bond::ENDDOWNRIGHT) + if (dir == Bond::ENDDOWNRIGHT) { dir = Bond::ENDUPRIGHT; - else + } else { dir = Bond::ENDDOWNRIGHT; + } } } Atom *nbrAtom = bond->getOtherAtom(atom); @@ -801,7 +821,9 @@ bool atomIsCandidateForRingStereochem(const ROMol &mol, const Atom *atom) { } break; case 1: - if (ringNbrs.size() >= 2) res = true; + if (ringNbrs.size() >= 2) { + res = true; + } break; case 0: if (ringNbrs.size() == 4 && nbrRanks.size() == 3) { @@ -839,7 +861,9 @@ void findChiralAtomSpecialCases(ROMol &mol, for (ROMol::AtomIterator ait = mol.beginAtoms(); ait != mol.endAtoms(); ++ait) { const Atom *atom = *ait; - if (atomsSeen[atom->getIdx()]) continue; + if (atomsSeen[atom->getIdx()]) { + continue; + } if (atom->getChiralTag() == Atom::CHI_UNSPECIFIED || atom->hasProp(common_properties::_CIPCode) || !mol.getRingInfo()->numAtomRings(atom->getIdx()) || @@ -1086,17 +1110,19 @@ std::pair assignAtomChiralCodes(ROMol &mol, UINT_VECT &ranks, // if that number is odd, we'll change our chirality: if (nSwaps % 2) { - if (tag == Atom::CHI_TETRAHEDRAL_CCW) + if (tag == Atom::CHI_TETRAHEDRAL_CCW) { tag = Atom::CHI_TETRAHEDRAL_CW; - else + } else { tag = Atom::CHI_TETRAHEDRAL_CCW; + } } // now assign the CIP code: std::string cipCode; - if (tag == Atom::CHI_TETRAHEDRAL_CCW) + if (tag == Atom::CHI_TETRAHEDRAL_CCW) { cipCode = "S"; - else + } else { cipCode = "R"; + } atom->setProp(common_properties::_CIPCode, cipCode); } } @@ -1242,7 +1268,9 @@ std::pair assignBondStereoCodes(ROMol &mol, UINT_VECT &ranks) { } for (unsigned int i = 0; i < mol.getNumBonds(); ++i) { - if (bondsToClear[i]) mol.getBondWithIdx(i)->setBondDir(Bond::NONE); + if (bondsToClear[i]) { + mol.getBondWithIdx(i)->setBondDir(Bond::NONE); + } } return std::make_pair(unassignedBonds > 0, assignedABond); @@ -1253,7 +1281,9 @@ std::pair assignBondStereoCodes(ROMol &mol, UINT_VECT &ranks) { void rerankAtoms(const ROMol &mol, UINT_VECT &ranks) { PRECONDITION(ranks.size() == mol.getNumAtoms(), "bad rank vector size"); unsigned int factor = 100; - while (factor < mol.getNumAtoms()) factor *= 10; + while (factor < mol.getNumAtoms()) { + factor *= 10; + } #ifdef VERBOSE_CANON BOOST_LOG(rdDebugLog) << "rerank PRE: " << std::endl; @@ -1465,10 +1495,12 @@ void assignStereochemistry(ROMol &mol, bool cleanIt, bool force, for (ROMol::AtomIterator atIt = mol.beginAtoms(); atIt != mol.endAtoms(); ++atIt) { - if ((*atIt)->hasProp(common_properties::_ringStereochemCand)) + if ((*atIt)->hasProp(common_properties::_ringStereochemCand)) { (*atIt)->clearProp(common_properties::_ringStereochemCand); - if ((*atIt)->hasProp(common_properties::_ringStereoAtoms)) + } + if ((*atIt)->hasProp(common_properties::_ringStereoAtoms)) { (*atIt)->clearProp(common_properties::_ringStereoAtoms); + } } boost::dynamic_bitset<> possibleSpecialCases(mol.getNumAtoms()); Chirality::findChiralAtomSpecialCases(mol, possibleSpecialCases); @@ -1530,7 +1562,9 @@ void assignStereochemistry(ROMol &mol, bool cleanIt, bool force, break; } } - if (okToClear) nbrBndI->setBondDir(Bond::NONE); + if (okToClear) { + nbrBndI->setBondDir(Bond::NONE); + } } } } @@ -1733,9 +1767,13 @@ void cleanupChirality(RWMol &mol) { void assignChiralTypesFrom3D(ROMol &mol, int confId, bool replaceExistingTags) { const double ZERO_VOLUME_TOL = 0.1; - if (!mol.getNumConformers()) return; + if (!mol.getNumConformers()) { + return; + } const Conformer &conf = mol.getConformer(confId); - if (!conf.is3D()) return; + if (!conf.is3D()) { + return; + } // if the molecule already has stereochemistry // perceived, remove the flags that indicate @@ -1820,8 +1858,9 @@ void assignChiralTypesFromMolParity(ROMol &mol, bool replaceExistingTags) { for (auto atom: mol.atoms()) { // if we aren't replacing existing tags and the atom is already tagged, // punt: - if (!replaceExistingTags && atom->getChiralTag() != Atom::CHI_UNSPECIFIED) + if (!replaceExistingTags && atom->getChiralTag() != Atom::CHI_UNSPECIFIED) { continue; + } int parity = 0; atom->getPropIfPresent(common_properties::molParity, parity); if (parity <= 0 || parity > 2 || atom->getDegree() < 3) { @@ -1843,8 +1882,9 @@ void assignChiralTypesFromMolParity(ROMol &mol, bool replaceExistingTags) { < mol.getBondWithIdx(bi)->getOtherAtomIdx(atomIdx)); }); int nSwaps = atom->getPerturbationOrder(nbrBondIdxList); - if (nSwaps % 2) + if (nSwaps % 2) { parity = 1 - parity; + } atom->setChiralTag(chiralTypeVect[parity]); if (atom->getImplicitValence() == -1) { atom->calcExplicitValence(false); @@ -1900,7 +1940,9 @@ void updateDoubleBondNeighbors(ROMol &mol, Bond *dblBond, const Conformer *conf, // we want to deal only with double bonds: PRECONDITION(dblBond, "bad bond"); PRECONDITION(dblBond->getBondType() == Bond::DOUBLE, "not a double bond"); - if (!needsDir[dblBond->getIdx()]) return; + if (!needsDir[dblBond->getIdx()]) { + return; + } needsDir.set(dblBond->getIdx(), 0); #if 0 std::cerr << "**********************\n"; @@ -2140,14 +2182,18 @@ void updateDoubleBondNeighbors(ROMol &mol, Bond *dblBond, const Conformer *conf, BOOST_FOREACH (int bidx, singleBondNbrs[bond1->getIdx()]) { // std::cerr << " neighbor from: " << bond1->getIdx() << " " << bidx // << ": " << needsDir[bidx] << std::endl; - if (needsDir[bidx]) followupBonds.push_back(mol.getBondWithIdx(bidx)); + if (needsDir[bidx]) { + followupBonds.push_back(mol.getBondWithIdx(bidx)); + } } } if (needsDir[bond2->getIdx()]) { BOOST_FOREACH (int bidx, singleBondNbrs[bond2->getIdx()]) { // std::cerr << " neighbor from: " << bond2->getIdx() << " " << bidx // << ": " << needsDir[bidx] << std::endl; - if (needsDir[bidx]) followupBonds.push_back(mol.getBondWithIdx(bidx)); + if (needsDir[bidx]) { + followupBonds.push_back(mol.getBondWithIdx(bidx)); + } } } if (!needsDir[bond1->getIdx()]) { @@ -2256,8 +2302,9 @@ void setDoubleBondNeighborDirections(ROMol &mol, const Conformer *conf) { if (nbrBond->getBondType() == Bond::SINGLE || nbrBond->getBondType() == Bond::AROMATIC) { singleBondCounts[nbrBond->getIdx()] += 1; - if (nbrBond->getBondDir() == Bond::NONE) + if (nbrBond->getBondDir() == Bond::NONE) { needsDir[nbrBond->getIdx()] = 1; + } needsDir[(*bondIt)->getIdx()] = 1; dblBondNbrs[(*bondIt)->getIdx()].push_back(nbrBond->getIdx()); // the search may seem inefficient, but these vectors are going to @@ -2279,8 +2326,9 @@ void setDoubleBondNeighborDirections(ROMol &mol, const Conformer *conf) { if (nbrBond->getBondType() == Bond::SINGLE || nbrBond->getBondType() == Bond::AROMATIC) { singleBondCounts[nbrBond->getIdx()] += 1; - if (nbrBond->getBondDir() == Bond::NONE) + if (nbrBond->getBondDir() == Bond::NONE) { needsDir[nbrBond->getIdx()] = 1; + } needsDir[(*bondIt)->getIdx()] = 1; dblBondNbrs[(*bondIt)->getIdx()].push_back(nbrBond->getIdx()); @@ -2301,7 +2349,9 @@ void setDoubleBondNeighborDirections(ROMol &mol, const Conformer *conf) { } if (!bondsInPlay.size()) { - if (resetRings) mol.getRingInfo()->reset(); + if (resetRings) { + mol.getRingInfo()->reset(); + } return; } @@ -2316,7 +2366,9 @@ void setDoubleBondNeighborDirections(ROMol &mol, const Conformer *conf) { // the sum // above (instead of the max) and this ring-membershipt test seem to fix // sf.net issue 3009836 - if (!(mol.getRingInfo()->numBondRings(dblBond->getIdx()))) countHere *= 10; + if (!(mol.getRingInfo()->numBondRings(dblBond->getIdx()))) { + countHere *= 10; + } orderedBondsInPlay.push_back(std::make_pair(countHere, dblBond)); } std::sort(orderedBondsInPlay.begin(), orderedBondsInPlay.end()); @@ -2331,11 +2383,15 @@ void setDoubleBondNeighborDirections(ROMol &mol, const Conformer *conf) { updateDoubleBondNeighbors(mol, pairIter->second, conf, needsDir, singleBondCounts, singleBondNbrs); } - if (resetRings) mol.getRingInfo()->reset(); + if (resetRings) { + mol.getRingInfo()->reset(); + } } void detectBondStereochemistry(ROMol &mol, int confId) { - if (!mol.getNumConformers()) return; + if (!mol.getNumConformers()) { + return; + } const Conformer &conf = mol.getConformer(confId); setDoubleBondNeighborDirections(mol, &conf); } @@ -2381,7 +2437,9 @@ void setBondStereoFromDirections(ROMol &mol) { void assignStereochemistryFrom3D(ROMol &mol, int confId, bool replaceExistingTags) { - if (!mol.getNumConformers() || !mol.getConformer(confId).is3D()) return; + if (!mol.getNumConformers() || !mol.getConformer(confId).is3D()) { + return; + } detectBondStereochemistry(mol, confId); assignChiralTypesFrom3D(mol, confId, replaceExistingTags); @@ -2393,7 +2451,9 @@ void assignStereochemistryFrom3D(ROMol &mol, int confId, void assignChiralTypesFromBondDirs(ROMol &mol, const int confId, const bool replaceExistingTags) { - if (!mol.getNumConformers()) return; + if (!mol.getNumConformers()) { + return; + } auto conf = mol.getConformer(confId); for (auto &bond : mol.bonds()) { diff --git a/Code/GraphMol/Conformer.cpp b/Code/GraphMol/Conformer.cpp index 6483e9e83..57b18a656 100644 --- a/Code/GraphMol/Conformer.cpp +++ b/Code/GraphMol/Conformer.cpp @@ -27,7 +27,9 @@ void Conformer::initFromOther(const Conformer &conf) { Conformer::Conformer(const Conformer &conf) : RDProps() { initFromOther(conf); } Conformer &Conformer::operator=(const Conformer &other) { - if (this == &other) return *this; + if (this == &other) { + return *this; + } initFromOther(other); return *this; } diff --git a/Code/GraphMol/ConjugHybrid.cpp b/Code/GraphMol/ConjugHybrid.cpp index 86195d748..48a8edc8b 100644 --- a/Code/GraphMol/ConjugHybrid.cpp +++ b/Code/GraphMol/ConjugHybrid.cpp @@ -36,7 +36,9 @@ bool isAtomConjugCand(const Atom *at) { } void markConjAtomBonds(Atom *at) { - if (!isAtomConjugCand(at)) return; + if (!isAtomConjugCand(at)) { + return; + } ROMol &mol = at->getOwningMol(); Atom *at2; @@ -83,7 +85,9 @@ int numBondsPlusLonePairs(Atom *at) { boost::tie(beg, end) = at->getOwningMol().getAtomBonds(at); while (beg != end) { Bond *bond = at->getOwningMol()[*beg]; - if (bond->getBondType() == Bond::ZERO) --deg; + if (bond->getBondType() == Bond::ZERO) { + --deg; + } ++beg; } @@ -115,7 +119,9 @@ bool atomHasConjugatedBond(const Atom *at) { ROMol::OEDGE_ITER beg, end; boost::tie(beg, end) = at->getOwningMol().getAtomBonds(at); while (beg != end) { - if (at->getOwningMol()[*beg]->getIsConjugated()) return true; + if (at->getOwningMol()[*beg]->getIsConjugated()) { + return true; + } beg++; } return false; diff --git a/Code/GraphMol/Depictor/EmbeddedFrag.cpp b/Code/GraphMol/Depictor/EmbeddedFrag.cpp index b0a14657a..c501a461e 100644 --- a/Code/GraphMol/Depictor/EmbeddedFrag.cpp +++ b/Code/GraphMol/Depictor/EmbeddedFrag.cpp @@ -1161,7 +1161,9 @@ void EmbeddedFrag::computeBox() { void EmbeddedFrag::canonicalizeOrientation() { // fix for issue 198 // no need to canonicalize if we are dealing with a single atm - if (d_eatoms.size() <= 1) return; + if (d_eatoms.size() <= 1) { + return; + } RDGeom::Point2D cent(0.0, 0.0); for (const auto &elem : d_eatoms) { @@ -1192,7 +1194,9 @@ void EmbeddedFrag::canonicalizeOrientation() { RDGeom::Transform2D trans; eig1.x = 2 * xy; eig1.y = (yy - xx) + d; - if (eig1.length() <= 1e-4) return; + if (eig1.length() <= 1e-4) { + return; + } double eVal1 = (xx + yy + d) / 2; eig1.normalize(); @@ -1489,8 +1493,8 @@ std::vector EmbeddedFrag::findCollisions(const double *dmat, bool includeBonds) { // find a pair of atoms that are too close to each other std::vector res; - for (auto efi = d_eatoms.begin(); efi != d_eatoms.end(); ++efi) { - efi->second.d_density = 0.0; + for (auto &d_eatom : d_eatoms) { + d_eatom.second.d_density = 0.0; } auto tempi = d_eatoms.begin(); @@ -1665,12 +1669,16 @@ void EmbeddedFrag::flipAboutBond(unsigned int bondId, bool flipEnd) { unsigned int nEndAtomsFixed = 0; unsigned int nAtomsFixed = 0; for (auto &d_eatom : d_eatoms) { - if (d_eatom.second.df_fixed) ++nAtomsFixed; + if (d_eatom.second.df_fixed) { + ++nAtomsFixed; + } } // if there are fixed atoms, look at the atoms on the "end side" if (nAtomsFixed) { BOOST_FOREACH (int endAtomId, endSideAids) { - if (d_eatoms[endAtomId].df_fixed) ++nEndAtomsFixed; + if (d_eatoms[endAtomId].df_fixed) { + ++nEndAtomsFixed; + } } } // std::cerr << " FLIP: " << nAtomsFixed << " " << nEndAtomsFixed << @@ -2006,7 +2014,9 @@ void EmbeddedFrag::removeCollisionsShortenBonds() { RDKit::INT_VECT_CI rpi; RDGeom::INT_POINT2D_MAP moveMap; for (rpi = rPath.begin(); rpi != rPath.end(); rpi++) { - if (d_eatoms[*rpi].df_fixed) continue; + if (d_eatoms[*rpi].df_fixed) { + continue; + } RDGeom::Point2D move; move = d_eatoms[nbrMap[*rpi][0]].loc; move += d_eatoms[nbrMap[*rpi][1]].loc; diff --git a/Code/GraphMol/Depictor/RDDepictor.cpp b/Code/GraphMol/Depictor/RDDepictor.cpp index 8a755e278..e8a16ffed 100644 --- a/Code/GraphMol/Depictor/RDDepictor.cpp +++ b/Code/GraphMol/Depictor/RDDepictor.cpp @@ -312,7 +312,9 @@ unsigned int compute2DCoords(RDKit::ROMol &mol, // default to use CoordGen if we have it installed if (!forceRDKit && preferCoordGen) { RDKit::CoordGen::CoordGenParams params; - if (coordMap) params.coordMap = *coordMap; + if (coordMap) { + params.coordMap = *coordMap; + } return RDKit::CoordGen::addCoords(mol, ¶ms); }; #endif diff --git a/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp b/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp index bfc5a39bf..92fa69635 100644 --- a/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp +++ b/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp @@ -72,7 +72,7 @@ unsigned int Compute2DCoordsMimicDistmat( throw_value_error("Argument isn't an array"); } - PyArrayObject *dmatrix = reinterpret_cast(distMatPtr); + auto *dmatrix = reinterpret_cast(distMatPtr); unsigned int nitems = PyArray_DIM(dmatrix, 0); unsigned int na = mol.getNumAtoms(); @@ -80,7 +80,7 @@ unsigned int Compute2DCoordsMimicDistmat( throw_value_error( "The array size does not match the number of atoms in the molecule"); } - double *inData = reinterpret_cast(PyArray_DATA(dmatrix)); + auto *inData = reinterpret_cast(PyArray_DATA(dmatrix)); auto *cData = new double[nitems]; memcpy(static_cast(cData), static_cast(inData), diff --git a/Code/GraphMol/Descriptors/AUTOCORR3D.cpp b/Code/GraphMol/Descriptors/AUTOCORR3D.cpp index 7fca30242..0f22e7628 100644 --- a/Code/GraphMol/Descriptors/AUTOCORR3D.cpp +++ b/Code/GraphMol/Descriptors/AUTOCORR3D.cpp @@ -60,12 +60,13 @@ VectorXd getEigenVect(std::vector v) { double* GetGeodesicMatrix(double* dist, int lag, int numAtoms) { int sizeArray = numAtoms * numAtoms; - double* Geodesic = new double[sizeArray]; + auto* Geodesic = new double[sizeArray]; for (int i = 0; i < sizeArray; i++) { - if (dist[i] == lag) + if (dist[i] == lag) { Geodesic[i] = 1.0; - else + } else { Geodesic[i] = 0.0; + } } return Geodesic; } @@ -118,42 +119,58 @@ void get3DautocorrelationDesc(double* dist3D, double* topologicaldistance, tmp = Wu.transpose() * RBi * Wu; dtmp = (double)tmp(0); - if (boost::math::isnan(dtmp)) dtmp = 0.0; + if (boost::math::isnan(dtmp)) { + dtmp = 0.0; + } TDBmat[0][i] = dtmp; tmp = Wm.transpose() * RBi * Wm; dtmp = (double)tmp(0); - if (boost::math::isnan(dtmp)) dtmp = 0.0; + if (boost::math::isnan(dtmp)) { + dtmp = 0.0; + } TDBmat[1][i] = dtmp; tmp = Wv.transpose() * RBi * Wv; dtmp = (double)tmp(0); - if (boost::math::isnan(dtmp)) dtmp = 0.0; + if (boost::math::isnan(dtmp)) { + dtmp = 0.0; + } TDBmat[2][i] = dtmp; tmp = We.transpose() * RBi * We; dtmp = (double)tmp(0); - if (boost::math::isnan(dtmp)) dtmp = 0.0; + if (boost::math::isnan(dtmp)) { + dtmp = 0.0; + } TDBmat[3][i] = dtmp; tmp = Wp.transpose() * RBi * Wp; dtmp = (double)tmp(0); - if (boost::math::isnan(dtmp)) dtmp = 0.0; + if (boost::math::isnan(dtmp)) { + dtmp = 0.0; + } TDBmat[4][i] = dtmp; tmp = Wi.transpose() * RBi * Wi; dtmp = (double)tmp(0); - if (boost::math::isnan(dtmp)) dtmp = 0.0; + if (boost::math::isnan(dtmp)) { + dtmp = 0.0; + } TDBmat[5][i] = dtmp; tmp = Ws.transpose() * RBi * Ws; dtmp = (double)tmp(0); - if (boost::math::isnan(dtmp)) dtmp = 0.0; + if (boost::math::isnan(dtmp)) { + dtmp = 0.0; + } TDBmat[6][i] = dtmp; tmp = Wr.transpose() * RBi * Wr; dtmp = (double)tmp(0); - if (boost::math::isnan(dtmp)) dtmp = 0.0; + if (boost::math::isnan(dtmp)) { + dtmp = 0.0; + } TDBmat[7][i] = dtmp; delete[] Bimat; } @@ -189,7 +206,9 @@ void get3DautocorrelationDesc(double* dist3D, double* topologicaldistance, tmp = Wc.transpose() * RBi * Wc; dtmp = (double)tmp(0); - if (std::isnan(dtmp)) dtmp = 0.0; + if (std::isnan(dtmp)) { + dtmp = 0.0; + } TDBmat[i] = dtmp; delete[] Bimat; } diff --git a/Code/GraphMol/Descriptors/ConnectivityDescriptors.cpp b/Code/GraphMol/Descriptors/ConnectivityDescriptors.cpp index 9c444e567..8727b3ff1 100644 --- a/Code/GraphMol/Descriptors/ConnectivityDescriptors.cpp +++ b/Code/GraphMol/Descriptors/ConnectivityDescriptors.cpp @@ -40,8 +40,9 @@ void hkDeltas(const ROMol &mol, std::vector &deltas, bool force) { double(tbl->getNouterElecs(n) - at->getTotalNumHs()) / (n - tbl->getNouterElecs(n) - 1); } - if (deltas[at->getIdx()] != 0.0) + if (deltas[at->getIdx()] != 0.0) { deltas[at->getIdx()] = 1. / sqrt(deltas[at->getIdx()]); + } ++atBegin; } mol.setProp(common_properties::_connectivityHKDeltas, deltas, true); @@ -276,7 +277,9 @@ double calcHallKierAlpha(const ROMol &mol, std::vector *atomContribs) { const Atom* at = mol[*atBegin]; ++atBegin; unsigned int n = at->getAtomicNum(); - if (!n) continue; + if (!n) { + continue; + } bool found; double alpha = detail::getAlpha(*(at), found); if (!found) { @@ -284,7 +287,9 @@ double calcHallKierAlpha(const ROMol &mol, std::vector *atomContribs) { alpha = rA / rC - 1.0; } alphaSum += alpha; - if (atomContribs) (*atomContribs)[at->getIdx()] = alpha; + if (atomContribs) { + (*atomContribs)[at->getIdx()] = alpha; + } } return alphaSum; }; diff --git a/Code/GraphMol/Descriptors/Crippen.cpp b/Code/GraphMol/Descriptors/Crippen.cpp index c0d0978d7..075adfeb2 100644 --- a/Code/GraphMol/Descriptors/Crippen.cpp +++ b/Code/GraphMol/Descriptors/Crippen.cpp @@ -69,12 +69,18 @@ void getCrippenAtomContribs(const ROMol &mol, std::vector &logpContribs, atomNeeded[idx] = 0; logpContribs[idx] = param.logp; mrContribs[idx] = param.mr; - if (atomTypes) (*atomTypes)[idx] = param.idx; - if (atomTypeLabels) (*atomTypeLabels)[idx] = param.label; + if (atomTypes) { + (*atomTypes)[idx] = param.idx; + } + if (atomTypeLabels) { + (*atomTypeLabels)[idx] = param.label; + } } } // no need to keep matching stuff if we already found all the atoms: - if (atomNeeded.none()) break; + if (atomNeeded.none()) { + break; + } } mol.setProp(common_properties::_crippenLogPContribs, logpContribs, true); mol.setProp(common_properties::_crippenMRContribs, mrContribs, true); @@ -89,7 +95,7 @@ void calcCrippenDescriptors(const ROMol &mol, double &logp, double &mr, // this isn't as bad as it looks, we aren't actually going // to harm the molecule in any way! - ROMol *workMol = const_cast(&mol); + auto *workMol = const_cast(&mol); if (includeHs) { workMol = MolOps::addHs(mol, false, false); } @@ -140,10 +146,11 @@ const CrippenParamCollection *CrippenParamCollection::getParams( CrippenParamCollection::CrippenParamCollection(const std::string ¶mData) { std::string params; boost::char_separator tabSep("\t", "", boost::keep_empty_tokens); - if (paramData == "") + if (paramData == "") { params = defaultParamData; - else + } else { params = paramData; + } std::istringstream inStream(params); std::string inLine = RDKit::getLine(inStream); diff --git a/Code/GraphMol/Descriptors/EEM.cpp b/Code/GraphMol/Descriptors/EEM.cpp index 42413f2e8..e4fcf3627 100644 --- a/Code/GraphMol/Descriptors/EEM.cpp +++ b/Code/GraphMol/Descriptors/EEM.cpp @@ -125,7 +125,7 @@ std::unique_ptr getEEMMatrix(double *dist3D, unsigned int n, const EEM_arrays& EEMatoms) { PRECONDITION(dist3D != nullptr, "bad dist3D argument") int sizeArray = (n + 1) * (n + 1); - double *EEM = + auto *EEM = new double[sizeArray](); // declaration to set all elements to zeros! /* Fill the full n * n block */ for (unsigned int i = 0; i < n; i++) { @@ -159,7 +159,7 @@ std::unique_ptr getEEMMatrix(double *dist3D, unsigned int n, std::unique_ptr getBVector(const ROMol &mol, unsigned int n, const EEM_arrays &EEMatoms) { /* Fill vector b i.e. -A */ - double *b = new double[n + 1]; + auto *b = new double[n + 1]; for (unsigned int j = 0; j < n; j++) { unsigned int t = EEMatoms.EEMatomtype[j]; unsigned int idx = EEMatoms.Atomindex[j]; diff --git a/Code/GraphMol/Descriptors/Lipinski.cpp b/Code/GraphMol/Descriptors/Lipinski.cpp index 2f870189e..aaaf5724b 100644 --- a/Code/GraphMol/Descriptors/Lipinski.cpp +++ b/Code/GraphMol/Descriptors/Lipinski.cpp @@ -78,7 +78,9 @@ unsigned int calcLipinskiHBA(const ROMol &mol) { unsigned int res = 0; for (ROMol::ConstAtomIterator iter = mol.beginAtoms(); iter != mol.endAtoms(); ++iter) { - if ((*iter)->getAtomicNum() == 7 || (*iter)->getAtomicNum() == 8) ++res; + if ((*iter)->getAtomicNum() == 7 || (*iter)->getAtomicNum() == 8) { + ++res; + } } return res; } @@ -105,9 +107,10 @@ const NumRotatableBondsOptions DefaultStrictDefinition = NonStrict; const std::string NumRotatableBondsVersion = "3.0.0"; unsigned int calcNumRotatableBonds(const ROMol &mol, NumRotatableBondsOptions strict) { - if (strict == Default) + if (strict == Default) { strict = DefaultStrictDefinition; - + } + if (strict == NonStrict) { std::string pattern = "[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]"; pattern_flyweight m(pattern); @@ -149,11 +152,15 @@ unsigned int calcNumRotatableBonds(const ROMol &mol, NumRotatableBondsOptions st // remove symmetrical rings: res -= symRings_matcher.get().countMatches(mol); - if (res < 0) res = 0; + if (res < 0) { + res = 0; + } // remove triple bonds res -= terminalTripleBonds_matcher.get().countMatches(mol); - if (res < 0) res = 0; + if (res < 0) { + res = 0; + } // removing amides is more complex boost::dynamic_bitset<> atomsSeen(mol.getNumAtoms()); @@ -166,10 +173,14 @@ unsigned int calcNumRotatableBonds(const ROMol &mol, NumRotatableBondsOptions st } atomsSeen.set(mIt.second); } - if (distinct && res > 0) --res; + if (distinct && res > 0) { + --res; + } } - if (res < 0) res = 0; + if (res < 0) { + res = 0; + } return static_cast(res); } } @@ -212,7 +223,9 @@ double calcFractionCSP3(const ROMol &mol) { } ++atBegin; } - if (!nC) return 0; + if (!nC) { + return 0; + } return static_cast(nCSP3) / nC; } @@ -289,7 +302,9 @@ unsigned int calcNumAromaticHeterocycles(const ROMol &mol) { countIt = true; } } - if (countIt) ++res; + if (countIt) { + ++res; + } } return res; } @@ -311,7 +326,9 @@ unsigned int calcNumAromaticCarbocycles(const ROMol &mol) { break; } } - if (countIt) ++res; + if (countIt) { + ++res; + } } return res; } @@ -333,7 +350,9 @@ unsigned int calcNumAliphaticHeterocycles(const ROMol &mol) { hasHetero = true; } } - if (hasHetero && hasAliph) ++res; + if (hasHetero && hasAliph) { + ++res; + } } return res; } @@ -355,7 +374,9 @@ unsigned int calcNumAliphaticCarbocycles(const ROMol &mol) { break; } } - if (hasAliph && !hasHetero) ++res; + if (hasAliph && !hasHetero) { + ++res; + } } return res; } @@ -378,7 +399,9 @@ unsigned int calcNumSaturatedHeterocycles(const ROMol &mol) { countIt = true; } } - if (countIt) ++res; + if (countIt) { + ++res; + } } return res; } @@ -401,7 +424,9 @@ unsigned int calcNumSaturatedCarbocycles(const ROMol &mol) { break; } } - if (countIt) ++res; + if (countIt) { + ++res; + } } return res; } @@ -414,7 +439,9 @@ unsigned int calcNumSpiroAtoms(const ROMol &mol, } const RingInfo *rInfo = mol.getRingInfo(); std::vector lAtoms; - if (!atoms) atoms = &lAtoms; + if (!atoms) { + atoms = &lAtoms; + } for (unsigned int i = 0; i < rInfo->atomRings().size(); ++i) { const INT_VECT &ri = rInfo->atomRings()[i]; @@ -442,7 +469,9 @@ unsigned int calcNumBridgeheadAtoms(const ROMol &mol, } const RingInfo *rInfo = mol.getRingInfo(); std::vector lAtoms; - if (!atoms) atoms = &lAtoms; + if (!atoms) { + atoms = &lAtoms; + } for (unsigned int i = 0; i < rInfo->bondRings().size(); ++i) { const INT_VECT &ri = rInfo->bondRings()[i]; @@ -478,9 +507,10 @@ bool hasStereoAssigned(const ROMol &mol) { } const std::string NumAtomStereoCentersVersion = "1.0.0"; unsigned int numAtomStereoCenters(const ROMol &mol) { - if(!hasStereoAssigned(mol)) + if (!hasStereoAssigned(mol)) { throw ValueErrorException("numStereoCenters called without stereo being assigned"); - + } + unsigned int res=0; for (ROMol::ConstAtomIterator atom = mol.beginAtoms(); atom != mol.endAtoms(); ++atom) { @@ -493,8 +523,9 @@ unsigned int numAtomStereoCenters(const ROMol &mol) { const std::string NumUnspecifiedAtomStereoCentersVersion = "1.0.0"; unsigned int numUnspecifiedAtomStereoCenters(const ROMol &mol) { - if(!hasStereoAssigned(mol)) + if (!hasStereoAssigned(mol)) { throw ValueErrorException("numUnspecifiedStereoCenters called without stereo being assigned"); + } unsigned int res=0; for (ROMol::ConstAtomIterator atom = mol.beginAtoms(); atom != mol.endAtoms(); diff --git a/Code/GraphMol/Descriptors/MQN.cpp b/Code/GraphMol/Descriptors/MQN.cpp index 6c2bb74be..1dd6bad0a 100644 --- a/Code/GraphMol/Descriptors/MQN.cpp +++ b/Code/GraphMol/Descriptors/MQN.cpp @@ -62,10 +62,11 @@ std::vector calcMQNs(const ROMol& mol, bool force) { res[6]++; break; case 7: - if (!nRings) + if (!nRings) { res[7]++; - else + } else { res[8]++; + } if (at->getDegree() != 4) { res[19]++; // number of acceptor sites res[20]++; // number of acceptor atoms @@ -76,10 +77,11 @@ std::vector calcMQNs(const ROMol& mol, bool force) { } break; case 8: - if (!nRings) + if (!nRings) { res[9]++; - else + } else { res[10]++; + } res[20]++; // number of acceptor atoms if (at->getFormalCharge() != -1) { res[19] += 2; // number of acceptor sites @@ -95,10 +97,11 @@ std::vector calcMQNs(const ROMol& mol, bool force) { break; } - if (at->getFormalCharge() > 0) + if (at->getFormalCharge() > 0) { res[24]++; // positive charges - else if (at->getFormalCharge() < 0) + } else if (at->getFormalCharge() < 0) { res[23]++; // negative charges + } if (at->getAtomicNum() != 1) { switch (at->getDegree()) { @@ -106,25 +109,30 @@ std::vector calcMQNs(const ROMol& mol, bool force) { res[25]++; break; case 2: - if (!nRings) + if (!nRings) { res[26]++; - else + } else { res[29]++; + } break; case 3: - if (!nRings) + if (!nRings) { res[27]++; - else + } else { res[30]++; + } break; case 4: - if (!nRings) + if (!nRings) { res[28]++; - else + } else { res[31]++; + } break; } - if (nRings >= 2) res[40]++; + if (nRings >= 2) { + res[40]++; + } } } res[11] = mol.getNumHeavyAtoms(); @@ -136,31 +144,38 @@ std::vector calcMQNs(const ROMol& mol, bool force) { boost::tie(firstB, lastB) = mol.getEdges(); while (firstB != lastB) { const Bond* bond = mol[*firstB]; - if (bond->getIsAromatic()) ++nAromatic; + if (bond->getIsAromatic()) { + ++nAromatic; + } unsigned int nRings = mol.getRingInfo()->numBondRings(bond->getIdx()); switch (bond->getBondType()) { case Bond::SINGLE: - if (!nRings) + if (!nRings) { res[12]++; - else + } else { res[15]++; + } break; case Bond::DOUBLE: - if (!nRings) + if (!nRings) { res[13]++; - else + } else { res[16]++; + } break; case Bond::TRIPLE: - if (!nRings) + if (!nRings) { res[14]++; - else + } else { res[17]++; + } break; default: break; } - if (nRings >= 2) res[41]++; + if (nRings >= 2) { + res[41]++; + } ++firstB; } // rather than do the work to kekulize the molecule, we cheat @@ -169,7 +184,9 @@ std::vector calcMQNs(const ROMol& mol, bool force) { // remainder to the single bonds res[15] += nAromatic / 2; res[16] += nAromatic / 2; - if (nAromatic % 2) res[15]++; + if (nAromatic % 2) { + res[15]++; + } res[18] = calcNumRotatableBonds(mol); // --------------------------------------------------- diff --git a/Code/GraphMol/Descriptors/MolData3Ddescriptors.cpp b/Code/GraphMol/Descriptors/MolData3Ddescriptors.cpp index a7fc46cb4..181c7d993 100644 --- a/Code/GraphMol/Descriptors/MolData3Ddescriptors.cpp +++ b/Code/GraphMol/Descriptors/MolData3Ddescriptors.cpp @@ -114,20 +114,21 @@ std::vector MolData3Ddescriptors::GetCharges(const RDKit::ROMol& mol) { } int MolData3Ddescriptors::GetPrincipalQuantumNumber(int AtomicNum) { - if (AtomicNum <= 2) + if (AtomicNum <= 2) { return 1; - else if (AtomicNum <= 10) + } else if (AtomicNum <= 10) { return 2; - else if (AtomicNum <= 18) + } else if (AtomicNum <= 18) { return 3; - else if (AtomicNum <= 36) + } else if (AtomicNum <= 36) { return 4; - else if (AtomicNum <= 54) + } else if (AtomicNum <= 54) { return 5; - else if (AtomicNum <= 86) + } else if (AtomicNum <= 86) { return 6; - else + } else { return 7; + } } std::vector MolData3Ddescriptors::GetIState(const RDKit::ROMol& mol) { diff --git a/Code/GraphMol/Descriptors/MolDescriptors.cpp b/Code/GraphMol/Descriptors/MolDescriptors.cpp index cc6fe6580..988f8c302 100644 --- a/Code/GraphMol/Descriptors/MolDescriptors.cpp +++ b/Code/GraphMol/Descriptors/MolDescriptors.cpp @@ -73,34 +73,43 @@ bool HillCompare(const std::pair &v1, // special cases: Cs, Hs, Ds, and Ts go at the beginning if (v1.second == "C") { - if (v2.second != "C") return true; + if (v2.second != "C") { + return true; + } return nCompare; - } else if (v2.second == "C") + } else if (v2.second == "C") { return false; + } if (v1.second == "H") { - if (v2.second != "H") return true; + if (v2.second != "H") { + return true; + } return nCompare; - } else if (v2.second == "H") + } else if (v2.second == "H") { return false; + } - if (v1.second == "D") + if (v1.second == "D") { return true; - else if (v2.second == "D") + } else if (v2.second == "D") { return false; + } - if (v1.second == "T") + if (v1.second == "T") { return true; - else if (v2.second == "T") + } else if (v2.second == "T") { return false; + } // finally, just compare the symbols and the isotopes: - if (v1 != v2) + if (v1 != v2) { return v1 < v2; - else + } else { return nCompare; + } } -} +} // namespace static std::string _molFormulaVersion = "1.3.0"; std::string calcMolFormula(const ROMol &mol, bool separateIsotopes, @@ -118,10 +127,11 @@ std::string calcMolFormula(const ROMol &mol, bool separateIsotopes, if (separateIsotopes) { unsigned int isotope = (*atomIt)->getIsotope(); if (abbreviateHIsotopes && atNum == 1 && (isotope == 2 || isotope == 3)) { - if (isotope == 2) + if (isotope == 2) { key.second = "D"; - else + } else { key.second = "T"; + } } else { key.first = isotope; } @@ -160,14 +170,20 @@ std::string calcMolFormula(const ROMol &mol, bool separateIsotopes, } else { res << key.second; } - if (counts[key] > 1) res << counts[key]; + if (counts[key] > 1) { + res << counts[key]; + } } if (charge > 0) { res << "+"; - if (charge > 1) res << charge; + if (charge > 1) { + res << charge; + } } else if (charge < 0) { res << "-"; - if (charge < -1) res << -1 * charge; + if (charge < -1) { + res << -1 * charge; + } } return res.str(); } diff --git a/Code/GraphMol/Descriptors/MolSurf.cpp b/Code/GraphMol/Descriptors/MolSurf.cpp index 236352870..ce4b165b9 100644 --- a/Code/GraphMol/Descriptors/MolSurf.cpp +++ b/Code/GraphMol/Descriptors/MolSurf.cpp @@ -161,113 +161,136 @@ double getTPSAAtomContribs(const ROMol &mol, std::vector &Vi, if (atNum == 7) { switch (nNbrs[i]) { case 1: - if (nHs[i] == 0 && chg == 0 && nTrip[i] == 1) + if (nHs[i] == 0 && chg == 0 && nTrip[i] == 1) { tmp = 23.79; - else if (nHs[i] == 1 && chg == 0 && nDoub[i] == 1) + } else if (nHs[i] == 1 && chg == 0 && nDoub[i] == 1) { tmp = 23.85; - else if (nHs[i] == 2 && chg == 0 && nSing[i] == 1) + } else if (nHs[i] == 2 && chg == 0 && nSing[i] == 1) { tmp = 26.02; - else if (nHs[i] == 2 && chg == 1 && nDoub[i] == 1) + } else if (nHs[i] == 2 && chg == 1 && nDoub[i] == 1) { tmp = 25.59; - else if (nHs[i] == 3 && chg == 1 && nSing[i] == 1) + } else if (nHs[i] == 3 && chg == 1 && nSing[i] == 1) { tmp = 27.64; + } break; case 2: - if (nHs[i] == 0 && chg == 0 && nSing[i] == 1 && nDoub[i] == 1) + if (nHs[i] == 0 && chg == 0 && nSing[i] == 1 && nDoub[i] == 1) { tmp = 12.36; - else if (nHs[i] == 0 && chg == 0 && nTrip[i] == 1 && nDoub[i] == 1) + } else if (nHs[i] == 0 && chg == 0 && nTrip[i] == 1 && + nDoub[i] == 1) { tmp = 13.60; - else if (nHs[i] == 1 && chg == 0 && nSing[i] == 2 && in3Ring) + } else if (nHs[i] == 1 && chg == 0 && nSing[i] == 2 && in3Ring) { tmp = 21.94; - else if (nHs[i] == 1 && chg == 0 && nSing[i] == 2 && !in3Ring) + } else if (nHs[i] == 1 && chg == 0 && nSing[i] == 2 && !in3Ring) { tmp = 12.03; - else if (nHs[i] == 0 && chg == 1 && nTrip[i] == 1 && nSing[i] == 1) + } else if (nHs[i] == 0 && chg == 1 && nTrip[i] == 1 && + nSing[i] == 1) { tmp = 4.36; - else if (nHs[i] == 1 && chg == 1 && nDoub[i] == 1 && nSing[i] == 1) + } else if (nHs[i] == 1 && chg == 1 && nDoub[i] == 1 && + nSing[i] == 1) { tmp = 13.97; - else if (nHs[i] == 2 && chg == 1 && nSing[i] == 2) + } else if (nHs[i] == 2 && chg == 1 && nSing[i] == 2) { tmp = 16.61; - else if (nHs[i] == 0 && chg == 0 && nArom[i] == 2) + } else if (nHs[i] == 0 && chg == 0 && nArom[i] == 2) { tmp = 12.89; - else if (nHs[i] == 1 && chg == 0 && nArom[i] == 2) + } else if (nHs[i] == 1 && chg == 0 && nArom[i] == 2) { tmp = 15.79; - else if (nHs[i] == 1 && chg == 1 && nArom[i] == 2) + } else if (nHs[i] == 1 && chg == 1 && nArom[i] == 2) { tmp = 14.14; + } break; case 3: - if (nHs[i] == 0 && chg == 0 && nSing[i] == 3 && in3Ring) + if (nHs[i] == 0 && chg == 0 && nSing[i] == 3 && in3Ring) { tmp = 3.01; - else if (nHs[i] == 0 && chg == 0 && nSing[i] == 3 && !in3Ring) + } else if (nHs[i] == 0 && chg == 0 && nSing[i] == 3 && !in3Ring) { tmp = 3.24; - else if (nHs[i] == 0 && chg == 0 && nSing[i] == 1 && nDoub[i] == 2) + } else if (nHs[i] == 0 && chg == 0 && nSing[i] == 1 && + nDoub[i] == 2) { tmp = 11.68; - else if (nHs[i] == 0 && chg == 1 && nSing[i] == 2 && nDoub[i] == 1) + } else if (nHs[i] == 0 && chg == 1 && nSing[i] == 2 && + nDoub[i] == 1) { tmp = 3.01; - else if (nHs[i] == 1 && chg == 1 && nSing[i] == 3) + } else if (nHs[i] == 1 && chg == 1 && nSing[i] == 3) { tmp = 4.44; - else if (nHs[i] == 0 && chg == 0 && nArom[i] == 3) + } else if (nHs[i] == 0 && chg == 0 && nArom[i] == 3) { tmp = 4.41; - else if (nHs[i] == 0 && chg == 0 && nSing[i] == 1 && nArom[i] == 2) + } else if (nHs[i] == 0 && chg == 0 && nSing[i] == 1 && + nArom[i] == 2) { tmp = 4.93; - else if (nHs[i] == 0 && chg == 0 && nDoub[i] == 1 && nArom[i] == 2) + } else if (nHs[i] == 0 && chg == 0 && nDoub[i] == 1 && + nArom[i] == 2) { tmp = 8.39; - else if (nHs[i] == 0 && chg == 1 && nArom[i] == 3) + } else if (nHs[i] == 0 && chg == 1 && nArom[i] == 3) { tmp = 4.10; - else if (nHs[i] == 0 && chg == 1 && nSing[i] == 1 && nArom[i] == 2) + } else if (nHs[i] == 0 && chg == 1 && nSing[i] == 1 && + nArom[i] == 2) { tmp = 3.88; + } break; case 4: - if (nHs[i] == 0 && nSing[i] == 4 && chg == 1) tmp = 0.0; + if (nHs[i] == 0 && nSing[i] == 4 && chg == 1) { + tmp = 0.0; + } break; default: break; } if (tmp < 0.0) { tmp = 30.5 - nNbrs[i] * 8.2 + nHs[i] * 1.5; - if (tmp < 0) tmp = 0.0; + if (tmp < 0) { + tmp = 0.0; + } } } else if (atNum == 8) { switch (nNbrs[i]) { case 1: - if (nHs[i] == 0 && chg == 0 && nDoub[i] == 1) + if (nHs[i] == 0 && chg == 0 && nDoub[i] == 1) { tmp = 17.07; - else if (nHs[i] == 1 && chg == 0 && nSing[i] == 1) + } else if (nHs[i] == 1 && chg == 0 && nSing[i] == 1) { tmp = 20.23; - else if (nHs[i] == 0 && chg == -1 && nSing[i] == 1) + } else if (nHs[i] == 0 && chg == -1 && nSing[i] == 1) { tmp = 23.06; + } break; case 2: - if (nHs[i] == 0 && chg == 0 && nSing[i] == 2 && in3Ring) + if (nHs[i] == 0 && chg == 0 && nSing[i] == 2 && in3Ring) { tmp = 12.53; - else if (nHs[i] == 0 && chg == 0 && nSing[i] == 2 && !in3Ring) + } else if (nHs[i] == 0 && chg == 0 && nSing[i] == 2 && !in3Ring) { tmp = 9.23; - else if (nHs[i] == 0 && chg == 0 && nArom[i] == 2) + } else if (nHs[i] == 0 && chg == 0 && nArom[i] == 2) { tmp = 13.14; + } break; default: break; } if (tmp < 0.0) { tmp = 28.5 - nNbrs[i] * 8.6 + nHs[i] * 1.5; - if (tmp < 0) tmp = 0.0; + if (tmp < 0) { + tmp = 0.0; + } } } else if (includeSandP && atNum == 15) { tmp = 0.0; switch (nNbrs[i]) { case 2: - if (nHs[i] == 0 && chg == 0 && nSing[i] == 1 && nDoub[i] == 1) + if (nHs[i] == 0 && chg == 0 && nSing[i] == 1 && nDoub[i] == 1) { tmp = 34.14; + } break; case 3: - if (nHs[i] == 0 && chg == 0 && nSing[i] == 3) + if (nHs[i] == 0 && chg == 0 && nSing[i] == 3) { tmp = 13.59; - else if (nHs[i] == 1 && chg == 0 && nSing[i] == 2 && nDoub[i] == 1) + } else if (nHs[i] == 1 && chg == 0 && nSing[i] == 2 && + nDoub[i] == 1) { tmp = 23.47; + } break; case 4: - if (nHs[i] == 0 && chg == 0 && nSing[i] == 3 && nDoub[i] == 1) + if (nHs[i] == 0 && chg == 0 && nSing[i] == 3 && nDoub[i] == 1) { tmp = 9.81; + } break; default: break; @@ -276,26 +299,31 @@ double getTPSAAtomContribs(const ROMol &mol, std::vector &Vi, tmp = 0.0; switch (nNbrs[i]) { case 1: - if (nHs[i] == 0 && chg == 0 && nDoub[i] == 1) + if (nHs[i] == 0 && chg == 0 && nDoub[i] == 1) { tmp = 32.09; - else if (nHs[i] == 1 && chg == 0 && nSing[i] == 1) + } else if (nHs[i] == 1 && chg == 0 && nSing[i] == 1) { tmp = 38.80; + } break; case 2: - if (nHs[i] == 0 && chg == 0 && nSing[i] == 2) + if (nHs[i] == 0 && chg == 0 && nSing[i] == 2) { tmp = 25.30; - else if (nHs[i] == 0 && chg == 0 && nArom[i] == 2) + } else if (nHs[i] == 0 && chg == 0 && nArom[i] == 2) { tmp = 28.24; + } break; case 3: - if (nHs[i] == 0 && chg == 0 && nArom[i] == 2 && nDoub[i] == 1) + if (nHs[i] == 0 && chg == 0 && nArom[i] == 2 && nDoub[i] == 1) { tmp = 21.70; - else if (nHs[i] == 0 && chg == 0 && nSing[i] == 2 && nDoub[i] == 1) + } else if (nHs[i] == 0 && chg == 0 && nSing[i] == 2 && + nDoub[i] == 1) { tmp = 19.21; + } break; case 4: - if (nHs[i] == 0 && chg == 0 && nSing[i] == 2 && nDoub[i] == 2) + if (nHs[i] == 0 && chg == 0 && nSing[i] == 2 && nDoub[i] == 2) { tmp = 8.38; + } break; default: break; diff --git a/Code/GraphMol/Descriptors/PBF.cpp b/Code/GraphMol/Descriptors/PBF.cpp index 2fb6bc5c5..6c58ec90f 100644 --- a/Code/GraphMol/Descriptors/PBF.cpp +++ b/Code/GraphMol/Descriptors/PBF.cpp @@ -115,10 +115,14 @@ bool getBestFitPlane(const Conformer &conf, double PBF(const ROMol &mol, int confId) { PRECONDITION(mol.getNumConformers() >= 1, "molecule has no conformers") unsigned int numAtoms = mol.getNumAtoms(); - if (numAtoms < 4) return 0; + if (numAtoms < 4) { + return 0; + } const Conformer &conf = mol.getConformer(confId); - if (!conf.is3D()) return 0; + if (!conf.is3D()) { + return 0; + } std::vector points; points.reserve(numAtoms); diff --git a/Code/GraphMol/Descriptors/PMI.cpp b/Code/GraphMol/Descriptors/PMI.cpp index 1bee1011b..d77c20399 100644 --- a/Code/GraphMol/Descriptors/PMI.cpp +++ b/Code/GraphMol/Descriptors/PMI.cpp @@ -115,7 +115,9 @@ double NPR1(const ROMol& mol, int confId, bool useAtomicMasses, bool force) { // the eigenvector calculation failed return 0.0; // FIX: throw an exception here? } - if (pm3 < 1e-8) return 0.0; + if (pm3 < 1e-8) { + return 0.0; + } return pm1 / pm3; } double NPR2(const ROMol& mol, int confId, bool useAtomicMasses, bool force) { @@ -125,7 +127,9 @@ double NPR2(const ROMol& mol, int confId, bool useAtomicMasses, bool force) { // the eigenvector calculation failed return 0.0; // FIX: throw an exception here? } - if (pm3 < 1e-8) return 0.0; + if (pm3 < 1e-8) { + return 0.0; + } return pm2 / pm3; } double PMI1(const ROMol& mol, int confId, bool useAtomicMasses, bool force) { diff --git a/Code/GraphMol/Descriptors/WHIM.cpp b/Code/GraphMol/Descriptors/WHIM.cpp index 2d1514af1..aeb32401b 100644 --- a/Code/GraphMol/Descriptors/WHIM.cpp +++ b/Code/GraphMol/Descriptors/WHIM.cpp @@ -63,8 +63,7 @@ MatrixXd GetCovMatrix(MatrixXd &X, MatrixXd &Weight, double weight) { } JacobiSVD *getSVD(MatrixXd &Mat) { - JacobiSVD *svd = - new JacobiSVD(Mat, ComputeThinU | ComputeThinV); + auto *svd = new JacobiSVD(Mat, ComputeThinU | ComputeThinV); return svd; } @@ -149,7 +148,7 @@ std::vector getWhimD(std::vector weightvector, // Index and/or Sphericity ! double gamma[3]; // Gamma values - double nAT = (double)numAtoms; + auto nAT = (double)numAtoms; // check if two atoms are symmetric versus the new axis ie newx,newy,newz a for (int i = 0; i < 3; i++) { @@ -304,7 +303,7 @@ void getWHIM(const ROMol &mol, std::vector &res, int confId, double th) { int numAtoms = mol.getNumAtoms(); const Conformer &conf = mol.getConformer(confId); - double *Vpoints = new double[3 * numAtoms]; + auto *Vpoints = new double[3 * numAtoms]; for (int i = 0; i < numAtoms; ++i) { Vpoints[3 * i] = conf.getAtomPos(i).x; @@ -353,7 +352,7 @@ void getWHIMone(const ROMol &mol, std::vector &res, int confId, double th, const std::string &customAtomPropName) { int numAtoms = mol.getNumAtoms(); const Conformer &conf = mol.getConformer(confId); - double *Vpoints = new double[3 * numAtoms]; + auto *Vpoints = new double[3 * numAtoms]; for (int i = 0; i < numAtoms; ++i) { Vpoints[3 * i] = conf.getAtomPos(i).x; diff --git a/Code/GraphMol/Descriptors/Wrap/rdMolDescriptors.cpp b/Code/GraphMol/Descriptors/Wrap/rdMolDescriptors.cpp index 733081041..eb6cf732c 100644 --- a/Code/GraphMol/Descriptors/Wrap/rdMolDescriptors.cpp +++ b/Code/GraphMol/Descriptors/Wrap/rdMolDescriptors.cpp @@ -388,8 +388,12 @@ RDKit::SparseIntVect *MorganFingerprintHelper( } delete bitInfoMap; } - if (invars) delete invars; - if (froms) delete froms; + if (invars) { + delete invars; + } + if (froms) { + delete froms; + } return res; } } // namespace @@ -434,7 +438,7 @@ ExplicitBitVect *GetMorganFingerprintBV( std::unique_ptr> froms = pythonObjectToVect(fromAtoms, mol.getNumAtoms()); - RDKit::MorganFingerprints::BitInfoMap *bitInfoMap = 0; + RDKit::MorganFingerprints::BitInfoMap *bitInfoMap = nullptr; if (bitInfo != python::object()) { // make sure the optional argument actually was a dictionary python::dict typecheck = python::extract(bitInfo); diff --git a/Code/GraphMol/Descriptors/test.cpp b/Code/GraphMol/Descriptors/test.cpp index 47bed0b6e..10be02400 100644 --- a/Code/GraphMol/Descriptors/test.cpp +++ b/Code/GraphMol/Descriptors/test.cpp @@ -321,12 +321,16 @@ void testTPSA() { while (!inf.eof()) { std::string inl = getLine(inf); boost::trim(inl); - if (inl.size() == 0 || inl[0] == '#') continue; + if (inl.size() == 0 || inl[0] == '#') { + continue; + } std::vector tokens; boost::split(tokens, inl, boost::is_any_of(",")); - if (tokens.size() != 2) continue; + if (tokens.size() != 2) { + continue; + } std::string smiles = tokens[0]; - double oTPSA = boost::lexical_cast(tokens[1]); + auto oTPSA = boost::lexical_cast(tokens[1]); ROMol *mol = SmilesToMol(smiles); TEST_ASSERT(mol); double nTPSA = calcTPSA(*mol); @@ -370,7 +374,9 @@ void testLipinski1() { const bool sanitize = true; ROMol *test_mol = SmilesToMol("CC(C)(C)c1cc(O)c(cc1O)C(C)(C)C", 0, sanitize); - if (calcNumRotatableBonds(*test_mol) == 2) rot_prop = NonStrictRotProp; + if (calcNumRotatableBonds(*test_mol) == 2) { + rot_prop = NonStrictRotProp; + } delete test_mol; } while (!suppl.atEnd()) { @@ -381,7 +387,9 @@ void testLipinski1() { } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } unsigned int oVal, nVal; std::string foo; @@ -826,7 +834,9 @@ void runblock(const std::vector &mols, unsigned int count, unsigned int idx) { for (unsigned int j = 0; j < 1000; j++) { for (unsigned int i = 0; i < mols.size(); ++i) { - if (i % count != idx) continue; + if (i % count != idx) { + continue; + } ROMol *mol = mols[i]; int nHBD = calcNumHBD(*mol); int nHBA = calcNumHBA(*mol); @@ -866,7 +876,9 @@ void testMultiThread() { } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } mols.push_back(mol); } std::vector> tg; @@ -881,7 +893,9 @@ void testMultiThread() { for (auto &fut : tg) { fut.get(); } - for (auto &mol : mols) delete mol; + for (auto &mol : mols) { + delete mol; + } BOOST_LOG(rdErrorLog) << " done" << std::endl; } @@ -1531,7 +1545,9 @@ void testMQNs() { const bool sanitize = true; ROMol *test_mol = SmilesToMol("CC(C)(C)c1cc(O)c(cc1O)C(C)(C)C", 0, sanitize); - if (calcNumRotatableBonds(*test_mol) == 2) tgt[18] = 26; + if (calcNumRotatableBonds(*test_mol) == 2) { + tgt[18] = 26; + } delete test_mol; } std::vector accum(42, 0); @@ -1544,7 +1560,9 @@ void testMQNs() { TEST_ASSERT(mol); std::vector v = calcMQNs(*mol); TEST_ASSERT(v.size() == 42); - for (unsigned int i = 0; i < 42; ++i) accum[i] += v[i]; + for (unsigned int i = 0; i < 42; ++i) { + accum[i] += v[i]; + } delete mol; } for (unsigned int i = 0; i < 42; ++i) { diff --git a/Code/GraphMol/DistGeomHelpers/BoundsMatrixBuilder.cpp b/Code/GraphMol/DistGeomHelpers/BoundsMatrixBuilder.cpp index 4e2afaa05..e215892df 100644 --- a/Code/GraphMol/DistGeomHelpers/BoundsMatrixBuilder.cpp +++ b/Code/GraphMol/DistGeomHelpers/BoundsMatrixBuilder.cpp @@ -650,7 +650,9 @@ void _setInRing14Bounds(const ROMol &mol, const Bond *bnd1, const Bond *bnd2, // basically we will assume 0 to 180 allowed dl = RDGeom::compute14DistCis(bl1, bl2, bl3, ba12, ba23); du = RDGeom::compute14DistTrans(bl1, bl2, bl3, ba12, ba23); - if (du < dl) std::swap(du, dl); + if (du < dl) { + std::swap(du, dl); + } if (fabs(du - dl) < DIST12_DELTA) { dl -= GEN_DIST_TOL; du += GEN_DIST_TOL; diff --git a/Code/GraphMol/DistGeomHelpers/Embedder.cpp b/Code/GraphMol/DistGeomHelpers/Embedder.cpp index 35cb817a5..b17292789 100644 --- a/Code/GraphMol/DistGeomHelpers/Embedder.cpp +++ b/Code/GraphMol/DistGeomHelpers/Embedder.cpp @@ -56,90 +56,90 @@ namespace RDKit { namespace DGeomHelpers { //! Parameters corresponding to Sereina Riniker's KDG approach -const EmbedParameters KDG(0, // maxIterations - 1, // numThreads - -1, // randomSeed - true, // clearConfs - false, // useRandomCoords - 2.0, // boxSizeMult - true, // randNegEig - 1, // numZeroFail - NULL, // coordMap - 1e-3, // optimizerForceTol - false, // ignoreSmoothingFailures - true, // enforceChirality - false, // useExpTorsionAnglePrefs - true, // useBasicKnowledge - false, // verbose - 5.0, // basinThresh - -1.0, // pruneRmsThresh - true, // onlyHeavyAtomsForRMS - 1 // ETversion +const EmbedParameters KDG(0, // maxIterations + 1, // numThreads + -1, // randomSeed + true, // clearConfs + false, // useRandomCoords + 2.0, // boxSizeMult + true, // randNegEig + 1, // numZeroFail + nullptr, // coordMap + 1e-3, // optimizerForceTol + false, // ignoreSmoothingFailures + true, // enforceChirality + false, // useExpTorsionAnglePrefs + true, // useBasicKnowledge + false, // verbose + 5.0, // basinThresh + -1.0, // pruneRmsThresh + true, // onlyHeavyAtomsForRMS + 1 // ETversion ); //! Parameters corresponding to Sereina Riniker's ETDG approach -const EmbedParameters ETDG(0, // maxIterations - 1, // numThreads - -1, // randomSeed - true, // clearConfs - false, // useRandomCoords - 2.0, // boxSizeMult - true, // randNegEig - 1, // numZeroFail - NULL, // coordMap - 1e-3, // optimizerForceTol - false, // ignoreSmoothingFailures - false, // enforceChirality - true, // useExpTorsionAnglePrefs - false, // useBasicKnowledge - false, // verbose - 5.0, // basinThresh - -1.0, // pruneRmsThresh - true, // onlyHeavyAtomsForRMS - 1 // ETversion +const EmbedParameters ETDG(0, // maxIterations + 1, // numThreads + -1, // randomSeed + true, // clearConfs + false, // useRandomCoords + 2.0, // boxSizeMult + true, // randNegEig + 1, // numZeroFail + nullptr, // coordMap + 1e-3, // optimizerForceTol + false, // ignoreSmoothingFailures + false, // enforceChirality + true, // useExpTorsionAnglePrefs + false, // useBasicKnowledge + false, // verbose + 5.0, // basinThresh + -1.0, // pruneRmsThresh + true, // onlyHeavyAtomsForRMS + 1 // ETversion ); //! Parameters corresponding to Sereina Riniker's ETKDG approach -const EmbedParameters ETKDG(0, // maxIterations - 1, // numThreads - -1, // randomSeed - true, // clearConfs - false, // useRandomCoords - 2.0, // boxSizeMult - true, // randNegEig - 1, // numZeroFail - NULL, // coordMap - 1e-3, // optimizerForceTol - false, // ignoreSmoothingFailures - true, // enforceChirality - true, // useExpTorsionAnglePrefs - true, // useBasicKnowledge - false, // verbose - 5.0, // basinThresh - -1.0, // pruneRmsThresh - true, // onlyHeavyAtomsForRMS - 1 // ETversion +const EmbedParameters ETKDG(0, // maxIterations + 1, // numThreads + -1, // randomSeed + true, // clearConfs + false, // useRandomCoords + 2.0, // boxSizeMult + true, // randNegEig + 1, // numZeroFail + nullptr, // coordMap + 1e-3, // optimizerForceTol + false, // ignoreSmoothingFailures + true, // enforceChirality + true, // useExpTorsionAnglePrefs + true, // useBasicKnowledge + false, // verbose + 5.0, // basinThresh + -1.0, // pruneRmsThresh + true, // onlyHeavyAtomsForRMS + 1 // ETversion ); //! Parameters corresponding to Sereina Riniker's ETKDG approach - version 2 -const EmbedParameters ETKDGv2(0, // maxIterations - 1, // numThreads - -1, // randomSeed - true, // clearConfs - false, // useRandomCoords - 2.0, // boxSizeMult - true, // randNegEig - 1, // numZeroFail - NULL, // coordMap - 1e-3, // optimizerForceTol - false, // ignoreSmoothingFailures - true, // enforceChirality - true, // useExpTorsionAnglePrefs - true, // useBasicKnowledge - false, // verbose - 5.0, // basinThresh - -1.0, // pruneRmsThresh - true, // onlyHeavyAtomsForRMS - 2 // ETversion +const EmbedParameters ETKDGv2(0, // maxIterations + 1, // numThreads + -1, // randomSeed + true, // clearConfs + false, // useRandomCoords + 2.0, // boxSizeMult + true, // randNegEig + 1, // numZeroFail + nullptr, // coordMap + 1e-3, // optimizerForceTol + false, // ignoreSmoothingFailures + true, // enforceChirality + true, // useExpTorsionAnglePrefs + true, // useBasicKnowledge + false, // verbose + 5.0, // basinThresh + -1.0, // pruneRmsThresh + true, // onlyHeavyAtomsForRMS + 2 // ETversion ); namespace detail { @@ -187,20 +187,36 @@ bool _volumeTest(const DistGeom::ChiralSetPtr &chiralSet, RDGeom::Point3D crossp = v1.crossProduct(v2); double vol = crossp.dotProduct(v3); - if (verbose) std::cerr << " " << fabs(vol) << std::endl; - if (fabs(vol) < MIN_TETRAHEDRAL_CHIRAL_VOL) return false; + if (verbose) { + std::cerr << " " << fabs(vol) << std::endl; + } + if (fabs(vol) < MIN_TETRAHEDRAL_CHIRAL_VOL) { + return false; + } crossp = v1.crossProduct(v2); vol = crossp.dotProduct(v4); - if (verbose) std::cerr << " " << fabs(vol) << std::endl; - if (fabs(vol) < MIN_TETRAHEDRAL_CHIRAL_VOL) return false; + if (verbose) { + std::cerr << " " << fabs(vol) << std::endl; + } + if (fabs(vol) < MIN_TETRAHEDRAL_CHIRAL_VOL) { + return false; + } crossp = v1.crossProduct(v3); vol = crossp.dotProduct(v4); - if (verbose) std::cerr << " " << fabs(vol) << std::endl; - if (fabs(vol) < MIN_TETRAHEDRAL_CHIRAL_VOL) return false; + if (verbose) { + std::cerr << " " << fabs(vol) << std::endl; + } + if (fabs(vol) < MIN_TETRAHEDRAL_CHIRAL_VOL) { + return false; + } crossp = v2.crossProduct(v3); vol = crossp.dotProduct(v4); - if (verbose) std::cerr << " " << fabs(vol) << std::endl; - if (fabs(vol) < MIN_TETRAHEDRAL_CHIRAL_VOL) return false; + if (verbose) { + std::cerr << " " << fabs(vol) << std::endl; + } + if (fabs(vol) < MIN_TETRAHEDRAL_CHIRAL_VOL) { + return false; + } return true; } @@ -212,7 +228,9 @@ bool _sameSide(const RDGeom::Point3D &v1, const RDGeom::Point3D &v2, double d1 = normal.dotProduct(v4 - v1); double d2 = normal.dotProduct(p0 - v1); // std::cerr << " " << d1 << " - " << d2 << std::endl; - if (fabs(d1) < tol || fabs(d2) < tol) return false; + if (fabs(d1) < tol || fabs(d2) < tol) { + return false; + } return !((d1 < 0.) ^ (d2 < 0.)); } bool _centerInVolume(unsigned int idx0, unsigned int idx1, unsigned int idx2, @@ -584,7 +602,9 @@ bool embedPoints(RDGeom::PointPtrVect *positions, detail::EmbedArgs eargs, // random coordinates since it ends up ignoring 1-4 (and higher) // interactions. This causes us to get folded-up (and self-penetrating) // conformations for large flexible molecules - if (embedParams.useRandomCoords) embedParams.basinThresh = 1e8; + if (embedParams.useRandomCoords) { + embedParams.basinThresh = 1e8; + } RDKit::double_source_type *rng = nullptr; RDKit::rng_type *generator; @@ -829,8 +849,8 @@ bool _isConfFarFromRest(const ROMol &mol, const Conformer &conf, _fillAtomPositions(refPoints, conf, mol, onlyHeavyAtomsForRMS); double ssrThres = conf.getNumAtoms() * threshold * threshold; - for (ROMol::ConstConformerIterator confi = mol.beginConformers(); - confi != mol.endConformers(); ++confi) { + for (auto confi = mol.beginConformers(); confi != mol.endConformers(); + ++confi) { _fillAtomPositions(prbPoints, *(*confi), mol, onlyHeavyAtomsForRMS); RDGeom::Transform3D trans; auto ssr = RDNumeric::Alignments::AlignPoints(refPoints, prbPoints, trans); @@ -846,8 +866,12 @@ namespace detail { template bool multiplication_overflows_(T a, T b) { // a * b > c if and only if a > c / b - if (a == 0 || b == 0) return false; - if (a > std::numeric_limits::max() / b) return true; + if (a == 0 || b == 0) { + return false; + } + if (a > std::numeric_limits::max() / b) { + return true; + } return false; } @@ -865,7 +889,9 @@ void embedHelper_(int threadId, int numThreads, EmbedArgs *eargs, } } for (size_t ci = 0; ci < eargs->confs->size(); ci++) { - if (rdcast(ci % numThreads) != threadId) continue; + if (rdcast(ci % numThreads) != threadId) { + continue; + } if (!(*eargs->confsOk)[ci]) { // we call this function for each fragment in a molecule, // if one of the fragments has already failed, there's no @@ -888,7 +914,7 @@ void embedHelper_(int threadId, int numThreads, EmbedArgs *eargs, // maximum possible value of the pair of numbers. The // following will generate unique integers: // hash(a, b) = a + b * N - size_t big_seed = rdcast(params->randomSeed); + auto big_seed = rdcast(params->randomSeed); size_t max_val = std::max(ci + 1, big_seed); size_t big_num = big_seed + max_val * (ci + 1); // only grab the first 31 bits xor'd with the next 31 bits to diff --git a/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp b/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp index 526043688..c60b8d1ed 100644 --- a/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp +++ b/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp @@ -129,7 +129,7 @@ PyObject *getMolBoundsMatrix(ROMol &mol, bool set15bounds = true, if (doTriangleSmoothing) { DistGeom::triangleSmoothBounds(mat); } - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); + auto *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); memcpy(static_cast(PyArray_DATA(res)), static_cast(mat->getData()), nats * nats * sizeof(double)); @@ -151,21 +151,27 @@ DGeomHelpers::EmbedParameters *getETDG() { void setBoundsMatrix(DGeomHelpers::EmbedParameters *self, python::object boundsMatArg) { PyObject *boundsMatObj = boundsMatArg.ptr(); - if (!PyArray_Check(boundsMatObj)) + if (!PyArray_Check(boundsMatObj)) { throw_value_error("Argument isn't an array"); + } - PyArrayObject *boundsMat = reinterpret_cast(boundsMatObj); + auto *boundsMat = reinterpret_cast(boundsMatObj); // get the dimensions of the array int nrows = PyArray_DIM(boundsMat, 0); int ncols = PyArray_DIM(boundsMat, 1); - if (nrows != ncols) throw_value_error("The array has to be square"); - if (nrows <= 0) throw_value_error("The array has to have a nonzero size"); - if (PyArray_DESCR(boundsMat)->type_num != NPY_DOUBLE) + if (nrows != ncols) { + throw_value_error("The array has to be square"); + } + if (nrows <= 0) { + throw_value_error("The array has to have a nonzero size"); + } + if (PyArray_DESCR(boundsMat)->type_num != NPY_DOUBLE) { throw_value_error("Only double arrays are currently supported"); + } unsigned int dSize = nrows * nrows; auto *cData = new double[dSize]; - double *inData = reinterpret_cast(PyArray_DATA(boundsMat)); + auto *inData = reinterpret_cast(PyArray_DATA(boundsMat)); memcpy(static_cast(cData), static_cast(inData), dSize * sizeof(double)); DistGeom::BoundsMatrix::DATA_SPTR sdata(cData); diff --git a/Code/GraphMol/DistGeomHelpers/testDgeomHelpers.cpp b/Code/GraphMol/DistGeomHelpers/testDgeomHelpers.cpp index 6dab65780..911afe538 100644 --- a/Code/GraphMol/DistGeomHelpers/testDgeomHelpers.cpp +++ b/Code/GraphMol/DistGeomHelpers/testDgeomHelpers.cpp @@ -572,9 +572,9 @@ void testMultipleConfs() { void testMultipleConfsExpTors() { std::string smi = "CC(C)(C)c(cc1)ccc1c(cc23)n[n]3C(=O)/C(=C\\N2)C(=O)OCC"; ROMol *m = SmilesToMol(smi, 0, 1); - INT_VECT cids = DGeomHelpers::EmbedMultipleConfs(*m, 10, 30, 100, true, false, - -1, true, 1, -1.0, 0, 1e-3, - false, true, true, true); + INT_VECT cids = DGeomHelpers::EmbedMultipleConfs( + *m, 10, 30, 100, true, false, -1, true, 1, -1.0, nullptr, 1e-3, false, + true, true, true); INT_VECT_CI ci; // SDWriter writer("junk.sdf"); double energy; @@ -891,7 +891,7 @@ void testRandomCoords() { std::string smi = *token; // std::cerr << "SMI: " << smi << std::endl; ROMol *m = SmilesToMol(smi, 0, 1); - RWMol *m2 = (RWMol *)MolOps::addHs(*m); + auto *m2 = (RWMol *)MolOps::addHs(*m); delete m; m = m2; int cid = DGeomHelpers::EmbedMolecule(*m, 10, 1, true, true, 2, true, 1, @@ -941,7 +941,7 @@ void testIssue1989539() { { std::string smi = "c1ccccc1.Cl"; ROMol *m = SmilesToMol(smi, 0, 1); - RWMol *m2 = (RWMol *)MolOps::addHs(*m); + auto *m2 = (RWMol *)MolOps::addHs(*m); delete m; m = m2; int cid = DGeomHelpers::EmbedMolecule(*m); @@ -1233,7 +1233,9 @@ void runblock(const std::vector &mols, unsigned int idx) { for (unsigned int j = 0; j < 100; j++) { for (unsigned int i = 0; i < mols.size(); ++i) { - if (i % count != idx) continue; + if (i % count != idx) { + continue; + } ROMol mol(*mols[i]); std::vector cids = DGeomHelpers::EmbedMultipleConfs(mol, 10, 30, 0xFEED); @@ -1324,7 +1326,9 @@ void testMultiThread() { fut.get(); } - for (auto &mol : mols) delete mol; + for (auto &mol : mols) { + delete mol; + } BOOST_LOG(rdErrorLog) << " done" << std::endl; } @@ -1433,10 +1437,8 @@ void testMultiThreadMultiConf() { TEST_ASSERT(pVect.size() == p2Vect.size()); double msd = 0.0; for (unsigned int i = 0; i < pVect.size(); ++i) { - const RDGeom::Point3D *p = - dynamic_cast(pVect[i]); - const RDGeom::Point3D *p2 = - dynamic_cast(p2Vect[i]); + const auto *p = dynamic_cast(pVect[i]); + const auto *p2 = dynamic_cast(p2Vect[i]); TEST_ASSERT(p && p2); msd += (*p - *p2).lengthSq(); } diff --git a/Code/GraphMol/FMCS/FMCS.cpp b/Code/GraphMol/FMCS/FMCS.cpp index a98169cd5..1a638254f 100644 --- a/Code/GraphMol/FMCS/FMCS.cpp +++ b/Code/GraphMol/FMCS/FMCS.cpp @@ -55,22 +55,24 @@ void parseMCSParametersJSON(const char* json, MCSParameters* params) { pt.get("MatchStereo", p.BondCompareParameters.MatchStereo); std::string s = pt.get("AtomCompare", "def"); - if (0 == strcmp("Any", s.c_str())) + if (0 == strcmp("Any", s.c_str())) { p.AtomTyper = MCSAtomCompareAny; - else if (0 == strcmp("Elements", s.c_str())) + } else if (0 == strcmp("Elements", s.c_str())) { p.AtomTyper = MCSAtomCompareElements; - else if (0 == strcmp("Isotopes", s.c_str())) + } else if (0 == strcmp("Isotopes", s.c_str())) { p.AtomTyper = MCSAtomCompareIsotopes; - else if (0 == strcmp("AnyHeavy", s.c_str())) + } else if (0 == strcmp("AnyHeavy", s.c_str())) { p.AtomTyper = MCSAtomCompareAnyHeavyAtom; + } s = pt.get("BondCompare", "def"); - if (0 == strcmp("Any", s.c_str())) + if (0 == strcmp("Any", s.c_str())) { p.BondTyper = MCSBondCompareAny; - else if (0 == strcmp("Order", s.c_str())) + } else if (0 == strcmp("Order", s.c_str())) { p.BondTyper = MCSBondCompareOrder; - else if (0 == strcmp("OrderExact", s.c_str())) + } else if (0 == strcmp("OrderExact", s.c_str())) { p.BondTyper = MCSBondCompareOrderExact; + } p.InitialSeed = pt.get("InitialSeed", ""); } @@ -79,7 +81,9 @@ void parseMCSParametersJSON(const char* json, MCSParameters* params) { MCSResult findMCS(const std::vector& mols, const MCSParameters* params) { MCSParameters p; - if (nullptr == params) params = &p; + if (nullptr == params) { + params = &p; + } RDKit::FMCS::MaximumCommonSubgraph fmcs(params); return fmcs.find(mols); } @@ -153,7 +157,7 @@ MCSResult findMCS(const std::vector& mols, bool maximizeBonds, bool MCSProgressCallbackTimeout(const MCSProgressData& stat, const MCSParameters& params, void* userData) { RDUNUSED_PARAM(stat); - unsigned long long* t0 = (unsigned long long*)userData; + auto* t0 = (unsigned long long*)userData; unsigned long long t = nanoClock(); return t - *t0 <= params.Timeout * 1000000ULL; } @@ -199,11 +203,15 @@ static bool checkAtomChirality(const MCSAtomCompareParameters& p, bool MCSAtomCompareAny(const MCSAtomCompareParameters& p, const ROMol& mol1, unsigned int atom1, const ROMol& mol2, unsigned int atom2, void*) { - if (p.MatchChiralTag && !checkAtomChirality(p, mol1, atom1, mol2, atom2)) + if (p.MatchChiralTag && !checkAtomChirality(p, mol1, atom1, mol2, atom2)) { return false; - if (p.MatchFormalCharge && !checkAtomCharge(p, mol1, atom1, mol2, atom2)) + } + if (p.MatchFormalCharge && !checkAtomCharge(p, mol1, atom1, mol2, atom2)) { return false; - if (p.RingMatchesRingOnly) return checkRingMatch(p, mol1, atom1, mol2, atom2); + } + if (p.RingMatchesRingOnly) { + return checkRingMatch(p, mol1, atom1, mol2, atom2); + } return true; } @@ -213,14 +221,21 @@ bool MCSAtomCompareElements(const MCSAtomCompareParameters& p, const ROMol& mol2, unsigned int atom2, void*) { const Atom& a1 = *mol1.getAtomWithIdx(atom1); const Atom& a2 = *mol2.getAtomWithIdx(atom2); - if (a1.getAtomicNum() != a2.getAtomicNum()) return false; - if (p.MatchValences && a1.getTotalValence() != a2.getTotalValence()) + if (a1.getAtomicNum() != a2.getAtomicNum()) { return false; - if (p.MatchChiralTag && !checkAtomChirality(p, mol1, atom1, mol2, atom2)) + } + if (p.MatchValences && a1.getTotalValence() != a2.getTotalValence()) { return false; - if (p.MatchFormalCharge && !checkAtomCharge(p, mol1, atom1, mol2, atom2)) + } + if (p.MatchChiralTag && !checkAtomChirality(p, mol1, atom1, mol2, atom2)) { return false; - if (p.RingMatchesRingOnly) return checkRingMatch(p, mol1, atom1, mol2, atom2); + } + if (p.MatchFormalCharge && !checkAtomCharge(p, mol1, atom1, mol2, atom2)) { + return false; + } + if (p.RingMatchesRingOnly) { + return checkRingMatch(p, mol1, atom1, mol2, atom2); + } return true; } @@ -233,12 +248,18 @@ bool MCSAtomCompareIsotopes(const MCSAtomCompareParameters& p, // return false; const Atom& a1 = *mol1.getAtomWithIdx(atom1); const Atom& a2 = *mol2.getAtomWithIdx(atom2); - if (a1.getIsotope() != a2.getIsotope()) return false; - if (p.MatchChiralTag && !checkAtomChirality(p, mol1, atom1, mol2, atom2)) + if (a1.getIsotope() != a2.getIsotope()) { return false; - if (p.MatchFormalCharge && !checkAtomCharge(p, mol1, atom1, mol2, atom2)) + } + if (p.MatchChiralTag && !checkAtomChirality(p, mol1, atom1, mol2, atom2)) { return false; - if (p.RingMatchesRingOnly) return checkRingMatch(p, mol1, atom1, mol2, atom2); + } + if (p.MatchFormalCharge && !checkAtomCharge(p, mol1, atom1, mol2, atom2)) { + return false; + } + if (p.RingMatchesRingOnly) { + return checkRingMatch(p, mol1, atom1, mol2, atom2); + } return true; } @@ -300,7 +321,9 @@ static bool checkBondStereo(const MCSBondCompareParameters& p, Bond::BondStereo bs1 = b1->getStereo(); Bond::BondStereo bs2 = b2->getStereo(); if (b1->getBondType() == Bond::DOUBLE && b2->getBondType() == Bond::DOUBLE) { - if (bs1 > Bond::STEREOANY && !(bs2 > Bond::STEREOANY)) return false; + if (bs1 > Bond::STEREOANY && !(bs2 > Bond::STEREOANY)) { + return false; + } } return true; } @@ -308,8 +331,10 @@ static bool checkBondStereo(const MCSBondCompareParameters& p, static bool checkRingMatch(const MCSBondCompareParameters&, const ROMol&, unsigned int bond1, const ROMol& mol2, unsigned int bond2, void* v_ringMatchMatrixSet) { - if (!v_ringMatchMatrixSet) throw "v_ringMatchMatrixSet is NULL"; // never - FMCS::RingMatchTableSet* ringMatchMatrixSet = + if (!v_ringMatchMatrixSet) { + throw "v_ringMatchMatrixSet is NULL"; // never + } + auto* ringMatchMatrixSet = static_cast(v_ringMatchMatrixSet); const std::vector& ringsIdx1 = @@ -326,10 +351,12 @@ static bool checkRingMatch(const MCSBondCompareParameters&, const ROMol&, bool MCSBondCompareAny(const MCSBondCompareParameters& p, const ROMol& mol1, unsigned int bond1, const ROMol& mol2, unsigned int bond2, void* ud) { - if (p.MatchStereo && !checkBondStereo(p, mol1, bond1, mol2, bond2)) + if (p.MatchStereo && !checkBondStereo(p, mol1, bond1, mol2, bond2)) { return false; - if (p.RingMatchesRingOnly) + } + if (p.RingMatchesRingOnly) { return checkRingMatch(p, mol1, bond1, mol2, bond2, ud); + } return true; } @@ -342,10 +369,12 @@ bool MCSBondCompareOrder(const MCSBondCompareParameters& p, const ROMol& mol1, Bond::BondType t1 = b1->getBondType(); Bond::BondType t2 = b2->getBondType(); if (match.isEqual(t1, t2)) { - if (p.MatchStereo && !checkBondStereo(p, mol1, bond1, mol2, bond2)) + if (p.MatchStereo && !checkBondStereo(p, mol1, bond1, mol2, bond2)) { return false; - if (p.RingMatchesRingOnly) + } + if (p.RingMatchesRingOnly) { return checkRingMatch(p, mol1, bond1, mol2, bond2, ud); + } return true; } return false; @@ -360,10 +389,12 @@ bool MCSBondCompareOrderExact(const MCSBondCompareParameters& p, Bond::BondType t1 = b1->getBondType(); Bond::BondType t2 = b2->getBondType(); if (match.isEqual(t1, t2)) { - if (p.MatchStereo && !checkBondStereo(p, mol1, bond1, mol2, bond2)) + if (p.MatchStereo && !checkBondStereo(p, mol1, bond1, mol2, bond2)) { return false; - if (p.RingMatchesRingOnly) + } + if (p.RingMatchesRingOnly) { return checkRingMatch(p, mol1, bond1, mol2, bond2, ud); + } return true; } return false; @@ -387,19 +418,26 @@ inline static bool ringFusionCheck(const std::uint32_t c1[], const Bond* b = mol2.getBondBetweenAtoms(target[c2[boost::source(*it, query)]], target[c2[boost::target(*it, query)]]); - if (!b) continue; + if (!b) { + continue; + } unsigned int bi = b->getIdx(); - if (!ri2->numBondRings(bi)) continue; + if (!ri2->numBondRings(bi)) { + continue; + } for (i = 0; i < br2.size(); ++i) { - if (std::find(br2[i].begin(), br2[i].end(), bi) != br2[i].end()) + if (std::find(br2[i].begin(), br2[i].end(), bi) != br2[i].end()) { ++numMcsBondRings[i]; + } } } // nonFusedBonds stores the number of non-fused bonds // (i.e., which belong to a single ring) for each ring for (i = 0; i < br2.size(); ++i) { for (auto bi : br2[i]) { - if (ri2->numBondRings(bi) == 1) ++nonFusedBonds[i]; + if (ri2->numBondRings(bi) == 1) { + ++nonFusedBonds[i]; + } } } /* if a ring has at least one bond which is part of the MCS, @@ -417,14 +455,16 @@ inline static bool ringFusionCheck(const std::uint32_t c1[], if (numMcsBondRings[i] && numMcsBondRings[i] > (br2[i].size() - nonFusedBonds[i]) && numMcsBondRings[i] < nonFusedBonds[i]) { - if (p->BondCompareParameters.CompleteRingsOnly) + if (p->BondCompareParameters.CompleteRingsOnly) { return true; - else + } else { continue; + } } if (numMcsBondRings[i] == nonFusedBonds[i] && - numMcsBondRings[i] < br2[i].size()) + numMcsBondRings[i] < br2[i].size()) { missingFusedBond = true; + } } /* If we found that the MCS is missing a fused bond, we may need to check against the smaller molecule as well. @@ -453,8 +493,9 @@ inline static bool ringFusionCheck(const std::uint32_t c1[], if (missingFusedBond ^ p->BondCompareParameters.MatchFusedRingsStrict) { // if we are in permissive mode we allow one of the molecules to miss // fused bonds, but not both. In strict mode we allow neither. - if (!p->BondCompareParameters.MatchFusedRingsStrict) + if (!p->BondCompareParameters.MatchFusedRingsStrict) { missingFusedBond = false; + } const RingInfo* ri1 = mol1.getRingInfo(); const VECT_INT_VECT& br1 = ri1->bondRings(); std::set mcsRingBondIdxSet; @@ -463,8 +504,9 @@ inline static bool ringFusionCheck(const std::uint32_t c1[], const Bond* b = mol1.getBondBetweenAtoms(query[c1[boost::source(*it, query)]], query[c1[boost::target(*it, query)]]); - if (b && ri1->numBondRings(b->getIdx())) + if (b && ri1->numBondRings(b->getIdx())) { mcsRingBondIdxSet.insert(b->getIdx()); + } } for (i = 0; i < br1.size(); ++i) { size_t mcsBonds = 0; @@ -475,16 +517,22 @@ inline static bool ringFusionCheck(const std::uint32_t c1[], // and how many bonds in each ring belong to a single ring (nonFusedBonds) for (auto bi : br1[i]) { bool isFused = (ri1->numBondRings(bi) > 1); - if (!isFused) ++nonFusedBonds; + if (!isFused) { + ++nonFusedBonds; + } if (std::find(mcsRingBondIdxSet.begin(), mcsRingBondIdxSet.end(), bi) != mcsRingBondIdxSet.end()) { ++mcsBonds; - if (isFused) ++mcsFusedBonds; + if (isFused) { + ++mcsFusedBonds; + } } } if (!p->BondCompareParameters.CompleteRingsOnly && - mcsBonds > mcsFusedBonds && mcsBonds - mcsFusedBonds < nonFusedBonds) + mcsBonds > mcsFusedBonds && + mcsBonds - mcsFusedBonds < nonFusedBonds) { continue; + } // if the ring is part of the MCS, and we found more bonds than the fused // ones (i.e., the ring is not simply adjacent to an MCS ring) but less // than the bonds which are part of this ring, then some fused bond is @@ -505,11 +553,13 @@ bool FinalMatchCheckFunction(const std::uint32_t c1[], const std::uint32_t c2[], const MCSParameters* p) { if ((p->BondCompareParameters.MatchFusedRings || p->BondCompareParameters.MatchFusedRingsStrict) && - !ringFusionCheck(c1, c2, mol1, query, mol2, target, p)) + !ringFusionCheck(c1, c2, mol1, query, mol2, target, p)) { return false; + } if (p->AtomCompareParameters.MatchChiralTag && - !FinalChiralityCheckFunction(c1, c2, mol1, query, mol2, target, p)) + !FinalChiralityCheckFunction(c1, c2, mol1, query, mol2, target, p)) { return false; + } return true; } @@ -531,10 +581,14 @@ bool FinalChiralityCheckFunction(const std::uint32_t c1[], // ???: non chiral query atoms ARE ALLOWED TO MATCH to Chiral target atoms // (see test for issue 481) if (a1.getDegree() < 3 || //#688: doesn't deal with "explicit" Hs properly - !(ac1 == Atom::CHI_TETRAHEDRAL_CW || ac1 == Atom::CHI_TETRAHEDRAL_CCW)) + !(ac1 == Atom::CHI_TETRAHEDRAL_CW || + ac1 == Atom::CHI_TETRAHEDRAL_CCW)) { continue; // skip non chiral center QUERY atoms - if (!(ac2 == Atom::CHI_TETRAHEDRAL_CW || ac2 == Atom::CHI_TETRAHEDRAL_CCW)) + } + if (!(ac2 == Atom::CHI_TETRAHEDRAL_CW || + ac2 == Atom::CHI_TETRAHEDRAL_CCW)) { return false; + } //-------------------- /* More accurate check: @@ -557,16 +611,19 @@ bool FinalChiralityCheckFunction(const std::uint32_t c1[], if (a1Degree > a2.getDegree()) { //#688 was != . // FIX issue 631 // printf("atoms Degree (%u, %u) %u [%u], %u\n", query[c1[i]], // target[c2[i]], a1Degree, a1.getDegree(), a2.getDegree()); - if (1 == a1Degree && a1.getDegree() == a2.getDegree()) + if (1 == a1Degree && a1.getDegree() == a2.getDegree()) { continue; // continue to grow the seed - else + } else { return false; + } } INT_LIST qOrder; for (unsigned int j = 0; j < qna && qOrder.size() != a1Degree; ++j) { const Bond* qB = mol1.getBondBetweenAtoms(query[c1[i]], query[c1[j]]); - if (qB) qOrder.push_back(qB->getIdx()); + if (qB) { + qOrder.push_back(qB->getIdx()); + } } //#688 @@ -576,8 +633,9 @@ bool FinalChiralityCheckFunction(const std::uint32_t c1[], boost::tie(dbeg, dend) = mol1.getAtomBonds(&a1); for (; dbeg != dend; dbeg++) { int dbidx = mol1[*dbeg]->getIdx(); - if (std::find(qOrder.begin(), qOrder.end(), dbidx) != qOrder.end()) + if (std::find(qOrder.begin(), qOrder.end(), dbidx) != qOrder.end()) { qmoOrder.push_back(dbidx); + } // else // qmoOrder.push_back(-1); } @@ -588,7 +646,9 @@ bool FinalChiralityCheckFunction(const std::uint32_t c1[], INT_LIST mOrder; for (unsigned int j = 0; j < qna && mOrder.size() != a2.getDegree(); ++j) { const Bond* mB = mol2.getBondBetweenAtoms(target[c2[i]], target[c2[j]]); - if (mB) mOrder.push_back(mB->getIdx()); + if (mB) { + mOrder.push_back(mB->getIdx()); + } } //#688 @@ -600,10 +660,11 @@ bool FinalChiralityCheckFunction(const std::uint32_t c1[], boost::tie(dbeg, dend) = mol2.getAtomBonds(&a2); for (; dbeg != dend; dbeg++) { int dbidx = mol2[*dbeg]->getIdx(); - if (std::find(mOrder.begin(), mOrder.end(), dbidx) != mOrder.end()) + if (std::find(mOrder.begin(), mOrder.end(), dbidx) != mOrder.end()) { moOrder.push_back(dbidx); - else + } else { moOrder.push_back(-1); + } } int mPermCount = // was: a2.getPerturbationOrder(mOrder); @@ -613,36 +674,44 @@ bool FinalChiralityCheckFunction(const std::uint32_t c1[], if ((qPermCount % 2 == mPermCount % 2 && a1.getChiralTag() != a2.getChiralTag()) || (qPermCount % 2 != mPermCount % 2 && - a1.getChiralTag() == a2.getChiralTag())) + a1.getChiralTag() == a2.getChiralTag())) { return false; + } } // check double bonds ONLY (why ???) const unsigned int qnb = boost::num_edges(query); std::map qMap; - for (unsigned int j = 0; j < qna; ++j) qMap[query[c1[j]]] = j; + for (unsigned int j = 0; j < qna; ++j) { + qMap[query[c1[j]]] = j; + } RDKit::FMCS::Graph::BOND_ITER_PAIR bpIter = boost::edges(query); RDKit::FMCS::Graph::EDGE_ITER bIter = bpIter.first; for (unsigned int i = 0; i < qnb; i++, ++bIter) { const Bond* qBnd = mol1.getBondWithIdx(query[*bIter]); if (qBnd->getBondType() != Bond::DOUBLE || - qBnd->getStereo() <= Bond::STEREOANY) + qBnd->getStereo() <= Bond::STEREOANY) { continue; + } // don't think this can actually happen, but check to be sure: - if (qBnd->getStereoAtoms().size() != 2) // MUST check it in the seed, not - // in full query molecule, but - // never happens !!! + if (qBnd->getStereoAtoms().size() != 2) { // MUST check it in the seed, not + // in full query molecule, but + // never happens !!! continue; + } const Bond* mBnd = mol2.getBondBetweenAtoms(target[c2[qMap[qBnd->getBeginAtomIdx()]]], target[c2[qMap[qBnd->getEndAtomIdx()]]]); CHECK_INVARIANT(mBnd, "Matching bond not found"); if (mBnd->getBondType() != Bond::DOUBLE || - mBnd->getStereo() <= Bond::STEREOANY) + mBnd->getStereo() <= Bond::STEREOANY) { continue; + } // don't think this can actually happen, but check to be sure: - if (mBnd->getStereoAtoms().size() != 2) continue; + if (mBnd->getStereoAtoms().size() != 2) { + continue; + } unsigned int end1Matches = 0; unsigned int end2Matches = 0; @@ -650,29 +719,35 @@ bool FinalChiralityCheckFunction(const std::uint32_t c1[], rdcast(mBnd->getBeginAtomIdx())) { // query Begin == mol Begin if (target[c2[qMap[qBnd->getStereoAtoms()[0]]]] == - rdcast(mBnd->getStereoAtoms()[0])) + rdcast(mBnd->getStereoAtoms()[0])) { end1Matches = 1; + } if (target[c2[qMap[qBnd->getStereoAtoms()[1]]]] == - rdcast(mBnd->getStereoAtoms()[1])) + rdcast(mBnd->getStereoAtoms()[1])) { end2Matches = 1; + } } else { // query End == mol Begin if (target[c2[qMap[qBnd->getStereoAtoms()[0]]]] == - rdcast(mBnd->getStereoAtoms()[1])) + rdcast(mBnd->getStereoAtoms()[1])) { end1Matches = 1; + } if (target[c2[qMap[qBnd->getStereoAtoms()[1]]]] == - rdcast(mBnd->getStereoAtoms()[0])) + rdcast(mBnd->getStereoAtoms()[0])) { end2Matches = 1; + } } // std::cerr<<" bnd: "<getIdx()<<":"<getStereo()<<" - // "<getIdx()<<":"<getStereo()<<" -- "<getStereo() == qBnd->getStereo() && - (end1Matches + end2Matches) == 1) + (end1Matches + end2Matches) == 1) { return false; + } if (mBnd->getStereo() != qBnd->getStereo() && - (end1Matches + end2Matches) != 1) + (end1Matches + end2Matches) != 1) { return false; + } } return true; } @@ -688,95 +763,118 @@ bool FinalChiralityCheckFunction_1(const short unsigned c1[], for (unsigned int i = 0; i < qna; ++i) { const Atom& a1 = *mol1.getAtomWithIdx(query[c1[i]]); Atom::ChiralType ac1 = a1.getChiralTag(); - if (!(ac1 == Atom::CHI_TETRAHEDRAL_CW || ac1 == Atom::CHI_TETRAHEDRAL_CCW)) + if (!(ac1 == Atom::CHI_TETRAHEDRAL_CW || + ac1 == Atom::CHI_TETRAHEDRAL_CCW)) { continue; // skip non chiral center query atoms + } const Atom& a2 = *mol2.getAtomWithIdx(target[c2[i]]); Atom::ChiralType ac2 = a2.getChiralTag(); - if (!(ac2 == Atom::CHI_TETRAHEDRAL_CW || ac2 == Atom::CHI_TETRAHEDRAL_CCW)) + if (!(ac2 == Atom::CHI_TETRAHEDRAL_CW || + ac2 == Atom::CHI_TETRAHEDRAL_CCW)) { continue; // skip non chiral center TARGET atoms even if query atom is + } // chiral //// return false; // both atoms are chiral: const unsigned a1Degree = boost::out_degree(c1[i], query); // a1.getDegree(); - if (a1Degree != a2.getDegree()) // number of all connected atoms in seed + if (a1Degree != a2.getDegree()) { // number of all connected atoms in seed return false; // ??? + } INT_LIST qOrder; for (unsigned int j = 0; j < qna && qOrder.size() != a1Degree; ++j) { const Bond* qB = mol1.getBondBetweenAtoms(query[c1[i]], query[c1[j]]); - if (qB) qOrder.push_back(qB->getIdx()); + if (qB) { + qOrder.push_back(qB->getIdx()); + } } int qPermCount = a1.getPerturbationOrder(qOrder); INT_LIST mOrder; for (unsigned int j = 0; j < qna && mOrder.size() != a2.getDegree(); ++j) { const Bond* mB = mol2.getBondBetweenAtoms(target[c2[i]], target[c2[j]]); - if (mB) mOrder.push_back(mB->getIdx()); + if (mB) { + mOrder.push_back(mB->getIdx()); + } } int mPermCount = a2.getPerturbationOrder(mOrder); if ((qPermCount % 2 == mPermCount % 2 && a1.getChiralTag() != a2.getChiralTag()) || (qPermCount % 2 != mPermCount % 2 && - a1.getChiralTag() == a2.getChiralTag())) + a1.getChiralTag() == a2.getChiralTag())) { return false; + } } // check double bonds ONLY (why ???) const unsigned int qnb = boost::num_edges(query); std::map qMap; - for (unsigned int j = 0; j < qna; ++j) qMap[query[c1[j]]] = j; + for (unsigned int j = 0; j < qna; ++j) { + qMap[query[c1[j]]] = j; + } RDKit::FMCS::Graph::BOND_ITER_PAIR bpIter = boost::edges(query); RDKit::FMCS::Graph::EDGE_ITER bIter = bpIter.first; for (unsigned int i = 0; i < qnb; i++, ++bIter) { const Bond* qBnd = mol1.getBondWithIdx(query[*bIter]); if (qBnd->getBondType() != Bond::DOUBLE || - qBnd->getStereo() <= Bond::STEREOANY) + qBnd->getStereo() <= Bond::STEREOANY) { continue; + } // don't think this can actually happen, but check to be sure: - if (qBnd->getStereoAtoms().size() != 2) // MUST check it in the seed, not - // in full query molecule, but - // never happens !!! + if (qBnd->getStereoAtoms().size() != 2) { // MUST check it in the seed, not + // in full query molecule, but + // never happens !!! continue; + } const Bond* mBnd = mol2.getBondBetweenAtoms(target[c2[qMap[qBnd->getBeginAtomIdx()]]], target[c2[qMap[qBnd->getEndAtomIdx()]]]); CHECK_INVARIANT(mBnd, "Matching bond not found"); if (mBnd->getBondType() != Bond::DOUBLE || - mBnd->getStereo() <= Bond::STEREOANY) + mBnd->getStereo() <= Bond::STEREOANY) { continue; + } // don't think this can actually happen, but check to be sure: - if (mBnd->getStereoAtoms().size() != 2) continue; + if (mBnd->getStereoAtoms().size() != 2) { + continue; + } unsigned int end1Matches = 0; unsigned int end2Matches = 0; if (target[c2[qMap[qBnd->getBeginAtomIdx()]]] == mBnd->getBeginAtomIdx()) { // query Begin == mol Begin if (target[c2[qMap[qBnd->getStereoAtoms()[0]]]] == - rdcast(mBnd->getStereoAtoms()[0])) + rdcast(mBnd->getStereoAtoms()[0])) { end1Matches = 1; + } if (target[c2[qMap[qBnd->getStereoAtoms()[1]]]] == - rdcast(mBnd->getStereoAtoms()[1])) + rdcast(mBnd->getStereoAtoms()[1])) { end2Matches = 1; + } } else { // query End == mol Begin if (target[c2[qMap[qBnd->getStereoAtoms()[0]]]] == - rdcast(mBnd->getStereoAtoms()[1])) + rdcast(mBnd->getStereoAtoms()[1])) { end1Matches = 1; + } if (target[c2[qMap[qBnd->getStereoAtoms()[1]]]] == - rdcast(mBnd->getStereoAtoms()[0])) + rdcast(mBnd->getStereoAtoms()[0])) { end2Matches = 1; + } } // std::cerr<<" bnd: "<getIdx()<<":"<getStereo()<<" - // "<getIdx()<<":"<getStereo()<<" -- "<getStereo() == qBnd->getStereo() && - (end1Matches + end2Matches) == 1) + (end1Matches + end2Matches) == 1) { return false; + } if (mBnd->getStereo() != qBnd->getStereo() && - (end1Matches + end2Matches) != 1) + (end1Matches + end2Matches) != 1) { return false; + } } return true; } diff --git a/Code/GraphMol/FMCS/MaximumCommonSubgraph.cpp b/Code/GraphMol/FMCS/MaximumCommonSubgraph.cpp old mode 100755 new mode 100644 index 6ae51d940..a9a589094 --- a/Code/GraphMol/FMCS/MaximumCommonSubgraph.cpp +++ b/Code/GraphMol/FMCS/MaximumCommonSubgraph.cpp @@ -41,8 +41,9 @@ MaximumCommonSubgraph::MaximumCommonSubgraph(const MCSParameters* params) { Parameters.BondCompareParameters.MatchFusedRingsStrict) && nullptr == Parameters.FinalMatchChecker) { Parameters.FinalMatchChecker = FinalMatchCheckFunction; - if (Parameters.AtomCompareParameters.MatchChiralTag) + if (Parameters.AtomCompareParameters.MatchChiralTag) { Parameters.BondCompareParameters.MatchStereo = true; + } } To = nanoClock(); } @@ -84,30 +85,34 @@ void MaximumCommonSubgraph::init() { if (!userData // predefined functor - compute RingMatchTable for all targets && (Parameters.BondCompareParameters.CompleteRingsOnly || Parameters.BondCompareParameters.RingMatchesRingOnly || - Parameters.AtomCompareParameters.RingMatchesRingOnly)) + Parameters.AtomCompareParameters.RingMatchesRingOnly)) { RingMatchTables.computeRingMatchTable(QueryMolecule, QueryMolecule, Parameters); + } // fill out match tables nq = QueryMolecule->getNumAtoms(); QueryAtomMatchTable.resize(nq, nq); - for (size_t aj = 0; aj < nq; aj++) - for (size_t ai = 0; ai < nq; ai++) + for (size_t aj = 0; aj < nq; aj++) { + for (size_t ai = 0; ai < nq; ai++) { QueryAtomMatchTable.set( ai, aj, Parameters.AtomTyper(Parameters.AtomCompareParameters, *QueryMolecule, ai, *QueryMolecule, aj, Parameters.CompareFunctionsUserData)); - + } + } nq = QueryMolecule->getNumBonds(); QueryBondMatchTable.resize(nq, nq); - for (size_t aj = 0; aj < nq; aj++) - for (size_t ai = 0; ai < nq; ai++) + for (size_t aj = 0; aj < nq; aj++) { + for (size_t ai = 0; ai < nq; ai++) { QueryBondMatchTable.set( ai, aj, Parameters.BondTyper(Parameters.BondCompareParameters, *QueryMolecule, ai, *QueryMolecule, aj, Parameters.CompareFunctionsUserData)); + } + } // Compute label values based on current functor and parameters for code // Morgan correct computation. unsigned currentLabelValue = 1; @@ -116,28 +121,28 @@ void MaximumCommonSubgraph::init() { QueryAtomLabels.resize(nq); for (size_t ai = 0; ai < nq; ai++) { if (MCSAtomCompareAny == - Parameters - .AtomTyper) // predefined functor without atom compare parameters + Parameters.AtomTyper) { // predefined functor without atom compare + // parameters QueryAtomLabels[ai] = 1; - else { + } else { const Atom* atom = QueryMolecule->getAtomWithIdx(ai); if (MCSAtomCompareElements == - Parameters - .AtomTyper) // predefined functor without atom compare parameters + Parameters.AtomTyper) { // predefined functor without atom compare + // parameters QueryAtomLabels[ai] = atom->getAtomicNum() | (Parameters.AtomCompareParameters.MatchValences ? (atom->getTotalValence() >> 8) : 0); - else if (MCSAtomCompareIsotopes == - Parameters.AtomTyper) // predefined functor without atom compare - // parameters + } else if (MCSAtomCompareIsotopes == + Parameters.AtomTyper) { // predefined functor without atom + // compare parameters QueryAtomLabels[ai] = atom->getAtomicNum() | (atom->getIsotope() >> 8) | (Parameters.AtomCompareParameters.MatchValences ? (atom->getTotalValence() >> 16) : 0); - else { // custom user defined functor + } else { // custom user defined functor QueryAtomLabels[ai] = NotSet; - for (auto& label : labels) + for (auto& label : labels) { if (Parameters.AtomTyper(Parameters.AtomCompareParameters, *QueryMolecule, label.ItemIndex, *QueryMolecule, ai, @@ -145,6 +150,7 @@ void MaximumCommonSubgraph::init() { QueryAtomLabels[ai] = label.Value; break; } + } if (NotSet == QueryAtomLabels[ai]) { // not found -> create new label QueryAtomLabels[ai] = ++currentLabelValue; labels.push_back(LabelDefinition(ai, currentLabelValue)); @@ -164,32 +170,33 @@ void MaximumCommonSubgraph::init() { ring = RingMatchTables.isQueryBondInRing(aj) ? 0 : 1; // is bond in ring } if (MCSBondCompareAny == - Parameters - .BondTyper) // predefined functor without atom compare parameters + Parameters.BondTyper) { // predefined functor without atom compare + // parameters QueryBondLabels[aj] = 1 | (ring >> 8); - else if (MCSBondCompareOrderExact == - Parameters - .BondTyper) // predefined functor without compare parameters + } else if (MCSBondCompareOrderExact == + Parameters.BondTyper) { // predefined functor without compare + // parameters QueryBondLabels[aj] = (bond->getBondType() + 1) | (ring >> 8); - else if (MCSBondCompareOrder == - Parameters - .BondTyper) { // predefined functor, ignore Aromatization + } else if (MCSBondCompareOrder == + Parameters + .BondTyper) { // predefined functor, ignore Aromatization unsigned order = bond->getBondType(); if (Bond::AROMATIC == order || - Bond::ONEANDAHALF == order) // ignore Aromatization + Bond::ONEANDAHALF == order) { // ignore Aromatization order = Bond::SINGLE; - else if (Bond::TWOANDAHALF == order) + } else if (Bond::TWOANDAHALF == order) { order = Bond::DOUBLE; - else if (Bond::THREEANDAHALF == order) + } else if (Bond::THREEANDAHALF == order) { order = Bond::TRIPLE; - else if (Bond::FOURANDAHALF == order) + } else if (Bond::FOURANDAHALF == order) { order = Bond::QUADRUPLE; - else if (Bond::FIVEANDAHALF == order) + } else if (Bond::FIVEANDAHALF == order) { order = Bond::QUINTUPLE; + } QueryBondLabels[aj] = (order + 1) | (ring >> 8); } else { // custom user defined functor QueryBondLabels[aj] = NotSet; - for (auto& label : labels) + for (auto& label : labels) { if (Parameters.BondTyper(Parameters.BondCompareParameters, *QueryMolecule, label.ItemIndex, *QueryMolecule, aj, @@ -197,6 +204,7 @@ void MaximumCommonSubgraph::init() { QueryBondLabels[aj] = label.Value; break; } + } if (NotSet == QueryAtomLabels[aj]) { // not found -> create new label QueryBondLabels[aj] = ++currentLabelValue; labels.push_back(LabelDefinition(aj, currentLabelValue)); @@ -240,26 +248,28 @@ void MaximumCommonSubgraph::init() { size_t nt = (*it)->getNumAtoms(); Targets[i].AtomMatchTable.resize(nq, nt); - for (size_t aj = 0; aj < nt; aj++) - for (size_t ai = 0; ai < nq; ai++) + for (size_t aj = 0; aj < nt; aj++) { + for (size_t ai = 0; ai < nq; ai++) { Targets[i].AtomMatchTable.set( ai, aj, Parameters.AtomTyper(Parameters.AtomCompareParameters, *QueryMolecule, ai, *Targets[i].Molecule, aj, Parameters.CompareFunctionsUserData)); - + } + } nq = QueryMolecule->getNumBonds(); nt = (*it)->getNumBonds(); Targets[i].BondMatchTable.resize(nq, nt); - for (size_t aj = 0; aj < nt; aj++) - for (size_t ai = 0; ai < nq; ai++) + for (size_t aj = 0; aj < nt; aj++) { + for (size_t ai = 0; ai < nq; ai++) { Targets[i].BondMatchTable.set( ai, aj, Parameters.BondTyper(Parameters.BondCompareParameters, *QueryMolecule, ai, *Targets[i].Molecule, aj, Parameters.CompareFunctionsUserData)); + } + } } - Parameters.CompareFunctionsUserData = userData; // restore } @@ -269,17 +279,23 @@ struct QueryRings { QueryRings(const ROMol* query) : BondRings(query->getNumBonds()), AtomRings(query->getNumAtoms()) { - { - for (unsigned int& BondRing : BondRings) BondRing = 0; - const RingInfo::VECT_INT_VECT& rings = query->getRingInfo()->bondRings(); - for (const auto& ring : rings) - for (int ri : ring) ++BondRings[ri]; + for (unsigned int& BondRing : BondRings) { + BondRing = 0; } - { - for (unsigned int& AtomRing : AtomRings) AtomRing = 0; - const RingInfo::VECT_INT_VECT& rings = query->getRingInfo()->atomRings(); - for (const auto& ring : rings) - for (int ri : ring) ++AtomRings[ri]; + const RingInfo::VECT_INT_VECT& brings = query->getRingInfo()->bondRings(); + for (const auto& ring : brings) { + for (int ri : ring) { + ++BondRings[ri]; + } + } + for (unsigned int& AtomRing : AtomRings) { + AtomRing = 0; + } + const RingInfo::VECT_INT_VECT& arings = query->getRingInfo()->atomRings(); + for (const auto& ring : arings) { + for (int ri : ring) { + ++AtomRings[ri]; + } } } @@ -290,7 +306,7 @@ struct QueryRings { inline unsigned getNumberRings(const Atom* atom) const { return AtomRings[atom->getIdx()]; } -}; +}; // namespace RDKit struct WeightedBond { const Bond* BondPtr; @@ -299,9 +315,15 @@ struct WeightedBond { WeightedBond(const Bond* bond, const QueryRings& r) : BondPtr(bond), Weight(0) { // score ((bond.is_in_ring + atom1.is_in_ring + atom2.is_in_ring) - if (r.getNumberRings(bond)) Weight += 1; - if (r.getNumberRings(bond->getBeginAtom())) Weight += 1; - if (r.getNumberRings(bond->getEndAtom())) Weight += 1; + if (r.getNumberRings(bond)) { + Weight += 1; + } + if (r.getNumberRings(bond->getBeginAtom())) { + Weight += 1; + } + if (r.getNumberRings(bond->getEndAtom())) { + Weight += 1; + } } bool operator<(const WeightedBond& r) { return Weight >= r.Weight; // sort in Z-A order (Rings first) @@ -309,7 +331,8 @@ struct WeightedBond { }; void MaximumCommonSubgraph::makeInitialSeeds() { - // build a set of initial seeds as "all" single bonds from query molecule + // build a set of initial seeds as "all" single bonds from query + // molecule std::vector excludedBonds(QueryMolecule->getNumBonds(), false); Seeds.clear(); @@ -318,8 +341,8 @@ void MaximumCommonSubgraph::makeInitialSeeds() { if (!Parameters.InitialSeed.empty()) { // make user defined seed std::auto_ptr initialSeedMolecule( (const ROMol*)SmartsToMol(Parameters.InitialSeed)); - // make a set of of seed as indices and pointers to current query molecule - // items based on matching results + // make a set of of seed as indices and pointers to current query + // molecule items based on matching results std::vector matching_substructs; SubstructMatch(*QueryMolecule, *initialSeedMolecule, matching_substructs); // loop throw all fragments of Query matched to initial seed @@ -343,8 +366,8 @@ void MaximumCommonSubgraph::makeInitialSeeds() { seed.addAtom(QueryMolecule->getAtomWithIdx(qai)); initialSeedToQueryAtom[sai] = qai; } - // add all bonds (existed in initial seed !!!) between all matched atoms - // in query + // add all bonds (existed in initial seed !!!) between all matched + // atoms in query for (const auto& msb : *ms) { const Atom* atom = initialSeedMolecule->getAtomWithIdx(msb.first); ROMol::OEDGE_ITER beg, end; @@ -366,22 +389,24 @@ void MaximumCommonSubgraph::makeInitialSeeds() { } seed.computeRemainingSize(*QueryMolecule); - if (checkIfMatchAndAppend(seed)) + if (checkIfMatchAndAppend(seed)) { QueryMoleculeMatchedBonds = seed.getNumBonds(); + } } } else { // create a set of seeds from each query bond // R1 additional performance OPTIMISATION // if(Parameters.BondCompareParameters.CompleteRingsOnly) - // disable all mismatched rings, and do not generate initial seeds from such - // disabled bonds + // disable all mismatched rings, and do not generate initial seeds + // from such disabled bonds // for( rings .....) for(i......) // if(mismatched) excludedBonds[i.......] = true; QueryRings r(QueryMolecule); std::vector wb; wb.reserve(QueryMolecule->getNumBonds()); for (RWMol::ConstBondIterator bi = QueryMolecule->beginBonds(); - bi != QueryMolecule->endBonds(); bi++) + bi != QueryMolecule->endBonds(); bi++) { wb.push_back(WeightedBond(*bi, r)); + } for (std::vector::const_iterator bi = wb.begin(); bi != wb.end(); bi++) { @@ -408,13 +433,15 @@ void MaximumCommonSubgraph::makeInitialSeeds() { if (checkIfMatchAndAppend(seed)) { ++QueryMoleculeMatchedBonds; } else { - // optionally remove all such bonds from all targets TOPOLOGY where it - // exists. + // optionally remove all such bonds from all targets TOPOLOGY + // where it exists. //.......... - // disable (mark as already processed) mismatched bond in all seeds - for (auto& Seed : Seeds) + // disable (mark as already processed) mismatched bond in all + // seeds + for (auto& Seed : Seeds) { Seed.ExcludedBonds[bi->BondPtr->getIdx()] = true; + } #ifdef VERBOSE_STATISTICS_ON ++VerboseStatistics.MismatchedInitialSeed; @@ -435,7 +462,9 @@ void MaximumCommonSubgraph::makeInitialSeeds() { } } } - if (matched >= ThresholdCount) ++QueryMoleculeMatchedAtoms; + if (matched >= ThresholdCount) { + ++QueryMoleculeMatchedAtoms; + } } } @@ -456,10 +485,14 @@ void _DFS(const Graph& g, const boost::dynamic_bitset<>& ringBonds, } // find the other vertex: unsigned oVertex = boost::source(*(bonds.first), g); - if (oVertex == vertex) oVertex = boost::target((*bonds.first), g); + if (oVertex == vertex) { + oVertex = boost::target((*bonds.first), g); + } ++bonds.first; - if (oVertex == fromVertex) continue; + if (oVertex == fromVertex) { + continue; + } if (colors[oVertex] == 1) { // closing a cycle for (auto ai = apath.rbegin(); ai != apath.rend() && *ai != oVertex; @@ -482,24 +515,31 @@ void _DFS(const Graph& g, const boost::dynamic_bitset<>& ringBonds, } bool checkIfRingsAreClosed(const Seed& fs) { - if (!fs.MoleculeFragment.Bonds.size()) return true; + if (!fs.MoleculeFragment.Bonds.size()) { + return true; + } bool res = true; const auto& om = fs.MoleculeFragment.Bonds[0]->getOwningMol(); const auto ri = om.getRingInfo(); boost::dynamic_bitset<> ringBonds(om.getNumBonds()); for (const auto bond : fs.MoleculeFragment.Bonds) { - if (ri->numBondRings(bond->getIdx())) ringBonds.set(bond->getIdx()); + if (ri->numBondRings(bond->getIdx())) { + ringBonds.set(bond->getIdx()); + } } boost::dynamic_bitset<> openBonds = ringBonds; if (openBonds.any()) { std::vector colors(om.getNumAtoms()); for (unsigned bi = 0; bi < openBonds.size(); ++bi) { - if (!openBonds[bi]) continue; + if (!openBonds[bi]) { + continue; + } std::pair bonds = boost::edges(fs.Topology); - while (bonds.first != bonds.second && fs.Topology[*(bonds.first)] != bi) + while (bonds.first != bonds.second && fs.Topology[*(bonds.first)] != bi) { ++bonds.first; + } CHECK_INVARIANT(bonds.first != bonds.second, "bond not found"); unsigned startVertex = boost::source(*(bonds.first), fs.Topology); std::vector apath = {startVertex}; @@ -515,13 +555,15 @@ bool checkIfRingsAreClosed(const Seed& fs) { bool MaximumCommonSubgraph::growSeeds() { bool mcsFound = false; bool canceled = false; - unsigned steps = 99999; // steps from last progress callback call. call it - // immediately in the beginning + unsigned steps = 99999; // steps from last progress callback call. call + // it immediately in the beginning - // Find MCS -- SDF Seed growing OPTIMISATION (it works in 3 times faster) + // Find MCS -- SDF Seed growing OPTIMISATION (it works in 3 times + // faster) while (!Seeds.empty()) { - if (getMaxNumberBonds() == QueryMoleculeMatchedBonds) // MCS == Query + if (getMaxNumberBonds() == QueryMoleculeMatchedBonds) { // MCS == Query break; + } ++steps; #ifdef VERBOSE_STATISTICS_ON VerboseStatistics.TotalSteps++; @@ -571,8 +613,9 @@ bool MaximumCommonSubgraph::growSeeds() { } } } - if (NotSet == si->GrowingStage) // finished + if (NotSet == si->GrowingStage) { // finished Seeds.erase(si); + } if (Parameters.ProgressCallback) { steps = 0; Stat.NumAtoms = getMaxNumberAtoms(); @@ -585,8 +628,8 @@ bool MaximumCommonSubgraph::growSeeds() { } } - if (mcsFound) { // postponed copy of current set of molecules for threshold < - // 1. + if (mcsFound) { // postponed copy of current set of molecules for + // threshold < 1. McsIdx.QueryMolecule = QueryMolecule; McsIdx.Targets = Targets; } @@ -603,8 +646,8 @@ typedef std::vector AtomMatchSet; std::pair MaximumCommonSubgraph::generateResultSMARTSAndQueryMol( const MCS& mcsIdx) const { - // match the result MCS with all targets to check if it is exact match or - // template + // match the result MCS with all targets to check if it is exact match + // or template Seed seed; // result MCS seed.ExcludedBonds.resize(mcsIdx.QueryMolecule->getNumBonds(), false); std::vector atomMatchResult(mcsIdx.Targets.size()); @@ -618,7 +661,9 @@ MaximumCommonSubgraph::generateResultSMARTSAndQueryMol( atomIdxMap[atom->getIdx()] = seed.getNumAtoms(); seed.addAtom(atom); } - for (auto bond : mcsIdx.Bonds) seed.addBond(bond); + for (auto bond : mcsIdx.Bonds) { + seed.addBond(bond); + } unsigned itarget = 0; for (auto tag = mcsIdx.Targets.begin(); tag != mcsIdx.Targets.end(); @@ -627,7 +672,9 @@ MaximumCommonSubgraph::generateResultSMARTSAndQueryMol( bool target_matched = SubstructMatchCustomTable( tag->Topology, *tag->Molecule, seed.Topology, *QueryMolecule, tag->AtomMatchTable, tag->BondMatchTable, &Parameters, &match); - if (!target_matched) continue; + if (!target_matched) { + continue; + } atomMatchResult[itarget].resize(seed.getNumAtoms()); for (match_V_t::const_iterator mit = match.begin(); mit != match.end(); mit++) { @@ -636,9 +683,10 @@ MaximumCommonSubgraph::generateResultSMARTSAndQueryMol( atomMatchResult[itarget][ai].TargetAtomIdx = tag->Topology[mit->second]; const Atom* ta = tag->Molecule->getAtomWithIdx(tag->Topology[mit->second]); - if (ta && - ta->getAtomicNum() != seed.MoleculeFragment.Atoms[ai]->getAtomicNum()) + if (ta && ta->getAtomicNum() != + seed.MoleculeFragment.Atoms[ai]->getAtomicNum()) { atomMatchSet[ai][ta->getAtomicNum()] = ta; // add + } } // AND BUILD BOND MATCH INFO unsigned bi = 0; @@ -649,15 +697,16 @@ MaximumCommonSubgraph::generateResultSMARTSAndQueryMol( unsigned ti = atomMatchResult[itarget][i].TargetAtomIdx; unsigned tj = atomMatchResult[itarget][j].TargetAtomIdx; const Bond* tb = tag->Molecule->getBondBetweenAtoms(ti, tj); - if (tb && (*bond)->getBondType() != tb->getBondType()) + if (tb && (*bond)->getBondType() != tb->getBondType()) { bondMatchSet[bi][tb->getBondType()] = tb; // add + } } } // Generate result's SMARTS // create molecule from MCS for MolToSmarts() - RWMol* mol = new RWMol(); + auto* mol = new RWMol(); const RingInfo* ri = QueryMolecule->getRingInfo(); unsigned ai = 0; // SeedAtomIdx for (auto atom = mcsIdx.Atoms.begin(); atom != mcsIdx.Atoms.end(); @@ -678,8 +727,9 @@ MaximumCommonSubgraph::generateResultSMARTSAndQueryMol( Queries::COMPOSITE_OR); if (Parameters.AtomCompareParameters.MatchChiralTag && (am->second->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW || - am->second->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW)) + am->second->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW)) { a.setChiralTag(am->second->getChiralTag()); + } } } if (Parameters.AtomCompareParameters.RingMatchesRingOnly) { @@ -705,8 +755,9 @@ MaximumCommonSubgraph::generateResultSMARTSAndQueryMol( b.expandQuery(makeBondOrderEqualsQuery(bm->second->getBondType()), Queries::COMPOSITE_OR); if (Parameters.BondCompareParameters.MatchStereo && - bm->second->getStereo() > Bond::STEREOANY) + bm->second->getStereo() > Bond::STEREOANY) { b.setStereo(bm->second->getStereo()); + } } if (Parameters.BondCompareParameters.RingMatchesRingOnly) { BOND_EQUALS_QUERY* q = makeBondIsInRingQuery(); @@ -728,20 +779,30 @@ bool MaximumCommonSubgraph::addFusedBondQueries(const MCS& mcsIdx, const VECT_INT_VECT& br = ri->bondRings(); std::vector mcsRingSize(br.size(), 0); for (size_t ringIdx = 0; ringIdx < br.size(); ++ringIdx) { - for (int bondIdx : br[ringIdx]) bondRingMembership[bondIdx].insert(ringIdx); + for (int bondIdx : br[ringIdx]) { + bondRingMembership[bondIdx].insert(ringIdx); + } } - for (auto bond = mcsIdx.Bonds.begin(); bond != mcsIdx.Bonds.end(); ++bond) { - unsigned int bondIdx = (*bond)->getIdx(); - if (!ri->numBondRings(bondIdx)) continue; - for (size_t ringIdx : bondRingMembership[bondIdx]) ++mcsRingSize[ringIdx]; + for (auto Bond : mcsIdx.Bonds) { + unsigned int bondIdx = Bond->getIdx(); + if (!ri->numBondRings(bondIdx)) { + continue; + } + for (size_t ringIdx : bondRingMembership[bondIdx]) { + ++mcsRingSize[ringIdx]; + } } for (auto bond = mcsIdx.Bonds.begin(); bond != mcsIdx.Bonds.end(); ++bond, ++bi) { unsigned int bondIdx = (*bond)->getIdx(); - if (!ri->numBondRings(bondIdx)) continue; + if (!ri->numBondRings(bondIdx)) { + continue; + } haveFusedBondQuery = true; for (int ringIdx : bondRingMembership[bondIdx]) { - if (mcsRingSize[ringIdx] < br[ringIdx].size()) continue; + if (mcsRingSize[ringIdx] < br[ringIdx].size()) { + continue; + } rwMol->getBondWithIdx(bi)->expandQuery( makeBondInRingOfSizeQuery(br[ringIdx].size()), Queries::COMPOSITE_AND, true); @@ -761,8 +822,9 @@ bool MaximumCommonSubgraph::createSeedFromMCS(size_t newQueryTarget, mcsAtomIdxMap[(*atom)->getIdx()] = mcs.addAtom((*atom)); } for (std::vector::const_iterator bond = McsIdx.Bonds.begin(); - bond != McsIdx.Bonds.end(); bond++) + bond != McsIdx.Bonds.end(); bond++) { mcs.addBond((*bond)); + } const Target& newQuery = McsIdx.Targets[newQueryTarget]; @@ -771,7 +833,9 @@ bool MaximumCommonSubgraph::createSeedFromMCS(size_t newQueryTarget, newQuery.Topology, *newQuery.Molecule, mcs.Topology, *McsIdx.QueryMolecule, newQuery.AtomMatchTable, newQuery.BondMatchTable, &Parameters, &match); - if (!target_matched) return false; + if (!target_matched) { + return false; + } AtomMatchSet atomMatchResult(mcs.getNumAtoms()); @@ -804,29 +868,37 @@ MCSResult MaximumCommonSubgraph::find(const std::vector& src_mols) { clear(); MCSResult res; - if (src_mols.size() < 2) + if (src_mols.size() < 2) { throw std::runtime_error( "FMCS. Invalid argument. mols.size() must be at least 2"); - if (Parameters.Threshold > 1.0) + } + if (Parameters.Threshold > 1.0) { throw std::runtime_error( - "FMCS. Invalid argument. Parameter Threshold must be 1.0 or less."); + "FMCS. Invalid argument. Parameter Threshold must be 1.0 or " + "less."); + } ThresholdCount = (unsigned)ceil((src_mols.size()) * Parameters.Threshold) - - 1; // minimal required number of matched targets - if (ThresholdCount < 1) // at least one target + 1; // minimal required number of matched targets + if (ThresholdCount < 1) { // at least one target ThresholdCount = 1; - if (ThresholdCount > src_mols.size() - 1) // max all targets + } + if (ThresholdCount > src_mols.size() - 1) { // max all targets ThresholdCount = src_mols.size() - 1; + } - // Selecting CompleteRingsOnly option also enables --ring-matches-ring-only. - // ring--ring and chain bonds only match chain bonds. - if (Parameters.BondCompareParameters.CompleteRingsOnly) + // Selecting CompleteRingsOnly option also enables + // --ring-matches-ring-only. ring--ring and chain bonds only match chain + // bonds. + if (Parameters.BondCompareParameters.CompleteRingsOnly) { Parameters.BondCompareParameters.RingMatchesRingOnly = true; + } for (const auto& src_mol : src_mols) { Molecules.push_back(src_mol.get()); - if (!Molecules.back()->getRingInfo()->isInitialized()) + if (!Molecules.back()->getRingInfo()->isInitialized()) { Molecules.back()->getRingInfo()->initialize(); // but do not fill out !!! + } } // sort source set of molecules by their 'size' and assume the smallest @@ -836,23 +908,29 @@ MCSResult MaximumCommonSubgraph::find(const std::vector& src_mols) { for (size_t i = 0; i < Molecules.size() - ThresholdCount && !res.Canceled; i++) { init(); - if (Targets.empty()) break; + if (Targets.empty()) { + break; + } MCSFinalMatchCheckFunction tff = Parameters.FinalMatchChecker; - if (FinalMatchCheckFunction == Parameters.FinalMatchChecker) + if (FinalMatchCheckFunction == Parameters.FinalMatchChecker) { Parameters.FinalMatchChecker = nullptr; // skip final match check for + } // initial seed to allow future growing // of it makeInitialSeeds(); Parameters.FinalMatchChecker = tff; // restore final functor - if (Parameters.Verbose) + if (Parameters.Verbose) { std::cout << "Query " << MolToSmiles(*QueryMolecule) << " " << QueryMolecule->getNumAtoms() << "(" << QueryMoleculeMatchedAtoms << ") atoms, " << QueryMolecule->getNumBonds() << "(" << QueryMoleculeMatchedBonds << ") bonds\n"; + } - if (Seeds.empty()) break; + if (Seeds.empty()) { + break; + } res.Canceled = growSeeds() ? false : true; // verify what MCS is equal to one of initial seed for chirality match if ((FinalMatchCheckFunction == Parameters.FinalMatchChecker && @@ -876,8 +954,9 @@ MCSResult MaximumCommonSubgraph::find(const std::vector& src_mols) { } else if (i + 1 < Molecules.size() - ThresholdCount) { Seed seed; - if (createSeedFromMCS(i, seed)) // MCS is matched with new query + if (createSeedFromMCS(i, seed)) { // MCS is matched with new query Seeds.push_back(seed); + } std::swap(Molecules[0], Molecules[i + 1]); // change query molecule for threshold < 1. } @@ -891,8 +970,9 @@ MCSResult MaximumCommonSubgraph::find(const std::vector& src_mols) { generateResultSMARTSAndQueryMol(McsIdx); res.SmartsString = smartsQueryMolPair.first; res.QueryMol = RWMOL_SPTR(smartsQueryMolPair.second); - if (Parameters.BondCompareParameters.MatchFusedRingsStrict) + if (Parameters.BondCompareParameters.MatchFusedRingsStrict) { addFusedBondQueries(McsIdx, smartsQueryMolPair.second); + } } #ifdef VERBOSE_STATISTICS_ON @@ -904,20 +984,22 @@ MCSResult MaximumCommonSubgraph::find(const std::vector& src_mols) { bool target_matched = SubstructMatch(*tag->Molecule, *res.QueryMol, match); - if (!target_matched) + if (!target_matched) { std::cout << "Target " << itarget + 1 << (target_matched ? " matched " : " MISMATCHED ") << MolToSmiles(*tag->Molecule) << "\n"; + } } std::cout << "STATISTICS:\n"; std::cout << "Total Growing Steps = " << VerboseStatistics.TotalSteps << ", MCS found on " << VerboseStatistics.MCSFoundStep << " step"; - if (VerboseStatistics.MCSFoundTime - To > 0) + if (VerboseStatistics.MCSFoundTime - To > 0) { printf(", for %.4lf seconds\n", double(VerboseStatistics.MCSFoundTime - To) / 1000000.); - else + } else { std::cout << ", for less than 1 second\n"; + } std::cout << "Initial Seeds = " << VerboseStatistics.InitialSeed << ", Mismatched " << VerboseStatistics.MismatchedInitialSeed << "\n"; @@ -999,8 +1081,9 @@ bool MaximumCommonSubgraph::checkIfMatchAndAppend(Seed& seed) { VerboseStatistics.DupCacheFound++; VerboseStatistics.DupCacheFoundMatch += foundInCache ? 1 : 0; #endif - if (!foundInCache) // mismatched !!! + if (!foundInCache) { // mismatched !!! return false; + } } foundInDupCache = foundInCache; #endif @@ -1021,8 +1104,9 @@ bool MaximumCommonSubgraph::checkIfMatchAndAppend(Seed& seed) { cacheEntry->begin(); !foundInCache && g != cacheEntry->end(); g++) { if (g->m_vertices.size() != seed.getNumAtoms() || - g->m_edges.size() != seed.getNumBonds()) + g->m_edges.size() != seed.getNumBonds()) { continue; + } #ifdef VERBOSE_STATISTICS_ON ++VerboseStatistics.ExactMatchCall; #endif @@ -1031,7 +1115,9 @@ bool MaximumCommonSubgraph::checkIfMatchAndAppend(Seed& seed) { (*g), *QueryMolecule, seed.Topology, *QueryMolecule, QueryAtomMatchTable, QueryBondMatchTable, &Parameters); #ifdef VERBOSE_STATISTICS_ON - if (foundInCache) ++VerboseStatistics.ExactMatchCallTrue; + if (foundInCache) { + ++VerboseStatistics.ExactMatchCallTrue; + } #endif } } @@ -1047,34 +1133,40 @@ bool MaximumCommonSubgraph::checkIfMatchAndAppend(Seed& seed) { Seed* newSeed = nullptr; { - if (found) { // Store new generated seed, if found in cache or in all(- - // threshold) targets + if (found) { // Store new generated seed, if found in cache or in + // all(- threshold) targets { newSeed = &Seeds.add(seed); newSeed->CopyComplete = false; } #ifdef DUP_SUBSTRUCT_CACHE - if (!foundInDupCache && seed.getNumBonds() >= 3) // only seed with a ring - // can be duplicated - - // do not store very - // small seed in cache + if (!foundInDupCache && + seed.getNumBonds() >= 3) { // only seed with a ring + // can be duplicated - + // do not store very + // small seed in cache DuplicateCache.add(seed.DupCacheKey, true); + } #endif #ifdef FAST_SUBSTRUCT_CACHE - if (!foundInCache) HashCache.add(seed, cacheKey, cacheEntry); + if (!foundInCache) { + HashCache.add(seed, cacheKey, cacheEntry); + } #endif } else { #ifdef DUP_SUBSTRUCT_CACHE - if (seed.getNumBonds() > 3) + if (seed.getNumBonds() > 3) { DuplicateCache.add(seed.DupCacheKey, false); // opt. cache mismatched duplicates too + } #endif } } - if (newSeed) - *newSeed = - seed; // non-blocking copy for MULTI_THREAD and best CPU utilization + if (newSeed) { + *newSeed = seed; // non-blocking copy for MULTI_THREAD and best CPU + // utilization + } return found; // new matched seed has been actually added } @@ -1091,8 +1183,9 @@ bool MaximumCommonSubgraph::match(Seed& seed) { { ++VerboseStatistics.MatchCall; } #endif bool target_matched = false; - if (!seed.MatchResult.empty() && !seed.MatchResult[itarget].empty()) + if (!seed.MatchResult.empty() && !seed.MatchResult[itarget].empty()) { target_matched = matchIncrementalFast(seed, itarget); + } if (!target_matched) { // slow full match match_V_t match; // THERE IS NO Bonds match INFO !!!! target_matched = SubstructMatchCustomTable( @@ -1100,10 +1193,13 @@ bool MaximumCommonSubgraph::match(Seed& seed) { tag->AtomMatchTable, tag->BondMatchTable, &Parameters, &match); // save current match info if (target_matched) { - if (seed.MatchResult.empty()) seed.MatchResult.resize(Targets.size()); + if (seed.MatchResult.empty()) { + seed.MatchResult.resize(Targets.size()); + } seed.MatchResult[itarget].init(seed, match, *QueryMolecule, *tag); - } else if (!seed.MatchResult.empty()) + } else if (!seed.MatchResult.empty()) { seed.MatchResult[itarget].clear(); //.Empty = true; // == fast clear(); + } #ifdef VERBOSE_STATISTICS_ON if (target_matched) { ++VerboseStatistics.SlowMatchCallTrue; @@ -1112,10 +1208,13 @@ bool MaximumCommonSubgraph::match(Seed& seed) { } if (target_matched) { - if (++passed >= ThresholdCount) // it's enough + if (++passed >= ThresholdCount) { // it's enough break; + } } else { // mismatched - if (++missing > max_miss) break; + if (++missing > max_miss) { + break; + } } } if (missing <= max_miss) { @@ -1135,7 +1234,9 @@ bool MaximumCommonSubgraph::matchIncrementalFast(Seed& seed, unsigned itarget) { #endif const Target& target = Targets[itarget]; TargetMatch& match = seed.MatchResult[itarget]; - if (match.empty()) return false; + if (match.empty()) { + return false; + } /* // CHIRALITY: FinalMatchCheck: if(Parameters.AtomCompareParameters.MatchChiralTag || @@ -1152,10 +1253,10 @@ bool MaximumCommonSubgraph::matchIncrementalFast(Seed& seed, unsigned itarget) { const Bond* newBond = seed.MoleculeFragment.Bonds[newBondSeedIdx]; unsigned newBondQueryIdx = seed.MoleculeFragment.BondsIdx[newBondSeedIdx]; - unsigned newBondSourceAtomSeedIdx; // seed's index of atom from which new - // bond was added - unsigned newBondAnotherAtomSeedIdx; // seed's index of atom on another end - // of the bond + unsigned newBondSourceAtomSeedIdx; // seed's index of atom from which + // new bond was added + unsigned newBondAnotherAtomSeedIdx; // seed's index of atom on + // another end of the bond unsigned i = seed.MoleculeFragment.SeedAtomIdxMap[newBond->getBeginAtomIdx()]; unsigned j = seed.MoleculeFragment.SeedAtomIdxMap[newBond->getEndAtomIdx()]; @@ -1172,7 +1273,8 @@ bool MaximumCommonSubgraph::matchIncrementalFast(Seed& seed, unsigned itarget) { seed.MoleculeFragment.AtomsIdx[newBondSourceAtomSeedIdx]; unsigned newBondSourceAtomTargetIdx = match.TargetAtomIdx - [newBondSourceAtomQueryIdx]; // matched to newBondSourceAtomSeedIdx + [newBondSourceAtomQueryIdx]; // matched to + // newBondSourceAtomSeedIdx const Bond* tb = nullptr; unsigned newBondAnotherAtomTargetIdx = NotSet; @@ -1189,9 +1291,10 @@ bool MaximumCommonSubgraph::matchIncrementalFast(Seed& seed, unsigned itarget) { if (tb) { // bond exists, check match with query molecule unsigned tbi = tb->getIdx(); unsigned qbi = seed.MoleculeFragment.BondsIdx[newBondSeedIdx]; - if (!match.VisitedTargetBonds[tbi]) // false if target bond is already - // matched + if (!match.VisitedTargetBonds[tbi]) { // false if target bond is + // already matched matched = target.BondMatchTable.at(qbi, tbi); + } } } else { // enumerate all bonds from source atom in the target const Atom* atom = @@ -1202,23 +1305,27 @@ bool MaximumCommonSubgraph::matchIncrementalFast(Seed& seed, unsigned itarget) { tb = &*((*target.Molecule)[*beg]); if (!match.VisitedTargetBonds[tb->getIdx()]) { newBondAnotherAtomTargetIdx = tb->getBeginAtomIdx(); - if (newBondSourceAtomTargetIdx == newBondAnotherAtomTargetIdx) + if (newBondSourceAtomTargetIdx == newBondAnotherAtomTargetIdx) { newBondAnotherAtomTargetIdx = tb->getEndAtomIdx(); + } if (newBondAnotherAtomSeedIdx < - seed.LastAddedAtomsBeginIdx // RING: old atom, new atom in - // matched substructure must be - // new in seed + seed.LastAddedAtomsBeginIdx // RING: old atom, new atom + // in matched substructure + // must be new in seed || std::find(seed.MoleculeFragment.AtomsIdx.begin() + seed.LastAddedAtomsBeginIdx, seed.MoleculeFragment.AtomsIdx.begin() + newBondAnotherAtomSeedIdx, newBondAnotherAtomQueryIdx) == seed.MoleculeFragment.AtomsIdx.end()) { - if (!match.VisitedTargetAtoms[newBondAnotherAtomTargetIdx]) + if (!match.VisitedTargetAtoms[newBondAnotherAtomTargetIdx]) { continue; + } } else { - if (match.VisitedTargetAtoms[newBondAnotherAtomTargetIdx]) continue; + if (match.VisitedTargetAtoms[newBondAnotherAtomTargetIdx]) { + continue; + } } // check AnotherAtom and bond @@ -1269,10 +1376,13 @@ bool MaximumCommonSubgraph::matchIncrementalFast(Seed& seed, unsigned itarget) { c1.push_back(si); c2.push_back(match.TargetAtomIdx[seed.Topology[si]]); } - matched = Parameters.FinalMatchChecker( - c1.data(), c2.data(), *QueryMolecule, seed.Topology, *target.Molecule, - target.Topology, &Parameters); // check CHIRALITY - if (!matched) match.clear(); + matched = Parameters.FinalMatchChecker(c1.data(), c2.data(), *QueryMolecule, + seed.Topology, *target.Molecule, + target.Topology, + &Parameters); // check CHIRALITY + if (!matched) { + match.clear(); + } } #ifdef VERBOSE_STATISTICS_ON if (matched) { diff --git a/Code/GraphMol/FMCS/Seed.cpp b/Code/GraphMol/FMCS/Seed.cpp index 69b448ce6..d7239a83e 100644 --- a/Code/GraphMol/FMCS/Seed.cpp +++ b/Code/GraphMol/FMCS/Seed.cpp @@ -34,7 +34,9 @@ unsigned Seed::addAtom(const Atom* atom) { unsigned Seed::addBond(const Bond* bond) { unsigned b = bond->getIdx(); - if (ExcludedBonds[b]) throw - 1; // never, check the implementation + if (ExcludedBonds[b]) { + throw - 1; // never, check the implementation + } ExcludedBonds[b] = true; MoleculeFragment.BondsIdx.push_back(b); MoleculeFragment.Bonds.push_back(bond); @@ -64,12 +66,13 @@ void Seed::fillNewBonds(const ROMol& qmol) { : bond->getBeginAtomIdx(); const Atom* end_atom = qmol.getAtomWithIdx(ai); unsigned end_atom_idx = NotSet; - for (unsigned i = 0; i < getNumAtoms(); i++) + for (unsigned i = 0; i < getNumAtoms(); i++) { if (end_atom == MoleculeFragment.Atoms[i]) { // already exists in this seed end_atom_idx = i; break; } + } NewBonds.push_back( NewBond(srcAtomIdx, bond->getIdx(), ai, end_atom_idx, NotSet == end_atom_idx ? end_atom : nullptr)); @@ -144,8 +147,9 @@ void Seed::grow(MaximumCommonSubgraph& mcs) const { seed); // this seed + all extern bonds is a part of MCS GrowingStage = 1; - if (allMatched && NewBonds.size() > 1) + if (allMatched && NewBonds.size() > 1) { return; // grow deep first. postpone next growing steps + } } // 2. Check and add all 2^N-1-1 other possible seeds: if (1 == NewBonds.size()) { @@ -175,7 +179,9 @@ void Seed::grow(MaximumCommonSubgraph& mcs) const { if (seed.canGrowBiggerThan(mcs.getMaxNumberBonds(), mcs.getMaxNumberAtoms())) { // prune() - if (!MatchResult.empty()) seed.MatchResult = MatchResult; + if (!MatchResult.empty()) { + seed.MatchResult = MatchResult; + } if (!mcs.checkIfMatchAndAppend(seed)) { nbi.BondIdx = NotSet; // exclude this new bond from growing this seed // - decrease 2^^N-1 to 2^^k-1, k::const_iterator nbi = dirtyNewBonds.begin(); - nbi != dirtyNewBonds.end(); nbi++) - if (NotSet != nbi->BondIdx) NewBonds.push_back(*nbi); + nbi != dirtyNewBonds.end(); nbi++) { + if (NotSet != nbi->BondIdx) { + NewBonds.push_back(*nbi); + } + } } - // add all other from 2^k-1 possible seeds, where k=newBonds.size() // if just one new bond, then seed has already been created if (NewBonds.size() > 1) { - if (sizeof(unsigned long long) * 8 < NewBonds.size()) + if (sizeof(unsigned long long) * 8 < NewBonds.size()) { throw std::runtime_error( "Max number of new external bonds of a seed more than 64"); + } BitSet maxCompositionValue; Composition2N::compute2N(NewBonds.size(), maxCompositionValue); maxCompositionValue -= 1; // 2^N-1 @@ -217,12 +226,14 @@ void Seed::grow(MaximumCommonSubgraph& mcs) const { #endif while (composition.generateNext()) { // exclude already processed single external bond combinations - if (composition.is2Power()) + if (composition.is2Power()) { continue; + } if (0 == numErasedNewBonds && - composition.getBitSet() == maxCompositionValue) + composition.getBitSet() == maxCompositionValue) { continue; // exclude already processed all external bonds combination - // 2N-1 + } + // 2N-1 #ifdef EXCLUDE_WRONG_COMPOSITION // OPTIMISATION. reduce amount of generated seeds and match calls // 2120 instead of 2208 match calls on small test. 43 wrongComp-s, 83 @@ -253,7 +264,7 @@ void Seed::grow(MaximumCommonSubgraph& mcs) const { seed.createFromParent(this); newAtomsSet.clear(); - for (unsigned i = 0; i < NewBonds.size(); i++) + for (unsigned i = 0; i < NewBonds.size(); i++) { if (composition.isSet(i)) { const NewBond* nbi = &NewBonds[i]; unsigned aIdx = @@ -268,6 +279,7 @@ void Seed::grow(MaximumCommonSubgraph& mcs) const { const Bond* src_bond = qmol.getBondWithIdx(nbi->BondIdx); seed.addBond(src_bond); } + } seed.computeRemainingSize(qmol); if (!seed.canGrowBiggerThan( mcs.getMaxNumberBonds(), @@ -303,11 +315,14 @@ void Seed::computeRemainingSize(const ROMol& qmol) { std::vector visitedBonds = ExcludedBonds; std::vector visitedAtoms(qmol.getNumAtoms()); - for (auto&& visitedAtom : visitedAtoms) visitedAtom = false; + for (auto&& visitedAtom : visitedAtoms) { + visitedAtom = false; + } for (std::vector::const_iterator it = MoleculeFragment.AtomsIdx.begin(); - it != MoleculeFragment.AtomsIdx.end(); it++) + it != MoleculeFragment.AtomsIdx.end(); it++) { visitedAtoms[*it] = true; + } // SDF all paths // 1. direct neighbours @@ -359,5 +374,5 @@ void Seed::computeRemainingSize(const ROMol& qmol) { } } } -} -} +} // namespace FMCS +} // namespace RDKit diff --git a/Code/GraphMol/FMCS/SubstructMatchCustom.cpp b/Code/GraphMol/FMCS/SubstructMatchCustom.cpp index 757d765ea..ec73dd653 100644 --- a/Code/GraphMol/FMCS/SubstructMatchCustom.cpp +++ b/Code/GraphMol/FMCS/SubstructMatchCustom.cpp @@ -39,8 +39,9 @@ class MolMatchFinalCheckFunctor { bool operator()(const boost::detail::node_id c1[], const boost::detail::node_id c2[]) const { - if ((unsigned)c1[0] >= boost::num_vertices(QueryTopology)) + if ((unsigned)c1[0] >= boost::num_vertices(QueryTopology)) { return false; // invalid index - match failed, see v2f implementation + } MCSFinalMatchCheckFunction compare = Parameters ? Parameters->FinalMatchChecker : nullptr; return compare ? compare(c1, c2, d_query, QueryTopology, d_mol, @@ -87,8 +88,9 @@ bool SubstructMatchCustomTable(const FMCS::Graph& target, const ROMol& mol, const MatchTable& bondMatchTable, const MCSParameters* p, match_V_t* match) { if (query.m_vertices.size() > target.m_vertices.size() // query > target - || query.m_edges.size() > target.m_edges.size()) + || query.m_edges.size() > target.m_edges.size()) { return false; + } MolMatchFinalCheckFunctor mc(query, target, querySrc, mol, p); @@ -96,7 +98,9 @@ bool SubstructMatchCustomTable(const FMCS::Graph& target, const ROMol& mol, BondTableCompareFunctor bc(query, target, bondMatchTable); match_V_t dummy_match; - if (!match) match = &dummy_match; + if (!match) { + match = &dummy_match; + } return boost::vf2(query, target, ac, bc, mc, *match); } @@ -179,7 +183,9 @@ bool SubstructMatchCustom( ud); match_V_t dummy_match; - if (!match) match = &dummy_match; + if (!match) { + match = &dummy_match; + } return boost::vf2(query, target, atomLabeler, bondLabeler, matchChecker, *match); } diff --git a/Code/GraphMol/FMCS/Test/testFMCS.cpp b/Code/GraphMol/FMCS/Test/testFMCS.cpp index 5891d4355..23b18e891 100644 --- a/Code/GraphMol/FMCS/Test/testFMCS.cpp +++ b/Code/GraphMol/FMCS/Test/testFMCS.cpp @@ -71,7 +71,9 @@ std::string getSmilesOnly( std::string* id = nullptr) { // remove label, because RDKit parse FAILED const char* sp = strchr(smiles, ' '); unsigned n = (sp ? sp - smiles + 1 : strlen(smiles)); - if (id) *id = std::string(smiles + n); + if (id) { + *id = std::string(smiles + n); + } return std::string(smiles, n); } @@ -81,13 +83,18 @@ std::string getSmilesOnlyTxt( // NS(=O)(=O)c1ccc(NC(=O)c2cccc(C(=O)O)n2)c(Cl)c1" const char* sp = strchr(smiles, ' '); if (sp && '\0' != *sp) { - if (id) *id = std::string(smiles, sp - smiles); + if (id) { + *id = std::string(smiles, sp - smiles); + } sp++; size_t i = strlen(sp); - while (i > 0 && sp[i - 1] < ' ') --i; + while (i > 0 && sp[i - 1] < ' ') { + --i; + } return std::string(sp, i); - } else + } else { return smiles; + } } std::string getSmilesOnlyChEMBL( @@ -96,9 +103,13 @@ std::string getSmilesOnlyChEMBL( const char* sp = strchr(smiles, '\t'); if (sp) { unsigned n = (sp ? sp - smiles + 1 : strlen(smiles)); - if (id) *id = std::string(smiles, n); + if (id) { + *id = std::string(smiles, n); + } sp = strchr(++sp, '\t'); - if (sp) sp++; + if (sp) { + sp++; + } } return std::string(sp); } @@ -124,10 +135,11 @@ void testFileMCSB( referenceOutFile += ".REF.out"; std::string outFile(test); if (!test_N.empty()) { - if (1 == test_N.size()) + if (1 == test_N.size()) { sprintf(str, ".%u.out", test_N[0]); - else + } else { sprintf(str, ".%u-%u.out", test_N[0], test_N.back()); + } outFile += str; } else { outFile += ".Cpp.out"; @@ -142,11 +154,11 @@ void testFileMCSB( std::vector referenceResultsTime; FILE* f = fopen(referenceOutFile.c_str(), "rt"); - if (!f) + if (!f) { perror("Could not open reference test result file"); - else { + } else { std::cout << "Loading reference test results ... \n"; - while (fgets(str, sizeof(str), f)) + while (fgets(str, sizeof(str), f)) { if ('#' != str[0]) { char c; int frag; @@ -160,6 +172,7 @@ void testFileMCSB( referenceResults.push_back(res); referenceResultsTime.push_back(t); } + } } fclose(f); @@ -170,17 +183,22 @@ void testFileMCSB( } { std::cout << "Loading MCSB test list ... \n"; - if (fgets(str, sizeof(str), f)) + if (fgets(str, sizeof(str), f)) { if (fgets(str, sizeof(str), f)) { char* c = strrchr(str, '\n'); // remove LineFeed - if (c) *c = '\0'; + if (c) { + *c = '\0'; + } c = strrchr(str, '\r'); - if (c) *c = '\0'; + if (c) { + *c = '\0'; + } molFile = str + 6; // #File filename } + } std::cout << "Molecules file:" << molFile << "\n"; n = 0; - while (fgets(str, sizeof(str), f)) + while (fgets(str, sizeof(str), f)) { if ('#' != str[0]) { // str= "1 CHEMBL526291 CHEMBL498211 ..." char name[256]; @@ -194,6 +212,7 @@ void testFileMCSB( testCase.back().push_back(std::string(name)); } } + } std::cout << n << " Test cases loaded\n"; } fclose(f); @@ -209,9 +228,13 @@ void testFileMCSB( std::cout << "\rLine: " << ++n << " "; if ('#' != str[0] && ' ' != str[0] && '/' != str[0]) { // commented to skip char* c = strrchr(str, '\n'); // remove LineFeed - if (c) *c = '\0'; + if (c) { + *c = '\0'; + } c = strrchr(str, '\r'); - if (c) *c = '\0'; + if (c) { + *c = '\0'; + } std::string sm = getSmilesOnly(str, &id); smilesList.push_back(sm); // without Id and LineFeed mols.push_back(ROMOL_SPTR(SmilesToMol(sm))); // SmartsToMol ??? @@ -229,7 +252,9 @@ void testFileMCSB( } setvbuf(f, nullptr, _IOFBF, 4 * 1024); FILE* fs = nullptr; // fopen(outSmilesFile.c_str(), "wt"); - if (fs) setvbuf(fs, nullptr, _IOFBF, 4 * 1024); + if (fs) { + setvbuf(fs, nullptr, _IOFBF, 4 * 1024); + } #ifdef xxVERBOSE_STATISTICS_ON FILE* ft = fopen((outFile + ".stat.csv").c_str(), "wt"); setvbuf(ft, 0, _IOFBF, 4 * 1024); // small file @@ -249,23 +274,31 @@ void testFileMCSB( tc = testCase.begin(); tc != testCase.end(); tc++, n++) { if (!test_N.empty() && - test_N.end() == std::find(test_N.begin(), test_N.end(), n + 1)) + test_N.end() == std::find(test_N.begin(), test_N.end(), n + 1)) { continue; + } std::cout << "\rTest: " << n + 1 << " "; - if (!test_N.empty()) // test case is listed + if (!test_N.empty()) { // test case is listed std::cout << "\n"; + } std::vector tcmols; fprintf(f, "# %u Using ", n + 1); - if (fs) fprintf(fs, "\n//TEST %u\n", n + 1); + if (fs) { + fprintf(fs, "\n//TEST %u\n", n + 1); + } for (const auto& mid : *tc) { std::map::const_iterator id = molIdMap.find(mid); - if (molIdMap.end() == id) continue; + if (molIdMap.end() == id) { + continue; + } size_t i = id->second; tcmols.push_back(mols[i]); fprintf(f, "%s ", mid.c_str()); - if (fs) fprintf(fs, "\"%s%s\",\n", smilesList[i].c_str(), mid.c_str()); + if (fs) { + fprintf(fs, "\"%s%s\",\n", smilesList[i].c_str(), mid.c_str()); + } } fprintf(f, "\n"); // ExecStatistics curStat = stat; //to compute the @@ -276,17 +309,18 @@ void testFileMCSB( double sec = double(tc1 - tc0) / 1000000.; // without time of SMILES to ROMol conversion secTotal += sec; - if (!test_N.empty()) + if (!test_N.empty()) { std::cout << "\n" << "MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " << res.NumBonds << " bonds\n"; - else if (!referenceResults[n].Canceled && !res.Canceled && - (/*referenceResults[n].NumAtoms > res.NumAtoms ||*/ referenceResults - [n].NumBonds > res.NumBonds)) + } else if (!referenceResults[n].Canceled && !res.Canceled && + (/*referenceResults[n].NumAtoms > res.NumAtoms ||*/ + referenceResults[n].NumBonds > res.NumBonds)) { std::cout << " - failed. LESS: " << res.NumAtoms << " atoms, " << res.NumBonds << " bonds (" << referenceResults[n].NumAtoms - res.NumAtoms << ", " << referenceResults[n].NumBonds - res.NumBonds << ")\n"; + } if (!referenceResults.empty()) { fprintf( @@ -300,12 +334,12 @@ void testFileMCSB( referenceResultsTime[n]); if (!referenceResults[n].Canceled) { // && !res.Canceled) if (referenceResults[n].NumAtoms == res.NumAtoms && - referenceResults[n].NumBonds == res.NumBonds) + referenceResults[n].NumBonds == res.NumBonds) { fprintf(f, "# %u REFCMP: res %s %s %u %u %s.\n", n + 1, "PASSED", "-------", referenceResults[n].NumAtoms, referenceResults[n].NumBonds, referenceResults[n].SmartsString.c_str()); - else + } else { fprintf( f, "# %u REFCMP: res %s %s %u %u %s.\n", n + 1, "FAILED", /*referenceResults[n].NumAtoms > res.NumAtoms ||*/ referenceResults @@ -314,29 +348,34 @@ void testFileMCSB( : "GREATER", referenceResults[n].NumAtoms, referenceResults[n].NumBonds, referenceResults[n].SmartsString.c_str()); + } if (referenceResults[n].Canceled || (referenceResults[n].NumAtoms == res.NumAtoms && - referenceResults[n].NumBonds == res.NumBonds)) + referenceResults[n].NumBonds == res.NumBonds)) { passed++; - else if (res.Canceled) + } else if (res.Canceled) { timedout++; - else { - if (referenceResults[n].NumBonds > res.NumBonds) failed_less++; + } else { + if (referenceResults[n].NumBonds > res.NumBonds) { + failed_less++; + } failed++; } - } else + } else { fprintf(f, "# %u REFCMP: res ABSENT - timeout\n", n + 1); + } } // 1 . 1 25 28 1.69 F-c1:c:c: fprintf(f, "%u %c %d %u %u %.2f %s\n", n + 1, (res.Canceled ? 'F' : '.'), 1 // number of fragments in the MCS , res.NumAtoms, res.NumBonds, sec, res.SmartsString.c_str()); - if (fs) + if (fs) { fprintf(fs, "//# %u %c %u %u %.2f sec MCS: %s\n", n + 1, (res.Canceled ? 'F' : '.'), res.NumAtoms, res.NumBonds, sec, res.SmartsString.c_str()); + } #ifdef xxVERBOSE_STATISTICS_ON if (ft) // statistic details fprintf( @@ -402,8 +441,12 @@ void testFileMCSB( #endif ); #endif - if (f) fclose(f); - if (fs) fclose(fs); + if (f) { + fclose(f); + } + if (fs) { + fclose(fs); + } #ifdef xxVERBOSE_STATISTICS_ON if (ft) fclose(ft); #endif @@ -450,9 +493,10 @@ void test504() { } std::cout << "Query +MAP " << MolToSmiles(*qm) << "\n"; mols.push_back(ROMOL_SPTR(qm)); // with RING INFO - for (size_t i = 1; i < sizeof(smi) / sizeof(smi[0]); i++) + for (size_t i = 1; i < sizeof(smi) / sizeof(smi[0]); i++) { mols.push_back( ROMOL_SPTR(SmilesToMol(getSmilesOnly(smi[i])))); // with RING INFO + } t0 = nanoClock(); MCSResult res = findMCS(mols, &p); std::cout << "MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " @@ -912,9 +956,10 @@ void testChEMBL_TxtSLOW_chembl_II_sets(double th = 1.0) { "Target_no_10193_46700.txt", "Target_no_10980_30994.txt", "Target_no_11140_37038.txt", }; - for (auto& i : test) + for (auto& i : test) { testChEMBL_Txt((std::string("chembl_II_sets/") + i).c_str(), th, "chembl_II_sets.SLOW.C++.res.csv"); + } } void testChEMBLdat(const char* test, double th = 1.0) { @@ -1032,11 +1077,12 @@ void testChEMBLdatALL(double th = 1.0) { "cmp_list_ChEMBL_93_actives.dat", "cmp_list_ChEMBL_zinc_decoys.dat", }; - for (auto& i : test) + for (auto& i : test) { testChEMBLdat( (std::string("benchmarking_platform-master/compounds/ChEMBL/") + i).c_str(), th); + } } void testTarget_no_10188_30149() { @@ -1055,7 +1101,9 @@ void testTarget_no_10188_30149() { "COc1ccccc1Nc1ccc2c(c1)[nH]nc2-c1ccccc1 CHEMBL254443", "CN(C)CCNC(=O)c1cccc(-c2[nH]nc3cc(Nc4ccccc4Cl)ccc32)c1 CHEMBL198821", }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } t0 = nanoClock(); #ifdef _DEBUG // check memory leaks _CrtMemState _ms; @@ -1097,7 +1145,9 @@ void testTarget_no_10188_49064() { "Cn1c(=O)c(-c2c(Cl)cccc2Cl)cc2cnc(Nc3ccc(I)cc3)nc21", "CN1CCN(C(=O)c2ccc(Nc3ncc4cc(-c5c(Cl)cccc5Cl)c(=O)n(C)c4n3)cc2)CC1", }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } t0 = nanoClock(); MCSResult res = findMCS(mols, &p); std::cout << "MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " @@ -1107,8 +1157,9 @@ void testTarget_no_10188_49064() { void testCmndLineSMILES(int argc, const char* argv[]) { std::vector mols; - for (int i = 1; i < argc; i++) + for (int i = 1; i < argc; i++) { mols.push_back(ROMOL_SPTR(SmilesToMol(argv[i]))); + } MCSResult res = findMCS(mols); std::cout << "MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " << res.NumBonds << " bonds\n"; @@ -1122,7 +1173,9 @@ double testFileSDF(const char* test) { RDKit::SDMolSupplier suppl(fn); while (!suppl.atEnd()) { ROMol* m = suppl.next(); - if (m) mols.push_back(ROMOL_SPTR(m)); + if (m) { + mols.push_back(ROMOL_SPTR(m)); + } } t0 = nanoClock(); MCSResult res = findMCS(mols, &p); @@ -1214,10 +1267,11 @@ void testFileSDF_RandomSet(const char* test = "chembl13-10000-random-pairs.sdf", std::string fn(std::string(path) + "/" + test); RDKit::MolSupplier* suppl = nullptr; try { - if ('f' == test[strlen(test) - 1]) // sdf file + if ('f' == test[strlen(test) - 1]) { // sdf file suppl = new RDKit::SDMolSupplier(fn); - else if ('i' == test[strlen(test) - 1]) // smi file + } else if ('i' == test[strlen(test) - 1]) { // smi file suppl = new RDKit::SmilesMolSupplier(fn); + } } catch (...) { std::cout << "ERROR: RDKit could not load input file" << "\n"; @@ -1280,7 +1334,9 @@ void testFileSDF_RandomSet(const char* test = "chembl13-10000-random-pairs.sdf", t0 = nanoClock(); MCSResult res = findMCS(mols, &p); double t = (nanoClock() - t0) / 1000000.; - if (t < 0.00001) t = 0.00001; // avoid division by zero + if (t < 0.00001) { + t = 0.00001; // avoid division by zero + } printTime(); std::cout << n << " MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " << res.NumBonds << " bonds\n"; @@ -1293,7 +1349,9 @@ void testFileSDF_RandomSet(const char* test = "chembl13-10000-random-pairs.sdf", t0 = nanoClock(); MCSResult res = findMCS(mols, &p); double t = (nanoClock() - t0) / 1000000.; - if (t < 0.00001) t = 0.00001; // avoid division by zero + if (t < 0.00001) { + t = 0.00001; // avoid division by zero + } printTime(); std::cout << n << " MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " << res.NumBonds << " bonds\n"; @@ -1329,7 +1387,9 @@ void testFileSDF_RandomSet(const char* test = "chembl13-10000-random-pairs.sdf", t0 = nanoClock(); MCSResult res = findMCS(mols, &p); double t = (nanoClock() - t0) / 1000000.; - if (t < 0.00001) t = 0.00001; // avoid division by zero + if (t < 0.00001) { + t = 0.00001; // avoid division by zero + } printTime(); std::cout << n << " MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " << res.NumBonds << " bonds\n"; @@ -1342,7 +1402,9 @@ void testFileSDF_RandomSet(const char* test = "chembl13-10000-random-pairs.sdf", t0 = nanoClock(); MCSResult res = findMCS(mols, &p); double t = (nanoClock() - t0) / 1000000.; - if (t < 0.00001) t = 0.00001; // avoid division by zero + if (t < 0.00001) { + t = 0.00001; // avoid division by zero + } printTime(); std::cout << n << " MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " << res.NumBonds << " bonds\n"; @@ -1359,7 +1421,9 @@ void testFileSDF_RandomSet(const char* test = "chembl13-10000-random-pairs.sdf", unsigned maxMol = 0; for (auto& all_mol : all_mols) { - if (maxMol < all_mol->getNumBonds()) maxMol = all_mol->getNumBonds(); + if (maxMol < all_mol->getNumBonds()) { + maxMol = all_mol->getNumBonds(); + } } const unsigned N_BigRandomTests = all_mols.size() > 2000 ? all_mols.size() / 2 : all_mols.size() * 2; @@ -1395,20 +1459,24 @@ void testFileSDF_RandomSet(const char* test = "chembl13-10000-random-pairs.sdf", // ROMol *m=0; unsigned iN = 2 + rand() % 24; mols.clear(); - for (size_t i = 0; i < iN; i++) // load random set + for (size_t i = 0; i < iN; i++) { // load random set for (size_t ij = 0; ij < all_mols.size() / 2; ij++) { unsigned mi = rand() % (all_mols.size() - 1); - if (all_mols[mi]->getNumBonds() < SizeOfBigMCS_ForBigRandomTests) + if (all_mols[mi]->getNumBonds() < SizeOfBigMCS_ForBigRandomTests) { continue; + } mols.push_back(all_mols[mi]); break; } + } MCSResult res; if (mols.size() > 1) { t0 = nanoClock(); res = findMCS(mols, &p); double t = (nanoClock() - t0) / 1000000.; - if (t < 0.00001) t = 0.00001; // avoid division by zero + if (t < 0.00001) { + t = 0.00001; // avoid division by zero + } printTime(); std::cout << n << " MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " << res.NumBonds << " bonds\n"; @@ -1437,7 +1505,9 @@ void testFileSDF_RandomSet(const char* test = "chembl13-10000-random-pairs.sdf", t0 = nanoClock(); res = findMCS(mols, &p); double t = (nanoClock() - t0) / 1000000.; - if (t < 0.00001) t = 0.00001; // avoid division by zero + if (t < 0.00001) { + t = 0.00001; // avoid division by zero + } printTime(); std::cout << n << " MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " << res.NumBonds << " bonds\n"; @@ -1464,9 +1534,10 @@ void testFileSMILES(const char* test) { while (fgets(smiles, sizeof(smiles), f)) { std::cout << "\rLine: " << ++n << " "; if ('#' != smiles[0] && ' ' != smiles[0] && - '/' != smiles[0]) // commented to skip + '/' != smiles[0]) { // commented to skip // if(strlen(smiles) > 92) // minimal query size !!! mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(smiles)))); + } } fclose(f); printTime(); @@ -1540,7 +1611,9 @@ void testGregSDFFileSetFiltered() { }; double totalT = 0.; - for (auto& i : sdf) totalT += testFileSDF((sdf_dir + i).c_str()); + for (auto& i : sdf) { + totalT += testFileSDF((sdf_dir + i).c_str()); + } printf( "\nTOTAL Time elapsed %.2lf " "seconds\n================================================\n", @@ -1675,18 +1748,22 @@ int main(int argc, const char* argv[]) { } #endif - if (3 == argc && '-' == argv[1][0]) + if (3 == argc && '-' == argv[1][0]) { switch (argv[1][1]) { // ./test -s|m|b case 's': { // smiles files list char test[256]; FILE* f = fopen(argv[2], "rt"); - while (fgets(test, sizeof(test), f)) testFileSMILES(test); + while (fgets(test, sizeof(test), f)) { + testFileSMILES(test); + } fclose(f); } break; case 'm': { // SDF mol files list char test[256]; FILE* f = fopen(argv[2], "rt"); - while (fgets(test, sizeof(test), f)) testFileSDF(test); + while (fgets(test, sizeof(test), f)) { + testFileSDF(test); + } fclose(f); } break; case 'b': { @@ -1696,20 +1773,21 @@ int main(int argc, const char* argv[]) { default: break; } - else if (2 == argc) { // .sdf /.smi file - if (0 == strcmp(argv[1] + strlen(argv[1]) - 4, ".smi")) + } else if (2 == argc) { // .sdf /.smi file + if (0 == strcmp(argv[1] + strlen(argv[1]) - 4, ".smi")) { testFileSMILES(argv[1]); // .smi - else if (0 == strcmp(argv[1] + strlen(argv[1]) - 4, ".sdf")) + } else if (0 == strcmp(argv[1] + strlen(argv[1]) - 4, ".sdf")) { testFileSDF(argv[1]); // .sdf - else if (0 == strcmp(argv[1] + strlen(argv[1]) - 4, "mcsb")) + } else if (0 == strcmp(argv[1] + strlen(argv[1]) - 4, "mcsb")) { testFileMCSB(argv[1], 30); // .mcsb - else if (0 == strcmp(argv[1] + strlen(argv[1]) - 4, ".dat")) + } else if (0 == strcmp(argv[1] + strlen(argv[1]) - 4, ".dat")) { testChEMBLdat(argv[1]); // .sdf - else + } else { printf("UNKNOWN File Extension.\n"); - } else if (argc > 1 + 2) + } + } else if (argc > 1 + 2) { testCmndLineSMILES(argc, argv); - else { + } else { testGregSDFFileSetFiltered(); } // BOOST_LOG(rdInfoLog) << diff --git a/Code/GraphMol/FMCS/Wrap/rdFMCS.cpp b/Code/GraphMol/FMCS/Wrap/rdFMCS.cpp index 00ce9c460..af00a5cbe 100644 --- a/Code/GraphMol/FMCS/Wrap/rdFMCS.cpp +++ b/Code/GraphMol/FMCS/Wrap/rdFMCS.cpp @@ -57,7 +57,9 @@ MCSResult *FindMCSWrapper(python::object mols, bool maximizeBonds, unsigned int nElems = python::extract(mols.attr("__len__")()); ms.resize(nElems); for (unsigned int i = 0; i < nElems; ++i) { - if (!mols[i]) throw_value_error("molecule is None"); + if (!mols[i]) { + throw_value_error("molecule is None"); + } ms[i] = python::extract(mols[i]); } MCSParameters p; @@ -89,7 +91,9 @@ MCSResult *FindMCSWrapper2(python::object mols, const MCSParameters ¶ms) { unsigned int nElems = python::extract(mols.attr("__len__")()); ms.resize(nElems); for (unsigned int i = 0; i < nElems; ++i) { - if (!mols[i]) throw_value_error("molecule is None"); + if (!mols[i]) { + throw_value_error("molecule is None"); + } ms[i] = python::extract(mols[i]); } diff --git a/Code/GraphMol/FMCS/testFMCS_Unit.cpp b/Code/GraphMol/FMCS/testFMCS_Unit.cpp old mode 100755 new mode 100644 index a405aa319..47d555f8c --- a/Code/GraphMol/FMCS/testFMCS_Unit.cpp +++ b/Code/GraphMol/FMCS/testFMCS_Unit.cpp @@ -74,7 +74,9 @@ std::string getSmilesOnly( std::string* id = nullptr) { // remove label, because RDKit parse FAILED const char* sp = strchr(smiles, ' '); unsigned n = (sp ? sp - smiles + 1 : strlen(smiles)); - if (id) *id = std::string(smiles + n); + if (id) { + *id = std::string(smiles + n); + } return std::string(smiles, n); } @@ -130,7 +132,9 @@ void test32() { "CHEMBL1334715", // 31 33 0.35 sec MCS: CCN(CC)c1ccc(cc1NC(=O)C=Cc1ccccc1)S(=O)(=O)N1CCOCC1 }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } t0 = nanoClock(); MCSResult res = findMCS(mols); std::cout << "MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " @@ -160,7 +164,9 @@ void test190() { //# 19 21 1.37 sec MCS: CC(=O)Nc1cccc(c1)-c1nc2ccccc2o1 // 19 21 2.36 sec MCS: CC(=O)Nc1cccc(c1)-c1nc2ccccc2o1 19 atoms, 21 bonds }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } t0 = nanoClock(); MCSResult res = findMCS(mols); std::cout << "MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " @@ -195,7 +201,9 @@ void test45() { "CHEMBL359567", "CCCc1c(OC)ccc2nc3c(c(CC)c21)Cn1c-3cc2c(c1=O)COC(=O)C2(O)CC CHEMBL373316", }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } t0 = nanoClock(); MCSResult res = findMCS(mols); std::cout << "MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " @@ -224,7 +232,9 @@ void test3() { "CC1(C)NC(C)(C)CC(NC(=O)Cc2ccccc2)C1 CHEMBL1703640", //# 3 . 1 14 14 0.08 sec MCS: CCCCNC(=O)Cc1ccccc1 }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } t0 = nanoClock(); MCSResult res = findMCS(mols); std::cout << "MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " @@ -245,9 +255,10 @@ void testRing1() { // original molecule "COCc1cnc(C(=O)OC(C)C)c2[nH]ccc(Oc4ccc(Cl)cc4)cccc12", // ring 3 removed }; - for (auto& i : smi) + for (auto& i : smi) { mols.push_back( ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); // with RING INFO + } { MCSParameters p; @@ -324,9 +335,10 @@ void test504() { } std::cout << "Query +MAP " << MolToSmiles(*qm) << "\n"; mols.push_back(ROMOL_SPTR(qm)); // with RING INFO - for (size_t i = 1; i < sizeof(smi) / sizeof(smi[0]); i++) + for (size_t i = 1; i < sizeof(smi) / sizeof(smi[0]); i++) { mols.push_back( ROMOL_SPTR(SmilesToMol(getSmilesOnly(smi[i])))); // with RING INFO + } t0 = nanoClock(); MCSResult res = findMCS(mols); std::cout << "MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " @@ -363,9 +375,10 @@ void test18() { } std::cout << "Query +MAP " << MolToSmiles(*qm) << "\n"; mols.push_back(ROMOL_SPTR(qm)); // with RING INFO - for (size_t i = 1; i < sizeof(smi) / sizeof(smi[0]); i++) + for (size_t i = 1; i < sizeof(smi) / sizeof(smi[0]); i++) { mols.push_back( ROMOL_SPTR(SmilesToMol(getSmilesOnly(smi[i])))); // with RING INFO + } t0 = nanoClock(); MCSResult res = findMCS(mols); std::cout << "MCS: " << res.SmartsString << " " << res.NumAtoms << " atoms, " @@ -384,7 +397,9 @@ void testThreshold() { "CCC", "CCCO", "CCCN", "CC", // "CCC", "CC", //th=0.5 }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } findMCS(mols); MCSParameters p; p.Threshold = 0.7; @@ -434,7 +449,9 @@ void test330() { //# 330 F 42 41 30.93 sec MCS: //[#6]-[#6](-[#7]-[#6](-[#6](-[#6])-[#7]-[#6](-[#6](-[#6])-[#7]-[#6](-[#6](-[#6]-[#6]-[#6])-[#7]-[#6](-[#6](-[#6])-[#7]-[#6](-[#6])=[#8])=[#8])=[#8])=[#8])=[#8])-[#6](-[#7]-[#6](-[#6]-[#6](:[#6]):[#6]:[#6]:[#6]:[#6])-[#6](-[#8])=[#8])=[#8] }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } MCSParameters p; t0 = nanoClock(); MCSResult res = findMCS(mols, &p); @@ -463,7 +480,9 @@ void testTarget_no_10188_30149() { "COc1ccccc1Nc1ccc2c(c1)[nH]nc2-c1ccccc1 CHEMBL254443", "CN(C)CCNC(=O)c1cccc(-c2[nH]nc3cc(Nc4ccccc4Cl)ccc32)c1 CHEMBL198821", }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } MCSParameters p; t0 = nanoClock(); MCSResult res = findMCS(mols, &p); @@ -501,7 +520,9 @@ void testTarget_no_10188_49064() { "Cn1c(=O)c(-c2c(Cl)cccc2Cl)cc2cnc(Nc3ccc(I)cc3)nc21", "CN1CCN(C(=O)c2ccc(Nc3ncc4cc(-c5c(Cl)cccc5Cl)c(=O)n(C)c4n3)cc2)CC1", }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } MCSParameters p; t0 = nanoClock(); MCSResult res = findMCS(mols, &p); @@ -531,7 +552,9 @@ void testSegFault() { "O=C1CN(CCc2ccccc2)CCN1CCOC(c1ccc(F)cc1)c1ccc(F)cc1", "CN(CCOC(c1ccccc1)c1ccccc1)CCN(C)CCc1ccc(F)cc1", }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } { MCSParameters p; p.BondCompareParameters.RingMatchesRingOnly = true; @@ -579,7 +602,9 @@ void testAtomCompareIsotopes() { "CC[13NH2]", "CC[13CH3]", }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } MCSParameters p; p.AtomTyper = MCSAtomCompareIsotopes; t0 = nanoClock(); @@ -601,7 +626,9 @@ void testAtomCompareAnyAtom() { "c1ccccc1F", // opt "c1ccccc1N", // opt }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } MCSParameters p; p.AtomTyper = MCSAtomCompareAny; t0 = nanoClock(); @@ -624,7 +651,9 @@ void testAtomCompareAnyAtomBond() { "c1ccccc1F", // opt "c1ccccc1N", // opt }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } t0 = nanoClock(); MCSParameters p; p.AtomTyper = MCSAtomCompareAny; @@ -645,7 +674,9 @@ void testAtomCompareAnyHeavyAtom() { const char* smi[] = { "[H]c1ccccc1C", "[H]c1ccccc1O", // H matches H, O matches C }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i),0,false))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i), 0, false))); + } MCSParameters p; p.AtomTyper = MCSAtomCompareAnyHeavyAtom; t0 = nanoClock(); @@ -665,7 +696,9 @@ void testAtomCompareAnyHeavyAtom1() { const char* smi[] = { "[H]c1ccccc1C", "Oc1ccccc1O", // O matches C, H does not match O }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i),0,false))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i), 0, false))); + } MCSParameters p; p.AtomTyper = MCSAtomCompareAnyHeavyAtom; t0 = nanoClock(); @@ -714,7 +747,9 @@ void testSimple() { "NC(C(C(C)C)NC(CNC(C3NC(=O)CC3)=O)=O)=O)CSSCC(C(O)=O)NC(=O)C3N(" "CCC3O)C(=O)C(Cc3ccccc3)NC(=O)C(CSSC2)NC1=O CHEMBL1076370", }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } { MCSParameters p; p.BondCompareParameters.RingMatchesRingOnly = true; @@ -769,7 +804,9 @@ void testSimpleFast() { "COCc1c(ncc2[nH]c3cccc(Oc4ccc(Cl)cc4)c3c12)C(=O)OC(C)C", "COCc1cnc(C(=O)OC(C)C)c2[nH]c3cc(Oc4ccc(Cl)cc4)ccc3c12", }; - for (auto& i : smi) mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + for (auto& i : smi) { + mols.push_back(ROMOL_SPTR(SmilesToMol(getSmilesOnly(i)))); + } MCSParameters p; t0 = nanoClock(); MCSResult res = findMCS(mols, &p); @@ -1152,13 +1189,14 @@ void testGithub631() { "Cc1cc2c(cc1C)C(=O)N([C@@H]1CCC(=O)NC1=O)C2=O", }; - for (int pass = 0; pass < 2; ++pass, mols.clear()) + for (int pass = 0; pass < 2; ++pass, mols.clear()) { for (auto& i : smi) { RWMol* m = SmilesToMol(getSmilesOnly(i)); TEST_ASSERT(m); - if (0 == pass) + if (0 == pass) { mols.clear(); // use a pair of the same molecules only. On the second + } // pass use all. mols.push_back(ROMOL_SPTR(m)); @@ -1196,6 +1234,7 @@ void testGithub631() { BOOST_LOG(rdInfoLog) << "============================================" << std::endl; } + } BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } diff --git a/Code/GraphMol/FileParsers/ForwardSDMolSupplier.cpp b/Code/GraphMol/FileParsers/ForwardSDMolSupplier.cpp index f6cc44284..58497388c 100644 --- a/Code/GraphMol/FileParsers/ForwardSDMolSupplier.cpp +++ b/Code/GraphMol/FileParsers/ForwardSDMolSupplier.cpp @@ -98,8 +98,9 @@ void ForwardSDMolSupplier::readMolProps(ROMol *mol) { while (stmp.length() != 0) { d_line++; std::getline(*dp_inStream, tempStr); - if (dp_inStream->eof()) + if (dp_inStream->eof()) { throw FileParseException("End of data field name not found"); + } } } else { dlabel = tempStr.substr(sl + 1, se - sl - 1); @@ -200,8 +201,9 @@ ROMol *ForwardSDMolSupplier::_next() { // there's a special case when trying to read an empty string that // we get an empty molecule after only reading a single line without any // additional error state. - if (!res && dp_inStream->eof() && (line - d_line < 2)) + if (!res && dp_inStream->eof() && (line - d_line < 2)) { df_eofHitOnRead = true; + } d_line = line; if (res) { this->readMolProps(res); @@ -216,7 +218,9 @@ ROMol *ForwardSDMolSupplier::_next() { } } } catch (FileParseException &fe) { - if (d_line < static_cast(line)) d_line = line; + if (d_line < static_cast(line)) { + d_line = line; + } // we couldn't read a mol block or the data for the molecule. In this case // advance forward in the stream until we hit the next record and then // rethrow @@ -234,7 +238,9 @@ ROMol *ForwardSDMolSupplier::_next() { std::getline(*dp_inStream, tempStr); } } catch (MolSanitizeException &se) { - if (d_line < static_cast(line)) d_line = line; + if (d_line < static_cast(line)) { + d_line = line; + } // We couldn't sanitize a molecule we got - write out an error message and // move to // the beginning of the next molecule @@ -245,15 +251,21 @@ ROMol *ForwardSDMolSupplier::_next() { d_line++; std::getline(*dp_inStream, tempStr); - if (dp_inStream->eof()) df_eofHitOnRead = true; + if (dp_inStream->eof()) { + df_eofHitOnRead = true; + } while (!dp_inStream->eof() && !dp_inStream->fail() && (tempStr[0] != '$' || tempStr.substr(0, 4) != "$$$$")) { d_line++; std::getline(*dp_inStream, tempStr); } } catch (...) { - if (dp_inStream->eof()) df_eofHitOnRead = true; - if (d_line < static_cast(line)) d_line = line; + if (dp_inStream->eof()) { + df_eofHitOnRead = true; + } + if (d_line < static_cast(line)) { + d_line = line; + } BOOST_LOG(rdErrorLog) << "Unexpected error hit on line " << d_line << std::endl; @@ -261,7 +273,9 @@ ROMol *ForwardSDMolSupplier::_next() { << "ERROR: moving to the beginning of the next molecule\n"; d_line++; std::getline(*dp_inStream, tempStr); - if (dp_inStream->eof()) df_eofHitOnRead = true; + if (dp_inStream->eof()) { + df_eofHitOnRead = true; + } while (!dp_inStream->eof() && !dp_inStream->fail() && (tempStr[0] != '$' || tempStr.substr(0, 4) != "$$$$")) { d_line++; diff --git a/Code/GraphMol/FileParsers/Mol2FileParser.cpp b/Code/GraphMol/FileParsers/Mol2FileParser.cpp index 33fad50a2..eb0b5dddd 100644 --- a/Code/GraphMol/FileParsers/Mol2FileParser.cpp +++ b/Code/GraphMol/FileParsers/Mol2FileParser.cpp @@ -227,10 +227,11 @@ void guessFormalCharges(RWMol *res) { int nElectrons = PeriodicTable::getTable()->getNouterElecs(at->getAtomicNum()); int assignChg; - if (nElectrons >= 4) + if (nElectrons >= 4) { assignChg = expVal - (*valens.begin()); - else + } else { assignChg = (*valens.begin()) - expVal; + } if (assignChg > 0 && nElectrons >= 4) { for (vi = valens.begin(); vi != valens.end(); ++vi) { // Since we do this only for nocharged atoms we can get away without diff --git a/Code/GraphMol/FileParsers/MolFileParser.cpp b/Code/GraphMol/FileParsers/MolFileParser.cpp index 04365c6e7..1847b020a 100644 --- a/Code/GraphMol/FileParsers/MolFileParser.cpp +++ b/Code/GraphMol/FileParsers/MolFileParser.cpp @@ -61,7 +61,9 @@ int toInt(const std::string &input, bool acceptSpaces) { res = strtol(input.c_str(), nullptr, 10); if (!res && !acceptSpaces && input[0] == ' ') { std::string trimmed = boost::trim_copy(input); - if (trimmed.length() == 0) throw boost::bad_lexical_cast(); + if (trimmed.length() == 0) { + throw boost::bad_lexical_cast(); + } } return res; } @@ -70,7 +72,9 @@ double toDouble(const std::string &input, bool acceptSpaces) { double res = atof(input.c_str()); if (res == 0.0 && !acceptSpaces && input[0] == ' ') { std::string trimmed = boost::trim_copy(input); - if (trimmed.length() == 0) throw boost::bad_lexical_cast(); + if (trimmed.length() == 0) { + throw boost::bad_lexical_cast(); + } } return res; } @@ -110,7 +114,9 @@ std::string getV3000Line(std::istream *inStream, unsigned int &line) { Atom *replaceAtomWithQueryAtom(RWMol *mol, Atom *atom) { PRECONDITION(mol, "bad molecule"); PRECONDITION(atom, "bad atom"); - if (atom->hasQuery()) return atom; + if (atom->hasQuery()) { + return atom; + } QueryAtom qa(*atom); unsigned int idx = atom->getIdx(); @@ -148,8 +154,7 @@ void completeMolQueries(RWMol *mol, int magicVal = 0xDEADBEEF) { for (ROMol::AtomIterator ai = mol->beginAtoms(); ai != mol->endAtoms(); ++ai) { if ((*ai)->hasQuery()) { - ATOM_EQUALS_QUERY *query = - static_cast((*ai)->getQuery()); + auto *query = static_cast((*ai)->getQuery()); completeQueryAndChildren(query, *ai, magicVal); } } @@ -288,7 +293,9 @@ void ParseOldAtomList(RWMol *mol, const std::string &text, unsigned int line) { RANGE_CHECK(0, atNum, 200); // goofy! q->addChild( QueryAtom::QUERYATOM_QUERY::CHILD_TYPE(makeAtomNumQuery(atNum))); - if (!i) a.setAtomicNum(atNum); + if (!i) { + a.setAtomicNum(atNum); + } } a.setQuery(q); @@ -401,7 +408,7 @@ void ParsePXALine(RWMol *mol, const std::string &text, unsigned int line) { PRECONDITION(text.substr(0, 6) == "M PXA", "bad PXA line"); unsigned int pos = 7; try { - unsigned int atIdx = + auto atIdx = FileParserUtils::stripSpacesAndCast(text.substr(pos, 3)); pos += 3; mol->getAtomWithIdx(atIdx - 1)->setProp( @@ -480,7 +487,9 @@ void ParseSubstitutionCountLine(RWMol *mol, const std::string &text, Atom *atom = mol->getAtomWithIdx(aid - 1); if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") { count = FileParserUtils::toInt(text.substr(spos, 4)); - if (count == 0) continue; + if (count == 0) { + continue; + } ATOM_EQUALS_QUERY *q = makeAtomExplicitDegreeQuery(0); switch (count) { case -1: @@ -601,7 +610,9 @@ void ParseRingBondCountLine(RWMol *mol, const std::string &text, Atom *atom = mol->getAtomWithIdx(aid - 1); if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") { count = FileParserUtils::toInt(text.substr(spos, 4)); - if (count == 0) continue; + if (count == 0) { + continue; + } ATOM_EQUALS_QUERY *q = makeAtomRingBondCountQuery(0); switch (count) { case -1: @@ -836,7 +847,7 @@ void ParseMarvinSmartsLine(RWMol *mol, const std::string &text, std::string sma = text.substr(smartsStart); Atom *at = mol->getAtomWithIdx(idx); at->setProp(common_properties::MRV_SMA, sma); - RWMol *m = 0; + RWMol *m = nullptr; try { m = SmartsToMol(sma); } catch (...) { @@ -1191,7 +1202,9 @@ Atom *ParseMolFileAtomLine(const std::string text, RDGeom::Point3D &pos, } catch (boost::bad_lexical_cast &) { rnumber = -1; } - if (rnumber >= 0) res->setIsotope(rnumber); + if (rnumber >= 0) { + res->setIsotope(rnumber); + } } } } else if (symb == "D") { // mol blocks support "D" and "T" as shorthand... @@ -1203,8 +1216,9 @@ Atom *ParseMolFileAtomLine(const std::string text, RDGeom::Point3D &pos, res->setAtomicNum(1); res->setIsotope(3); } else { - if (symb.size() == 2 && symb[1] >= 'A' && symb[1] <= 'Z') + if (symb.size() == 2 && symb[1] >= 'A' && symb[1] <= 'Z') { symb[1] = static_cast(tolower(symb[1])); + } try { res->setAtomicNum(PeriodicTable::getTable()->getAtomicNumber(symb)); } catch (const Invar::Invariant &e) { @@ -1214,7 +1228,9 @@ Atom *ParseMolFileAtomLine(const std::string text, RDGeom::Point3D &pos, } // res->setPos(pX,pY,pZ); - if (chg != 0) res->setFormalCharge(4 - chg); + if (chg != 0) { + res->setFormalCharge(4 - chg); + } // FIX: this does not appear to be correct if (hCount == 1) { @@ -1629,19 +1645,19 @@ bool ParseMolBlockProperties(std::istream *inStream, unsigned int &line, ++line; tempStr = getLine(inStream); } - } else if (lineBeg == "M ALS") + } else if (lineBeg == "M ALS") { ParseNewAtomList(mol, tempStr, line); - else if (lineBeg == "M ISO") + } else if (lineBeg == "M ISO") { ParseIsotopeLine(mol, tempStr, line); - else if (lineBeg == "M RGP") + } else if (lineBeg == "M RGP") { ParseRGroupLabels(mol, tempStr, line); - else if (lineBeg == "M RBC") + } else if (lineBeg == "M RBC") { ParseRingBondCountLine(mol, tempStr, line); - else if (lineBeg == "M SUB") + } else if (lineBeg == "M SUB") { ParseSubstitutionCountLine(mol, tempStr, line); - else if (lineBeg == "M UNS") + } else if (lineBeg == "M UNS") { ParseUnsaturationLine(mol, tempStr, line); - else if (lineBeg == "M CHG") { + } else if (lineBeg == "M CHG") { ParseChargeLine(mol, tempStr, firstChargeLine, line); firstChargeLine = false; } else if (lineBeg == "M RAD") { @@ -1695,9 +1711,9 @@ bool ParseMolBlockProperties(std::istream *inStream, unsigned int &line, ParseSGroupV2000SBTLine(sGroupMap, mol, tempStr, line); /* SGroup parsing end */ - } else if (lineBeg == "M ZBO") + } else if (lineBeg == "M ZBO") { ParseZBOLine(mol, tempStr, line); - else if (lineBeg == "M ZCH") { + } else if (lineBeg == "M ZCH") { ParseZCHLine(mol, tempStr, line); } else if (lineBeg == "M HYD") { ParseHYDLine(mol, tempStr, line); @@ -1747,9 +1763,12 @@ Atom *ParseV3000AtomSymbol(std::string token, unsigned int &line) { for (std::vector::const_iterator stIt = splitToken.begin(); stIt != splitToken.end(); ++stIt) { std::string atSymb = boost::trim_copy(*stIt); - if (atSymb == "") continue; - if (atSymb.size() == 2 && atSymb[1] >= 'A' && atSymb[1] <= 'Z') + if (atSymb == "") { + continue; + } + if (atSymb.size() == 2 && atSymb[1] >= 'A' && atSymb[1] <= 'Z') { atSymb[1] = static_cast(tolower(atSymb[1])); + } int atNum = PeriodicTable::getTable()->getAtomicNumber(atSymb); if (!res) { @@ -1803,7 +1822,9 @@ Atom *ParseV3000AtomSymbol(std::string token, unsigned int &line) { } catch (boost::bad_lexical_cast &) { rnumber = -1; } - if (rnumber >= 0) res->setIsotope(rnumber); + if (rnumber >= 0) { + res->setIsotope(rnumber); + } } } else if (token == "D") { // mol blocks support "D" and "T" as // shorthand... handle that. @@ -1814,8 +1835,9 @@ Atom *ParseV3000AtomSymbol(std::string token, unsigned int &line) { res = new Atom(1); res->setIsotope(3); } else { - if (token.size() == 2 && token[1] >= 'A' && token[1] <= 'Z') + if (token.size() == 2 && token[1] >= 'A' && token[1] <= 'Z') { token[1] = static_cast(tolower(token[1])); + } res = new Atom(PeriodicTable::getTable()->getAtomicNumber(token)); } @@ -1928,7 +1950,9 @@ void ParseV3000AtomProps(RWMol *mol, Atom *&atom, typename T::iterator &token, if (!atom->hasQuery()) { atom = FileParserUtils::replaceAtomWithQueryAtom(mol, atom); } - if (hcount == -1) hcount = 0; + if (hcount == -1) { + hcount = 0; + } atom->expandQuery(makeAtomHCountQuery(hcount)); } } else if (prop == "UNSAT") { @@ -1944,7 +1968,9 @@ void ParseV3000AtomProps(RWMol *mol, Atom *&atom, typename T::iterator &token, if (!atom->hasQuery()) { atom = FileParserUtils::replaceAtomWithQueryAtom(mol, atom); } - if (rbcount == -1) rbcount = 0; + if (rbcount == -1) { + rbcount = 0; + } atom->expandQuery(makeAtomRingBondCountQuery(rbcount)); } } else if (prop == "VAL") { @@ -2233,9 +2259,9 @@ void ParseV3000BondBlock(std::istream *inStream, unsigned int &line, chiralityPossible = true; break; case 2: - if (bType == 1) + if (bType == 1) { bond->setBondDir(Bond::UNKNOWN); - else if (bType == 2) { + } else if (bType == 2) { bond->setBondDir(Bond::EITHERDOUBLE); bond->setStereo(Bond::STEREOANY); } @@ -2304,7 +2330,9 @@ void ProcessMolProps(RWMol *mol) { int totV; if (atom->getPropIfPresent(common_properties::molTotValence, totV) && !atom->hasProp("_ZBO_H")) { - if (totV == 0) continue; + if (totV == 0) { + continue; + } atom->setNoImplicit(true); if (totV == 15 // V2000 || totV == -1 // v3000 @@ -2373,10 +2401,15 @@ bool ParseV3000CTAB(std::istream *inStream, unsigned int &line, RWMol *mol, unsigned int nSgroups = 0, n3DConstraints = 0, chiralFlag = 0; (void)chiralFlag; // needs to be read - if (splitLine.size() > 2) nSgroups = FileParserUtils::toInt(splitLine[2]); - if (splitLine.size() > 3) + if (splitLine.size() > 2) { + nSgroups = FileParserUtils::toInt(splitLine[2]); + } + if (splitLine.size() > 3) { n3DConstraints = FileParserUtils::toInt(splitLine[3]); - if (splitLine.size() > 4) chiralFlag = FileParserUtils::toInt(splitLine[4]); + } + if (splitLine.size() > 4) { + chiralFlag = FileParserUtils::toInt(splitLine[4]); + } ParseV3000AtomBlock(inStream, line, nAtoms, mol, conf); if (nBonds) { @@ -2398,8 +2431,9 @@ bool ParseV3000CTAB(std::istream *inStream, unsigned int &line, RWMol *mol, errout << "BEGIN OBJ3D line not found on line " << line; throw FileParseException(errout.str()); } - for (unsigned int i = 0; i < n3DConstraints; ++i) + for (unsigned int i = 0; i < n3DConstraints; ++i) { tempStr = getV3000Line(inStream, line); + } tempStr = getV3000Line(inStream, line); boost::to_upper(tempStr); if (tempStr.length() < 9 || tempStr.substr(0, 9) != "END OBJ3D") { @@ -2488,7 +2522,9 @@ bool ParseV2000CTAB(std::istream *inStream, unsigned int &line, RWMol *mol, void finishMolProcessing(RWMol *res, bool chiralityPossible, bool sanitize, bool removeHs) { - if (!res) return; + if (!res) { + return; + } res->clearAllAtomBookmarks(); res->clearAllBondBookmarks(); @@ -2637,32 +2673,39 @@ RWMol *MolDataStreamToMol(std::istream *inStream, unsigned int &line, } try { spos = 6; - if (tempStr.size() >= 9) + if (tempStr.size() >= 9) { nLists = FileParserUtils::toInt(tempStr.substr(spos, 3), true); + } spos = 12; - if (tempStr.size() >= spos + 3) + if (tempStr.size() >= spos + 3) { chiralFlag = FileParserUtils::toInt(tempStr.substr(spos, 3), true); + } spos = 15; - if (tempStr.size() >= spos + 3) + if (tempStr.size() >= spos + 3) { nsText = FileParserUtils::toInt(tempStr.substr(spos, 3), true); + } spos = 18; - if (tempStr.size() >= spos + 3) + if (tempStr.size() >= spos + 3) { nRxnComponents = FileParserUtils::toInt(tempStr.substr(spos, 3), true); + } spos = 21; - if (tempStr.size() >= spos + 3) + if (tempStr.size() >= spos + 3) { nReactants = FileParserUtils::toInt(tempStr.substr(spos, 3), true); + } spos = 24; - if (tempStr.size() >= spos + 3) + if (tempStr.size() >= spos + 3) { nProducts = FileParserUtils::toInt(tempStr.substr(spos, 3), true); + } spos = 27; - if (tempStr.size() >= spos + 3) + if (tempStr.size() >= spos + 3) { nIntermediates = FileParserUtils::toInt(tempStr.substr(spos, 3), true); + } } catch (boost::bad_lexical_cast &) { // some SD files (such as some from NCI) lack all the extra information @@ -2734,7 +2777,9 @@ RWMol *MolDataStreamToMol(std::istream *inStream, unsigned int &line, BOOST_LOG(rdErrorLog) << " Unhandled CTAB feature: '" << e.message() << "'. Molecule skipped." << std::endl; - if (!inStream->eof()) tempStr = getLine(inStream); + if (!inStream->eof()) { + tempStr = getLine(inStream); + } ++line; while (!inStream->eof() && !inStream->fail() && tempStr.substr(0, 6) != "M END" && tempStr.substr(0, 4) != "$$$$") { @@ -2742,10 +2787,11 @@ RWMol *MolDataStreamToMol(std::istream *inStream, unsigned int &line, ++line; } if (!inStream->eof() || tempStr.substr(0, 6) == "M END" || - tempStr.substr(0, 4) == "$$$$") + tempStr.substr(0, 4) == "$$$$") { fileComplete = true; - else + } else { fileComplete = false; + } } catch (FileParseException &e) { // catch our exceptions and throw them back after cleanup delete res; diff --git a/Code/GraphMol/FileParsers/MolFileStereochem.cpp b/Code/GraphMol/FileParsers/MolFileStereochem.cpp index 6fdf26dbe..393cccff3 100644 --- a/Code/GraphMol/FileParsers/MolFileStereochem.cpp +++ b/Code/GraphMol/FileParsers/MolFileStereochem.cpp @@ -25,7 +25,9 @@ void WedgeBond(Bond *bond, unsigned int fromAtomIdx, const Conformer *conf) { PRECONDITION(conf, "no conformer"); PRECONDITION(&conf->getOwningMol() == &bond->getOwningMol(), "bond and conformer do not belong to same molecule"); - if (bond->getBondType() != Bond::SINGLE) return; + if (bond->getBondType() != Bond::SINGLE) { + return; + } Bond::BondDir dir = DetermineBondWedgeState(bond, fromAtomIdx, conf); if (dir == Bond::BEGINWEDGE || dir == Bond::BEGINDASH) { bond->setBondDir(dir); @@ -77,11 +79,14 @@ INT_MAP_INT pickBondsToWedge(const ROMol &mol) { bond->getBondDir() == Bond::BEGINDASH || bond->getBondDir() == Bond::UNKNOWN) { if (bond->getBeginAtom()->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW || - bond->getBeginAtom()->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW) + bond->getBeginAtom()->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW) { nChiralNbrs[bond->getBeginAtomIdx()] = noNbrs + 1; - else if (bond->getEndAtom()->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW || - bond->getEndAtom()->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW) + } else if (bond->getEndAtom()->getChiralTag() == + Atom::CHI_TETRAHEDRAL_CW || + bond->getEndAtom()->getChiralTag() == + Atom::CHI_TETRAHEDRAL_CCW) { nChiralNbrs[bond->getEndAtomIdx()] = noNbrs + 1; + } } } @@ -95,8 +100,9 @@ INT_MAP_INT pickBondsToWedge(const ROMol &mol) { continue; } Atom::ChiralType type = at->getChiralTag(); - if (type != Atom::CHI_TETRAHEDRAL_CW && type != Atom::CHI_TETRAHEDRAL_CCW) + if (type != Atom::CHI_TETRAHEDRAL_CW && type != Atom::CHI_TETRAHEDRAL_CCW) { continue; + } nChiralNbrs[at->getIdx()] = 0; chiNbrs = true; ROMol::ADJ_ITER nbrIdx, endNbrs; @@ -110,13 +116,17 @@ INT_MAP_INT pickBondsToWedge(const ROMol &mol) { continue; } type = nat->getChiralTag(); - if (type != Atom::CHI_TETRAHEDRAL_CW && type != Atom::CHI_TETRAHEDRAL_CCW) + if (type != Atom::CHI_TETRAHEDRAL_CW && + type != Atom::CHI_TETRAHEDRAL_CCW) { continue; + } nChiralNbrs[at->getIdx()] -= 1; } } std::vector indices(mol.getNumAtoms()); - for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) indices[i] = i; + for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) { + indices[i] = i; + } if (chiNbrs) { std::sort(indices.begin(), indices.end(), Rankers::argless(nChiralNbrs)); @@ -150,8 +160,9 @@ INT_MAP_INT pickBondsToWedge(const ROMol &mol) { Atom::ChiralType type = atom->getChiralTag(); // the indices are ordered such that all chiral atoms come first. If // this has no chiral flag, we can stop the whole loop: - if (type != Atom::CHI_TETRAHEDRAL_CW && type != Atom::CHI_TETRAHEDRAL_CCW) + if (type != Atom::CHI_TETRAHEDRAL_CW && type != Atom::CHI_TETRAHEDRAL_CCW) { break; + } RDKit::ROMol::OBOND_ITER_PAIR atomBonds = mol.getAtomBonds(atom); std::vector> nbrScores; while (atomBonds.first != atomBonds.second) { @@ -159,7 +170,9 @@ INT_MAP_INT pickBondsToWedge(const ROMol &mol) { ++atomBonds.first; // can only wedge single bonds: - if (bond->getBondType() != Bond::SINGLE) continue; + if (bond->getBondType() != Bond::SINGLE) { + continue; + } int bid = bond->getIdx(); if (res.find(bid) == res.end()) { @@ -261,7 +274,9 @@ Bond::BondDir DetermineBondWedgeState(const Bond *bond, tmpPt.z = 0.0; RDGeom::Point3D tmpVect = centerLoc.directionVector(tmpPt); double angle = refVect.signedAngleTo(tmpVect); - if (angle < 0.0) angle += 2. * M_PI; + if (angle < 0.0) { + angle += 2. * M_PI; + } auto nbrIt = neighborBondIndices.begin(); auto angleIt = neighborBondAngles.begin(); // find the location of this neighbor in our angle-sorted list @@ -357,8 +372,9 @@ void ClearSingleBondDirFlags(ROMol &mol) { for (RWMol::BondIterator bondIt = mol.beginBonds(); bondIt != mol.endBonds(); ++bondIt) { if ((*bondIt)->getBondType() == Bond::SINGLE) { - if ((*bondIt)->getBondDir() == Bond::UNKNOWN) + if ((*bondIt)->getBondDir() == Bond::UNKNOWN) { (*bondIt)->setProp(common_properties::_UnknownStereo, 1); + } (*bondIt)->setBondDir(Bond::NONE); } } diff --git a/Code/GraphMol/FileParsers/MolFileWriter.cpp b/Code/GraphMol/FileParsers/MolFileWriter.cpp index 97970dc57..de4314d15 100644 --- a/Code/GraphMol/FileParsers/MolFileWriter.cpp +++ b/Code/GraphMol/FileParsers/MolFileWriter.cpp @@ -69,10 +69,11 @@ int getQueryBondTopology(const Bond *bond) { } } if (qry->getDescription() == "BondInRing") { - if (qry->getNegation()) + if (qry->getNegation()) { res = 2; - else + } else { res = 1; + } } return res; } @@ -112,7 +113,9 @@ int getQueryBondSymbol(const Bond *bond) { // ok, it's a bond query we have a chance of dealing with int t1 = static_cast(child1->get())->getVal(); int t2 = static_cast(child2->get())->getVal(); - if (t1 > t2) std::swap(t1, t2); + if (t1 > t2) { + std::swap(t1, t2); + } if (t1 == Bond::SINGLE && t2 == Bond::DOUBLE) { res = 5; } else if (t1 == Bond::SINGLE && t2 == Bond::AROMATIC) { @@ -290,9 +293,10 @@ const std::string GetMolFileQueryInfo( } std::string molFileValue; if (!wrote_query && - atom->getPropIfPresent(common_properties::molFileValue, molFileValue)) + atom->getPropIfPresent(common_properties::molFileValue, molFileValue)) { ss << "V " << std::setw(3) << atom->getIdx() + 1 << " " << molFileValue << std::endl; + } } for (const auto atom : mol.atoms()) { if (listQs[atom->getIdx()]) { @@ -328,8 +332,9 @@ const std::string GetMolFileRGroupInfo(const RWMol &mol) { } } std::stringstream ss2; - if (nEntries) + if (nEntries) { ss2 << "M RGP" << std::setw(3) << nEntries << ss.str() << std::endl; + } return ss2.str(); } @@ -339,9 +344,10 @@ const std::string GetMolFileAliasInfo(const RWMol &mol) { atomIt != mol.endAtoms(); ++atomIt) { std::string lbl; if ((*atomIt)->getPropIfPresent(common_properties::molFileAlias, lbl)) { - if (!lbl.empty()) + if (!lbl.empty()) { ss << "A " << std::setw(3) << (*atomIt)->getIdx() + 1 << "\n" << lbl << "\n"; + } } } return ss.str(); @@ -387,7 +393,9 @@ const std::string GetMolFileZBOInfo(const RWMol &mol) { std::stringstream zchss; unsigned int nzch = 0; for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) { - if (!atomsAffected[i]) continue; + if (!atomsAffected[i]) { + continue; + } const Atom *atom = mol.getAtomWithIdx(i); nhyd++; hydss << boost::format(" %3d %3d") % (atom->getIdx() + 1) % @@ -464,35 +472,38 @@ const std::string AtomGetMolFileSymbol( } else { std::string symb; atom->getProp(common_properties::dummyLabel, symb); - if (symb == "*") + if (symb == "*") { res = "R"; - else if (symb == "X") + } else if (symb == "X") { res = "R"; - else if (symb == "Xa") + } else if (symb == "Xa") { res = "R1"; - else if (symb == "Xb") + } else if (symb == "Xb") { res = "R2"; - else if (symb == "Xc") + } else if (symb == "Xc") { res = "R3"; - else if (symb == "Xd") + } else if (symb == "Xd") { res = "R4"; - else if (symb == "Xf") + } else if (symb == "Xf") { res = "R5"; - else if (symb == "Xg") + } else if (symb == "Xg") { res = "R6"; - else if (symb == "Xh") + } else if (symb == "Xh") { res = "R7"; - else if (symb == "Xi") + } else if (symb == "Xi") { res = "R8"; - else if (symb == "Xj") + } else if (symb == "Xj") { res = "R9"; - else + } else { res = symb; + } } } // pad the end with spaces if (padWithSpaces) { - while (res.size() < 3) res += " "; + while (res.size() < 3) { + res += " "; + } } return res; } @@ -501,8 +512,10 @@ namespace { unsigned int getAtomParityFlag(const Atom *atom, const Conformer *conf) { PRECONDITION(atom, "bad atom"); PRECONDITION(conf, "bad conformer"); - if (!conf->is3D() || !(atom->getDegree() >= 3 && atom->getTotalDegree() == 4)) + if (!conf->is3D() || + !(atom->getDegree() >= 3 && atom->getTotalDegree() == 4)) { return 0; + } const ROMol &mol = atom->getOwningMol(); RDGeom::Point3D pos = conf->getAtomPos(atom->getIdx()); @@ -538,8 +551,12 @@ unsigned int getAtomParityFlag(const Atom *atom, const Conformer *conf) { } // namespace bool hasNonDefaultValence(const Atom *atom) { - if (atom->getNumRadicalElectrons() != 0) return true; - if (atom->hasQuery()) return false; + if (atom->getNumRadicalElectrons() != 0) { + return true; + } + if (atom->hasQuery()) { + return false; + } if (atom->getAtomicNum() == 1 || SmilesWrite ::inOrganicSubset(atom->getAtomicNum())) { // for the ones we "know", we may have to specify the valence if it's @@ -889,16 +906,21 @@ const std::string GetV3000MolFileAtomLine( } else { INT_VECT vals; getListQueryVals(atom->getQuery(), vals); - if (atom->getQuery()->getNegation()) + if (atom->getQuery()->getNegation()) { ss << " " << "\"NOT"; + } ss << " ["; for (unsigned int i = 0; i < vals.size(); ++i) { - if (i != 0) ss << ","; + if (i != 0) { + ss << ","; + } ss << PeriodicTable::getTable()->getElementSymbol(vals[i]); } ss << "]"; - if (atom->getQuery()->getNegation()) ss << "\""; + if (atom->getQuery()->getNegation()) { + ss << "\""; + } } ss << " " << x << " " << y << " " << z; @@ -921,7 +943,9 @@ const std::string GetV3000MolFileAtomLine( // We'll go with the int. int mass = static_cast(round(atom->getMass())); // dummies may have an isotope set but they always have a mass of zero: - if (!mass) mass = isotope; + if (!mass) { + mass = isotope; + } ss << " MASS=" << mass; } @@ -958,7 +982,9 @@ int GetV3000BondCode(const Bond *bond) { PRECONDITION(bond, ""); int res = 0; // FIX: should eventually recognize queries - if (bond->hasQuery()) res = getQueryBondSymbol(bond); + if (bond->hasQuery()) { + res = getQueryBondSymbol(bond); + } if (!res) { switch (bond->getBondType()) { case Bond::SINGLE: @@ -1055,22 +1081,22 @@ void appendEnhancedStereoGroups(std::string &res, const RWMol &tmol) { break; case RDKit::StereoGroupType::STEREO_OR: res += "STEREL"; - res += boost::lexical_cast(or_count); + res += std::to_string(or_count); ++or_count; break; case RDKit::StereoGroupType::STEREO_AND: res += "STERAC"; - res += boost::lexical_cast(and_count); + res += std::to_string(and_count); ++and_count; break; } res += " ATOMS=("; auto &atoms = group.getAtoms(); - res += boost::lexical_cast(atoms.size()); + res += std::to_string(atoms.size()); for (auto &&atom : atoms) { res += ' '; // atoms are 1 indexed in molfiles - res += boost::lexical_cast(atom->getIdx() + 1); + res += std::to_string(atom->getIdx() + 1); } res += ")\n"; } @@ -1252,13 +1278,15 @@ std::string MolToMolBlock(const ROMol &mol, bool includeStereo, int confId, RDUNUSED_PARAM(includeStereo); RDKit::Utils::LocaleSwitcher switcher; ROMol tromol(mol); - RWMol &trwmol = static_cast(tromol); + auto &trwmol = static_cast(tromol); // NOTE: kekulize the molecule before writing it out // because of the way mol files handle aromaticity if (trwmol.needsUpdatePropertyCache()) { trwmol.updatePropertyCache(false); } - if (kekulize) MolOps::Kekulize(trwmol); + if (kekulize) { + MolOps::Kekulize(trwmol); + } if (includeStereo && !trwmol.getNumConformers()) { // generate coordinates so that the stereo we generate makes sense diff --git a/Code/GraphMol/FileParsers/PDBParser.cpp b/Code/GraphMol/FileParsers/PDBParser.cpp index c5e5561c9..8bd01a176 100644 --- a/Code/GraphMol/FileParsers/PDBParser.cpp +++ b/Code/GraphMol/FileParsers/PDBParser.cpp @@ -51,17 +51,27 @@ static void PDBAtomLine(RWMol *mol, const char *ptr, unsigned int len, PRECONDITION(ptr, "bad char ptr"); std::string tmp; - if (len < 16) return; + if (len < 16) { + return; + } if ((flavor & 1) == 0) { // Ignore alternate locations of atoms. - if (len >= 17 && ptr[16] != ' ' && ptr[16] != 'A' && ptr[16] != '1') return; + if (len >= 17 && ptr[16] != ' ' && ptr[16] != 'A' && ptr[16] != '1') { + return; + } // Ignore XPLOR pseudo atoms - if (len >= 54 && !memcmp(ptr + 30, "9999.0009999.0009999.000", 24)) return; + if (len >= 54 && !memcmp(ptr + 30, "9999.0009999.0009999.000", 24)) { + return; + } // Ignore NMR pseudo atoms - if (ptr[12] == ' ' && ptr[13] == 'Q') return; + if (ptr[12] == ' ' && ptr[13] == 'Q') { + return; + } // Ignore PDB dummy residues - if (len >= 20 && !memcmp(ptr + 18, "DUM", 3)) return; + if (len >= 20 && !memcmp(ptr + 18, "DUM", 3)) { + return; + } } int serialno; @@ -87,23 +97,29 @@ static void PDBAtomLine(RWMol *mol, const char *ptr, unsigned int len, } else if (ptr[77] >= 'a' && ptr[77] <= 'z') { symb[1] = ptr[77]; symb[2] = '\0'; - } else + } else { symb[1] = '\0'; + } } else if (ptr[76] == ' ' && ptr[77] >= 'A' && ptr[77] <= 'Z') { symb[0] = ptr[77]; symb[1] = '\0'; - } else + } else { symb[0] = '\0'; + } } else if (len == 77) { if (ptr[76] >= 'A' && ptr[76] <= 'Z') { symb[0] = ptr[76]; symb[1] = '\0'; - } else + } else { symb[0] = '\0'; - } else + } + } else { symb[0] = '\0'; + } - if (symb[0]) atom = PDBAtomFromSymbol(symb); + if (symb[0]) { + atom = PDBAtomFromSymbol(symb); + } if (!atom) { // Attempt #2: Atomic Symbol from PDB atom name @@ -113,8 +129,9 @@ static void PDBAtomLine(RWMol *mol, const char *ptr, unsigned int len, if (ptr[14] >= 'a' && ptr[14] <= 'z') { symb[1] = ptr[14]; symb[2] = '\0'; - } else + } else { symb[1] = '\0'; + } } else if (ptr[12] >= 'A' && ptr[12] <= 'Z') { symb[0] = ptr[12]; symb[1] = ptr[13] + 32; // tolower @@ -127,12 +144,16 @@ static void PDBAtomLine(RWMol *mol, const char *ptr, unsigned int len, } else if (ptr[12] >= '0' && ptr[12] <= '9') { symb[0] = ptr[13]; symb[1] = '\0'; - } else + } else { symb[0] = '\0'; - } else + } + } else { symb[0] = '\0'; + } - if (symb[0]) atom = PDBAtomFromSymbol(symb); + if (symb[0]) { + atom = PDBAtomFromSymbol(symb); + } } if (!atom) { @@ -148,10 +169,12 @@ static void PDBAtomLine(RWMol *mol, const char *ptr, unsigned int len, RDGeom::Point3D pos; try { pos.x = FileParserUtils::toDouble(std::string(ptr + 30, 8)); - if (len >= 46) + if (len >= 46) { pos.y = FileParserUtils::toDouble(std::string(ptr + 38, 8)); - if (len >= 54) + } + if (len >= 54) { pos.z = FileParserUtils::toDouble(std::string(ptr + 46, 8)); + } } catch (boost::bad_lexical_cast &) { std::ostringstream errout; errout << "Problem with coordinates for PDB atom #" << serialno; @@ -166,7 +189,9 @@ static void PDBAtomLine(RWMol *mol, const char *ptr, unsigned int len, mol->addConformer(conf, false); } else { conf = &mol->getConformer(); - if (pos.z != 0.0) conf->set3D(true); + if (pos.z != 0.0) { + conf->set3D(true); + } } conf->setAtomPos(atom->getIdx(), pos); } @@ -174,33 +199,39 @@ static void PDBAtomLine(RWMol *mol, const char *ptr, unsigned int len, if (len >= 79) { int charge = 0; if (ptr[78] >= '1' && ptr[78] <= '9') { - if (ptr[79] == '-') + if (ptr[79] == '-') { charge = -(ptr[78] - '0'); - else if (ptr[79] == '+' || ptr[79] == ' ' || !ptr[79]) + } else if (ptr[79] == '+' || ptr[79] == ' ' || !ptr[79]) { charge = ptr[78] - '0'; + } } else if (ptr[78] == '+') { - if (ptr[79] >= '1' && ptr[79] <= '9') + if (ptr[79] >= '1' && ptr[79] <= '9') { charge = ptr[79] - '0'; - else if (ptr[79] == '+') + } else if (ptr[79] == '+') { charge = 2; - else if (ptr[79] != '0') + } else if (ptr[79] != '0') { charge = 1; + } } else if (ptr[78] == '-') { - if (ptr[79] >= '1' && ptr[79] <= '9') + if (ptr[79] >= '1' && ptr[79] <= '9') { charge = ptr[79] - '0'; - else if (ptr[79] == '-') + } else if (ptr[79] == '-') { charge = -2; - else if (ptr[79] != '0') + } else if (ptr[79] != '0') { charge = -1; + } } else if (ptr[78] == ' ') { - if (ptr[79] >= '1' && ptr[79] <= '9') + if (ptr[79] >= '1' && ptr[79] <= '9') { charge = ptr[79] - '0'; - else if (ptr[79] == '+') + } else if (ptr[79] == '+') { charge = 1; - else if (ptr[79] == '-') + } else if (ptr[79] == '-') { charge = -1; + } + } + if (charge != 0) { + atom->setFormalCharge(charge); } - if (charge != 0) atom->setFormalCharge(charge); } tmp = std::string(ptr + 12, 4); @@ -210,24 +241,30 @@ static void PDBAtomLine(RWMol *mol, const char *ptr, unsigned int len, if (len >= 20) { tmp = std::string(ptr + 17, 3); // boost::trim(tmp); - } else + } else { tmp = "UNL"; + } info->setResidueName(tmp); - if (ptr[0] == 'H') info->setIsHeteroAtom(true); - if (len >= 17) + if (ptr[0] == 'H') { + info->setIsHeteroAtom(true); + } + if (len >= 17) { tmp = std::string(ptr + 16, 1); - else + } else { tmp = " "; + } info->setAltLoc(tmp); - if (len >= 22) + if (len >= 22) { tmp = std::string(ptr + 21, 1); - else + } else { tmp = " "; + } info->setChainId(tmp); - if (len >= 27) + if (len >= 27) { tmp = std::string(ptr + 26, 1); - else + } else { tmp = " "; + } info->setInsertionCode(tmp); int resno = 1; @@ -273,7 +310,9 @@ static void PDBBondLine(RWMol *mol, const char *ptr, unsigned int len, PRECONDITION(mol, "bad mol"); PRECONDITION(ptr, "bad char ptr"); - if (len < 16) return; + if (len < 16) { + return; + } std::string tmp(ptr + 6, 5); bool fail = false; @@ -281,18 +320,26 @@ static void PDBBondLine(RWMol *mol, const char *ptr, unsigned int len, try { src = FileParserUtils::toInt(tmp); - if (amap.find(src) == amap.end()) return; + if (amap.find(src) == amap.end()) { + return; + } } catch (boost::bad_lexical_cast &) { fail = true; } if (!fail) { - if (len > 41) len = 41; + if (len > 41) { + len = 41; + } for (unsigned int pos = 11; pos + 5 <= len; pos += 5) { - if (!memcmp(ptr + pos, " ", 5)) break; + if (!memcmp(ptr + pos, " ", 5)) { + break; + } try { dst = FileParserUtils::toInt(std::string(ptr + pos, 5)); - if (dst == src || amap.find(dst) == amap.end()) continue; + if (dst == src || amap.find(dst) == amap.end()) { + continue; + } } catch (boost::bad_lexical_cast &) { fail = true; } @@ -307,42 +354,57 @@ static void PDBBondLine(RWMol *mol, const char *ptr, unsigned int len, if (src < dst) { if ((seen & 0x0f) == 0x01) { bmap[bond] = seen | 0x02; - if ((seen & 0x20) == 0) bond->setBondType(Bond::DOUBLE); + if ((seen & 0x20) == 0) { + bond->setBondType(Bond::DOUBLE); + } } else if ((seen & 0x0f) == 0x03) { bmap[bond] = seen | 0x04; - if ((seen & 0x40) == 0) bond->setBondType(Bond::TRIPLE); + if ((seen & 0x40) == 0) { + bond->setBondType(Bond::TRIPLE); + } } else if ((seen & 0x0f) == 0x07) { bmap[bond] = seen | 0x08; - if ((seen & 0x80) == 0) bond->setBondType(Bond::QUADRUPLE); + if ((seen & 0x80) == 0) { + bond->setBondType(Bond::QUADRUPLE); + } } } else /* src < dst */ { if ((seen & 0xf0) == 0x10) { bmap[bond] = seen | 0x20; - if ((seen & 0x02) == 0) bond->setBondType(Bond::DOUBLE); + if ((seen & 0x02) == 0) { + bond->setBondType(Bond::DOUBLE); + } } else if ((seen & 0xf0) == 0x30) { bmap[bond] = seen | 0x40; - if ((seen & 0x04) == 0) bond->setBondType(Bond::TRIPLE); + if ((seen & 0x04) == 0) { + bond->setBondType(Bond::TRIPLE); + } } else if ((seen & 0xf0) == 0x70) { bmap[bond] = seen | 0x80; - if ((seen & 0x08) == 0) bond->setBondType(Bond::QUADRUPLE); + if ((seen & 0x08) == 0) { + bond->setBondType(Bond::QUADRUPLE); + } } } } else if (!bond) { // Bonds in PDB file are explicit // if they are not sanitize friendly, set their order to zero - if (IsBlacklistedPair(amap[src], amap[dst])) + if (IsBlacklistedPair(amap[src], amap[dst])) { bond = new Bond(Bond::ZERO); - else + } else { bond = new Bond(Bond::SINGLE); + } bond->setOwningMol(mol); bond->setBeginAtom(amap[src]); bond->setEndAtom(amap[dst]); mol->addBond(bond, true); bmap[bond] = (src < dst) ? 0x01 : 0x10; - } else + } else { break; - } else + } + } else { break; + } } } @@ -357,13 +419,20 @@ static void PDBTitleLine(RWMol *mol, const char *ptr, unsigned int len) { PRECONDITION(mol, "bad mol"); PRECONDITION(ptr, "bad char ptr"); std::string title; - while (ptr[len - 1] == ' ') len--; - if (ptr[len - 1] == ';') len--; - if (len > 21 && !strncmp(ptr + 10, " MOLECULE: ", 11)) + while (ptr[len - 1] == ' ') { + len--; + } + if (ptr[len - 1] == ';') { + len--; + } + if (len > 21 && !strncmp(ptr + 10, " MOLECULE: ", 11)) { title = std::string(ptr + 21, len - 21); - else if (len > 10) + } else if (len > 10) { title = std::string(ptr + 10, len - 10); - if (!title.empty()) mol->setProp(common_properties::_Name, title); + } + if (!title.empty()) { + mol->setProp(common_properties::_Name, title); + } } static void PDBConformerLine(RWMol *mol, const char *ptr, unsigned int len, @@ -375,10 +444,12 @@ static void PDBConformerLine(RWMol *mol, const char *ptr, unsigned int len, RDGeom::Point3D pos; try { pos.x = FileParserUtils::toDouble(std::string(ptr + 30, 8)); - if (len >= 46) + if (len >= 46) { pos.y = FileParserUtils::toDouble(std::string(ptr + 38, 8)); - if (len >= 54) + } + if (len >= 54) { pos.z = FileParserUtils::toDouble(std::string(ptr + 46, 8)); + } } catch (boost::bad_lexical_cast &) { std::ostringstream errout; errout << "Problem with multi-conformer coordinates"; @@ -390,8 +461,9 @@ static void PDBConformerLine(RWMol *mol, const char *ptr, unsigned int len, conf->setId(mol->getNumConformers()); conf->set3D(pos.z != 0.0); mol->addConformer(conf, false); - } else if (pos.z != 0.0) + } else if (pos.z != 0.0) { conf->set3D(true); + } if (conformer_atmidx < rdcast(mol->getNumAtoms())) { conf->setAtomPos(conformer_atmidx, pos); @@ -443,14 +515,15 @@ static void StandardPDBResidueChirality(RWMol *mol) { atomIt != mol->endAtoms(); ++atomIt) { Atom *atom = *atomIt; if (atom->getChiralTag() != Atom::CHI_UNSPECIFIED) { - AtomPDBResidueInfo *info = (AtomPDBResidueInfo *)atom->getMonomerInfo(); + auto *info = (AtomPDBResidueInfo *)atom->getMonomerInfo(); if (info && info->getMonomerType() == AtomMonomerInfo::PDBRESIDUE && !info->getIsHeteroAtom() && !StandardPDBChiralAtom(info->getResidueName().c_str(), info->getName().c_str())) { atom->setChiralTag(Atom::CHI_UNSPECIFIED); - if (atom->hasProp(common_properties::_CIPCode)) + if (atom->hasProp(common_properties::_CIPCode)) { atom->clearProp(common_properties::_CIPCode); + } } } } @@ -492,8 +565,9 @@ RWMol *PDBBlockToMol(const char *str, bool sanitize, bool removeHs, len = (unsigned int)(next - str); if (next[1] == '\n') { next += 2; - } else + } else { next++; + } break; } else if (*next == '\n') { len = (unsigned int)(next - str); @@ -510,37 +584,53 @@ RWMol *PDBBlockToMol(const char *str, bool sanitize, bool removeHs, if (str[0] == 'A' && str[1] == 'T' && str[2] == 'O' && str[3] == 'M' && str[4] == ' ' && str[5] == ' ') { if (!multi_conformer) { - if (!mol) mol = new RWMol(); + if (!mol) { + mol = new RWMol(); + } PDBAtomLine(mol, str, len, flavor, amap); - } else + } else { PDBConformerLine(mol, str, len, conf, conformer_atmidx); + } // HETATM records } else if (str[0] == 'H' && str[1] == 'E' && str[2] == 'T' && str[3] == 'A' && str[4] == 'T' && str[5] == 'M') { if (!multi_conformer) { - if (!mol) mol = new RWMol(); + if (!mol) { + mol = new RWMol(); + } PDBAtomLine(mol, str, len, flavor, amap); - } else + } else { PDBConformerLine(mol, str, len, conf, conformer_atmidx); + } // CONECT records } else if (str[0] == 'C' && str[1] == 'O' && str[2] == 'N' && str[3] == 'E' && str[4] == 'C' && str[5] == 'T') { - if (mol && !multi_conformer) PDBBondLine(mol, str, len, amap, bmap); + if (mol && !multi_conformer) { + PDBBondLine(mol, str, len, amap, bmap); + } // COMPND records } else if (str[0] == 'C' && str[1] == 'O' && str[2] == 'M' && str[3] == 'P' && str[4] == 'N' && str[5] == 'D') { - if (!mol) mol = new RWMol(); - if (len > 10 && (str[9] == ' ' || !strncmp(str + 9, "2 MOLECULE: ", 12))) + if (!mol) { + mol = new RWMol(); + } + if (len > 10 && + (str[9] == ' ' || !strncmp(str + 9, "2 MOLECULE: ", 12))) { PDBTitleLine(mol, str, len); + } // HEADER records } else if (str[0] == 'H' && str[1] == 'E' && str[2] == 'A' && str[3] == 'D' && str[4] == 'E' && str[5] == 'R') { - if (!mol) mol = new RWMol(); + if (!mol) { + mol = new RWMol(); + } PDBTitleLine(mol, str, len < 50 ? len : 50); // ENDMDL records } else if (str[0] == 'E' && str[1] == 'N' && str[2] == 'D' && str[3] == 'M' && str[4] == 'D' && str[5] == 'L') { - if (!mol) break; + if (!mol) { + break; + } multi_conformer = true; conformer_atmidx = 0; conf = nullptr; @@ -548,12 +638,17 @@ RWMol *PDBBlockToMol(const char *str, bool sanitize, bool removeHs, str = next; } - if (!mol) return (RWMol *)nullptr; + if (!mol) { + return (RWMol *)nullptr; + } - if (proximityBonding) ConnectTheDots(mol, ctdIGNORE_H_H_CONTACTS); + if (proximityBonding) { + ConnectTheDots(mol, ctdIGNORE_H_H_CONTACTS); + } // flavor & 8 doesn't encode double bonds - if (proximityBonding || ((flavor & 8) != 0)) + if (proximityBonding || ((flavor & 8) != 0)) { StandardPDBResidueBondOrders(mol); + } BasicPDBCleanup(*mol); @@ -593,12 +688,14 @@ RWMol *PDBDataStreamToMol(std::istream *inStream, bool sanitize, bool removeHs, auto ptr = line.c_str(); // Check for END if (ptr[0] == 'E' && ptr[1] == 'N' && ptr[2] == 'D' && - (ptr[3] == ' ' || ptr[3] == '\r' || ptr[3] == '\n' || !ptr[3])) + (ptr[3] == ' ' || ptr[3] == '\r' || ptr[3] == '\n' || !ptr[3])) { break; + } // Check for ENDMDL if ((flavor & 2) != 0 && ptr[0] == 'E' && ptr[1] == 'N' && ptr[2] == 'D' && - ptr[3] == 'M' && ptr[4] == 'D' && ptr[5] == 'L') + ptr[3] == 'M' && ptr[4] == 'D' && ptr[5] == 'L') { break; + } } return PDBBlockToMol(buffer.c_str(), sanitize, removeHs, flavor, proximityBonding); diff --git a/Code/GraphMol/FileParsers/PDBSupplier.cpp b/Code/GraphMol/FileParsers/PDBSupplier.cpp index 3fee85160..58a641388 100644 --- a/Code/GraphMol/FileParsers/PDBSupplier.cpp +++ b/Code/GraphMol/FileParsers/PDBSupplier.cpp @@ -53,7 +53,9 @@ ROMol *PDBMolSupplier::next() { } bool PDBMolSupplier::atEnd() { - if (dp_inStream->eof()) return true; + if (dp_inStream->eof()) { + return true; + } int ch = dp_inStream->peek(); return ch == -1; } diff --git a/Code/GraphMol/FileParsers/PDBWriter.cpp b/Code/GraphMol/FileParsers/PDBWriter.cpp index 662322da9..ef7aa4635 100644 --- a/Code/GraphMol/FileParsers/PDBWriter.cpp +++ b/Code/GraphMol/FileParsers/PDBWriter.cpp @@ -54,27 +54,35 @@ std::string GetPDBAtomLine(const Atom *atom, const Conformer *conf, default: at1 = symb[0]; at2 = symb[1]; - if (at2 >= 'a' && at2 <= 'z') at2 -= 32; // toupper + if (at2 >= 'a' && at2 <= 'z') { + at2 -= 32; // toupper + } break; } - AtomPDBResidueInfo *info = (AtomPDBResidueInfo *)(atom->getMonomerInfo()); + auto *info = (AtomPDBResidueInfo *)(atom->getMonomerInfo()); if (info && info->getMonomerType() == AtomMonomerInfo::PDBRESIDUE) { ss << (info->getIsHeteroAtom() ? "HETATM" : "ATOM "); ss << std::setw(5) << atom->getIdx() + 1; ss << ' '; ss << info->getName(); // Always 4 characters? const char *ptr = info->getAltLoc().c_str(); - if (*ptr == '\0') ptr = " "; + if (*ptr == '\0') { + ptr = " "; + } ss << *ptr; ss << info->getResidueName(); // Always 3 characters? ss << ' '; ptr = info->getChainId().c_str(); - if (*ptr == '\0') ptr = " "; + if (*ptr == '\0') { + ptr = " "; + } ss << *ptr; ss << std::setw(4) << info->getResidueNumber(); ptr = info->getInsertionCode().c_str(); - if (*ptr == '\0') ptr = " "; + if (*ptr == '\0') { + ptr = " "; + } ss << *ptr; ss << " "; } else { @@ -135,8 +143,9 @@ std::string GetPDBAtomLine(const Atom *atom, const Conformer *conf, } else if (charge < 0 && charge > -10) { ss << (char)('0' - charge); ss << '-'; - } else + } else { ss << " "; + } return ss.str(); } @@ -152,14 +161,20 @@ std::string GetPDBBondLines(const Atom *atom, bool all, bool both, bool mult, Bond *bptr = (*mol)[*bondIt.first]; Atom *nptr = bptr->getOtherAtom(atom); unsigned int dst = nptr->getIdx() + 1; - if (dst < src && !both) continue; + if (dst < src && !both) { + continue; + } Bond::BondType btype = Bond::SINGLE; - if (mult) btype = bptr->getBondType(); + if (mult) { + btype = bptr->getBondType(); + } switch (btype) { default: case Bond::SINGLE: case Bond::AROMATIC: - if (all) v.push_back(dst); + if (all) { + v.push_back(dst); + } break; case Bond::QUADRUPLE: v.push_back(dst); @@ -173,14 +188,18 @@ std::string GetPDBBondLines(const Atom *atom, bool all, bool both, bool mult, } } - unsigned int count = rdcast(v.size()); - if (count == 0) return ""; + auto count = rdcast(v.size()); + if (count == 0) { + return ""; + } std::sort(v.begin(), v.end()); std::stringstream ss; for (unsigned int i = 0; i < count; i++) { if ((i & 3) == 0) { - if (i != 0) ss << '\n'; + if (i != 0) { + ss << '\n'; + } ss << "CONECT"; ss << std::setw(5) << src; conect_count++; @@ -232,7 +251,7 @@ std::string MolToPDBBody(const ROMol &mol, const Conformer *conf, std::string MolToPDBBlock(const ROMol &imol, int confId, unsigned int flavor) { ROMol mol(imol); - RWMol &trwmol = static_cast(mol); + auto &trwmol = static_cast(mol); MolOps::Kekulize(trwmol); Utils::LocaleSwitcher ls; @@ -320,7 +339,9 @@ PDBWriter::PDBWriter(std::ostream *outStream, bool takeOwnership, PDBWriter::~PDBWriter() { // close the writer if it's still open: - if (dp_ostream != nullptr) close(); + if (dp_ostream != nullptr) { + close(); + } } void PDBWriter::write(const ROMol &mol, int confId) { @@ -338,7 +359,9 @@ void PDBWriter::write(const ROMol &mol, int confId) { // write the molecule (*dp_ostream) << MolToPDBBlock(mol, confId, d_flavor); - if (d_flavor & 1) (*dp_ostream) << "ENDMDL\n"; + if (d_flavor & 1) { + (*dp_ostream) << "ENDMDL\n"; + } } void MolToPDBFile(const ROMol &mol, const std::string &fname, int confId, diff --git a/Code/GraphMol/FileParsers/ProximityBonds.cpp b/Code/GraphMol/FileParsers/ProximityBonds.cpp index c737200c5..bad2cf01d 100644 --- a/Code/GraphMol/FileParsers/ProximityBonds.cpp +++ b/Code/GraphMol/FileParsers/ProximityBonds.cpp @@ -30,18 +30,25 @@ struct ProximityEntry { }; static bool IsBonded(ProximityEntry *p, ProximityEntry *q, unsigned int flags) { - if (flags & ctdIGNORE_H_H_CONTACTS && p->elem == 1 && q->elem == 1) + if (flags & ctdIGNORE_H_H_CONTACTS && p->elem == 1 && q->elem == 1) { return false; + } double dx = (double)p->x - (double)q->x; double dist2 = dx * dx; - if (dist2 > MAXDIST2) return false; + if (dist2 > MAXDIST2) { + return false; + } double dy = (double)p->y - (double)q->y; dist2 += dy * dy; - if (dist2 > MAXDIST2) return false; + if (dist2 > MAXDIST2) { + return false; + } double dz = (double)p->z - (double)q->z; dist2 += dz * dz; - if (dist2 > MAXDIST2 || dist2 < MINDIST2) return false; + if (dist2 > MAXDIST2 || dist2 < MINDIST2) { + return false; + } double radius = (double)p->r + (double)q->r + EXTDIST; return dist2 <= radius * radius; @@ -59,31 +66,35 @@ static bool IsBlacklistedAtom(Atom *atom) { int elem = atom->getAtomicNum(); // make an inverse query (non-metals and metaloids) if ((5 <= elem && elem <= 8) || (14 <= elem && elem <= 16) || - (32 <= elem && elem <= 34) || (51 <= elem && elem <= 52)) + (32 <= elem && elem <= 34) || (51 <= elem && elem <= 52)) { return false; - else + } else { return true; + } } bool IsBlacklistedPair(Atom *beg_atom, Atom *end_atom) { PRECONDITION(beg_atom, "empty atom"); PRECONDITION(end_atom, "empty atom"); - AtomPDBResidueInfo *beg_info = - (AtomPDBResidueInfo *)beg_atom->getMonomerInfo(); - AtomPDBResidueInfo *end_info = - (AtomPDBResidueInfo *)end_atom->getMonomerInfo(); - if (!beg_info || beg_info->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) + auto *beg_info = (AtomPDBResidueInfo *)beg_atom->getMonomerInfo(); + auto *end_info = (AtomPDBResidueInfo *)end_atom->getMonomerInfo(); + if (!beg_info || beg_info->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) { return false; - if (!end_info || end_info->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) + } + if (!end_info || end_info->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) { return false; + } if (!SamePDBResidue(beg_info, end_info)) { - if (IsBlacklistedAtom(beg_atom) || IsBlacklistedAtom(end_atom)) return true; + if (IsBlacklistedAtom(beg_atom) || IsBlacklistedAtom(end_atom)) { + return true; + } // Dont make bonds to waters if (beg_info->getResidueName() == "HOH" || - end_info->getResidueName() == "HOH") + end_info->getResidueName() == "HOH") { return true; + } } return false; } @@ -160,9 +171,8 @@ static void ConnectTheDots_Large(RWMol *mol, unsigned int flags) { memset(HashTable, -1, sizeof(HashTable)); unsigned int count = mol->getNumAtoms(); - ProximityEntry *tmp = - (ProximityEntry *)malloc(count * sizeof(ProximityEntry)); - CHECK_INVARIANT(tmp,"bad allocation"); + auto *tmp = (ProximityEntry *)malloc(count * sizeof(ProximityEntry)); + CHECK_INVARIANT(tmp, "bad allocation"); PeriodicTable *table = PeriodicTable::getTable(); Conformer *conf = &mol->getConformer(); @@ -181,8 +191,8 @@ static void ConnectTheDots_Large(RWMol *mol, unsigned int flags) { int hash = HASHX * (int)(p.x / MAXDIST) + HASHY * (int)(p.y / MAXDIST) + HASHZ * (int)(p.z / MAXDIST); - for (int dx = -HASHX; dx <= HASHX; dx += HASHX) - for (int dy = -HASHY; dy <= HASHY; dy += HASHY) + for (int dx = -HASHX; dx <= HASHX; dx += HASHX) { + for (int dy = -HASHY; dy <= HASHY; dy += HASHY) { for (int dz = -HASHZ; dz <= HASHZ; dz += HASHZ) { int probe = hash + dx + dy + dz; int list = HashTable[probe & HASHMASK]; @@ -190,11 +200,14 @@ static void ConnectTheDots_Large(RWMol *mol, unsigned int flags) { ProximityEntry *tmpj = &tmp[list]; if (tmpj->hash == probe && IsBonded(tmpi, tmpj, flags) && !mol->getBondBetweenAtoms(tmpi->atm, tmpj->atm) && - !IsBlacklistedPair(atom, mol->getAtomWithIdx(tmpj->atm))) + !IsBlacklistedPair(atom, mol->getAtomWithIdx(tmpj->atm))) { mol->addBond(tmpi->atm, tmpj->atm, Bond::SINGLE); + } list = tmpj->next; } } + } + } int list = hash & HASHMASK; tmpi->next = HashTable[list]; HashTable[list] = i; @@ -206,8 +219,7 @@ static void ConnectTheDots_Large(RWMol *mol, unsigned int flags) { unsigned int elem = atom->getAtomicNum(); // detect multivalent Hs, which could happen with ConnectTheDots if (elem == 1 && atom->getDegree() > 1) { - AtomPDBResidueInfo *atom_info = - (AtomPDBResidueInfo *)(atom->getMonomerInfo()); + auto *atom_info = (AtomPDBResidueInfo *)(atom->getMonomerInfo()); // cut all but shortest Bond RDGeom::Point3D p = conf->getAtomPos(i); RDKit::RWMol::ADJ_ITER nbr, end_nbr; @@ -217,7 +229,7 @@ static void ConnectTheDots_Large(RWMol *mol, unsigned int flags) { while (nbr != end_nbr) { RDGeom::Point3D pn = conf->getAtomPos(*nbr); float d = (p - pn).length(); - AtomPDBResidueInfo *n_info = + auto *n_info = (AtomPDBResidueInfo *)(mol->getAtomWithIdx(*nbr)->getMonomerInfo()); if (d < best && atom_info->getResidueNumber() == n_info->getResidueNumber()) { @@ -243,7 +255,9 @@ static void ConnectTheDots_Large(RWMol *mol, unsigned int flags) { } void ConnectTheDots(RWMol *mol, unsigned int flags) { - if (!mol || !mol->getNumConformers()) return; + if (!mol || !mol->getNumConformers()) { + return; + } // Determine optimal algorithm to use by getNumAtoms()? ConnectTheDots_Large(mol, flags); } @@ -273,159 +287,202 @@ static bool StandardPDBDoubleBond(unsigned int rescode, unsigned int atm1, case BCNAM('T', 'H', 'R'): case BCNAM('V', 'A', 'L'): if (atm1 == BCATM(' ', 'C', ' ', ' ') && - atm2 == BCATM(' ', 'O', ' ', ' ')) + atm2 == BCATM(' ', 'O', ' ', ' ')) { return true; + } break; case BCNAM('A', 'R', 'G'): if (atm1 == BCATM(' ', 'C', ' ', ' ') && - atm2 == BCATM(' ', 'O', ' ', ' ')) + atm2 == BCATM(' ', 'O', ' ', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', 'Z', ' ') && - atm2 == BCATM(' ', 'N', 'H', '2')) + atm2 == BCATM(' ', 'N', 'H', '2')) { return true; + } break; case BCNAM('A', 'S', 'N'): case BCNAM('A', 'S', 'P'): if (atm1 == BCATM(' ', 'C', ' ', ' ') && - atm2 == BCATM(' ', 'O', ' ', ' ')) + atm2 == BCATM(' ', 'O', ' ', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', 'G', ' ') && - atm2 == BCATM(' ', 'O', 'D', '1')) + atm2 == BCATM(' ', 'O', 'D', '1')) { return true; + } break; case BCNAM('G', 'L', 'N'): case BCNAM('G', 'L', 'U'): if (atm1 == BCATM(' ', 'C', ' ', ' ') && - atm2 == BCATM(' ', 'O', ' ', ' ')) + atm2 == BCATM(' ', 'O', ' ', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', 'D', ' ') && - atm2 == BCATM(' ', 'O', 'E', '1')) + atm2 == BCATM(' ', 'O', 'E', '1')) { return true; + } break; case BCNAM('H', 'I', 'S'): if (atm1 == BCATM(' ', 'C', ' ', ' ') && - atm2 == BCATM(' ', 'O', ' ', ' ')) + atm2 == BCATM(' ', 'O', ' ', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', 'D', '2') && - atm2 == BCATM(' ', 'C', 'G', ' ')) + atm2 == BCATM(' ', 'C', 'G', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', 'E', '1') && - atm2 == BCATM(' ', 'N', 'D', '1')) + atm2 == BCATM(' ', 'N', 'D', '1')) { return true; + } break; case BCNAM('P', 'H', 'E'): case BCNAM('T', 'Y', 'R'): if (atm1 == BCATM(' ', 'C', ' ', ' ') && - atm2 == BCATM(' ', 'O', ' ', ' ')) + atm2 == BCATM(' ', 'O', ' ', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', 'D', '1') && - atm2 == BCATM(' ', 'C', 'G', ' ')) + atm2 == BCATM(' ', 'C', 'G', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', 'D', '2') && - atm2 == BCATM(' ', 'C', 'E', '2')) + atm2 == BCATM(' ', 'C', 'E', '2')) { return true; + } if (atm1 == BCATM(' ', 'C', 'E', '1') && - atm2 == BCATM(' ', 'C', 'Z', ' ')) + atm2 == BCATM(' ', 'C', 'Z', ' ')) { return true; + } break; case BCNAM('T', 'R', 'P'): if (atm1 == BCATM(' ', 'C', ' ', ' ') && - atm2 == BCATM(' ', 'O', ' ', ' ')) + atm2 == BCATM(' ', 'O', ' ', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', 'D', '1') && - atm2 == BCATM(' ', 'C', 'G', ' ')) + atm2 == BCATM(' ', 'C', 'G', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', 'D', '2') && - atm2 == BCATM(' ', 'C', 'E', '2')) + atm2 == BCATM(' ', 'C', 'E', '2')) { return true; + } if (atm1 == BCATM(' ', 'C', 'E', '3') && - atm2 == BCATM(' ', 'C', 'Z', '3')) + atm2 == BCATM(' ', 'C', 'Z', '3')) { return true; + } if (atm1 == BCATM(' ', 'C', 'H', '2') && - atm2 == BCATM(' ', 'C', 'Z', '2')) + atm2 == BCATM(' ', 'C', 'Z', '2')) { return true; + } break; case BCNAM(' ', ' ', 'A'): case BCNAM(' ', 'D', 'A'): if (atm1 == BCATM(' ', 'C', '6', ' ') && - atm2 == BCATM(' ', 'N', '1', ' ')) + atm2 == BCATM(' ', 'N', '1', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', '2', ' ') && - atm2 == BCATM(' ', 'N', '3', ' ')) + atm2 == BCATM(' ', 'N', '3', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', '4', ' ') && - atm2 == BCATM(' ', 'C', '5', ' ')) + atm2 == BCATM(' ', 'C', '5', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', '8', ' ') && - atm2 == BCATM(' ', 'N', '7', ' ')) + atm2 == BCATM(' ', 'N', '7', ' ')) { return true; + } if (atm1 == BCATM(' ', 'O', 'P', '1') && - atm2 == BCATM(' ', 'P', ' ', ' ')) + atm2 == BCATM(' ', 'P', ' ', ' ')) { return true; + } break; case BCNAM(' ', ' ', 'G'): case BCNAM(' ', 'D', 'G'): if (atm1 == BCATM(' ', 'C', '6', ' ') && - atm2 == BCATM(' ', 'O', '6', ' ')) + atm2 == BCATM(' ', 'O', '6', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', '2', ' ') && - atm2 == BCATM(' ', 'N', '3', ' ')) + atm2 == BCATM(' ', 'N', '3', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', '4', ' ') && - atm2 == BCATM(' ', 'C', '5', ' ')) + atm2 == BCATM(' ', 'C', '5', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', '8', ' ') && - atm2 == BCATM(' ', 'N', '7', ' ')) + atm2 == BCATM(' ', 'N', '7', ' ')) { return true; + } if (atm1 == BCATM(' ', 'O', 'P', '1') && - atm2 == BCATM(' ', 'P', ' ', ' ')) + atm2 == BCATM(' ', 'P', ' ', ' ')) { return true; + } break; case BCNAM(' ', ' ', 'C'): case BCNAM(' ', 'D', 'C'): if (atm1 == BCATM(' ', 'C', '2', ' ') && - atm2 == BCATM(' ', 'O', '2', ' ')) + atm2 == BCATM(' ', 'O', '2', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', '4', ' ') && - atm2 == BCATM(' ', 'N', '3', ' ')) + atm2 == BCATM(' ', 'N', '3', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', '5', ' ') && - atm2 == BCATM(' ', 'C', '6', ' ')) + atm2 == BCATM(' ', 'C', '6', ' ')) { return true; + } if (atm1 == BCATM(' ', 'O', 'P', '1') && - atm2 == BCATM(' ', 'P', ' ', ' ')) + atm2 == BCATM(' ', 'P', ' ', ' ')) { return true; + } break; case BCNAM(' ', ' ', 'T'): case BCNAM(' ', 'D', 'T'): case BCNAM(' ', ' ', 'U'): case BCNAM(' ', 'D', 'U'): if (atm1 == BCATM(' ', 'C', '2', ' ') && - atm2 == BCATM(' ', 'O', '2', ' ')) + atm2 == BCATM(' ', 'O', '2', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', '4', ' ') && - atm2 == BCATM(' ', 'O', '4', ' ')) + atm2 == BCATM(' ', 'O', '4', ' ')) { return true; + } if (atm1 == BCATM(' ', 'C', '5', ' ') && - atm2 == BCATM(' ', 'C', '6', ' ')) + atm2 == BCATM(' ', 'C', '6', ' ')) { return true; + } if (atm1 == BCATM(' ', 'O', 'P', '1') && - atm2 == BCATM(' ', 'P', ' ', ' ')) + atm2 == BCATM(' ', 'P', ' ', ' ')) { return true; + } break; } return false; } static bool StandardPDBDoubleBond(RWMol *mol, Atom *beg, Atom *end) { - AtomPDBResidueInfo *bInfo = (AtomPDBResidueInfo *)beg->getMonomerInfo(); - if (!bInfo || bInfo->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) + auto *bInfo = (AtomPDBResidueInfo *)beg->getMonomerInfo(); + if (!bInfo || bInfo->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) { return false; - AtomPDBResidueInfo *eInfo = (AtomPDBResidueInfo *)end->getMonomerInfo(); - if (!eInfo || eInfo->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) + } + auto *eInfo = (AtomPDBResidueInfo *)end->getMonomerInfo(); + if (!eInfo || eInfo->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) { return false; - if (!SamePDBResidue(bInfo, eInfo)) return false; - if (bInfo->getIsHeteroAtom() || eInfo->getIsHeteroAtom()) return false; + } + if (!SamePDBResidue(bInfo, eInfo)) { + return false; + } + if (bInfo->getIsHeteroAtom() || eInfo->getIsHeteroAtom()) { + return false; + } const char *ptr = bInfo->getResidueName().c_str(); unsigned int rescode = BCNAM(ptr[0], ptr[1], ptr[2]); @@ -434,15 +491,22 @@ static bool StandardPDBDoubleBond(RWMol *mol, Atom *beg, Atom *end) { ptr = eInfo->getName().c_str(); unsigned int atm2 = BCATM(ptr[0], ptr[1], ptr[2], ptr[3]); - if (!StandardPDBDoubleBond(rescode, atm1, atm2)) return false; + if (!StandardPDBDoubleBond(rescode, atm1, atm2)) { + return false; + } // Check that neither end already has a double bond ROMol::OBOND_ITER_PAIR bp; - for (bp = mol->getAtomBonds(beg); bp.first != bp.second; ++bp.first) - if ((*mol)[*bp.first]->getBondType() == Bond::DOUBLE) return false; - for (bp = mol->getAtomBonds(end); bp.first != bp.second; ++bp.first) - if ((*mol)[*bp.first]->getBondType() == Bond::DOUBLE) return false; - + for (bp = mol->getAtomBonds(beg); bp.first != bp.second; ++bp.first) { + if ((*mol)[*bp.first]->getBondType() == Bond::DOUBLE) { + return false; + } + } + for (bp = mol->getAtomBonds(end); bp.first != bp.second; ++bp.first) { + if ((*mol)[*bp.first]->getBondType() == Bond::DOUBLE) { + return false; + } + } return true; } @@ -453,7 +517,9 @@ void StandardPDBResidueBondOrders(RWMol *mol) { if (bond->getBondType() == Bond::SINGLE) { Atom *beg = bond->getBeginAtom(); Atom *end = bond->getEndAtom(); - if (StandardPDBDoubleBond(mol, beg, end)) bond->setBondType(Bond::DOUBLE); + if (StandardPDBDoubleBond(mol, beg, end)) { + bond->setBondType(Bond::DOUBLE); + } } } } diff --git a/Code/GraphMol/FileParsers/SDMolSupplier.cpp b/Code/GraphMol/FileParsers/SDMolSupplier.cpp index 9c2f299cb..a37b0d8ca 100644 --- a/Code/GraphMol/FileParsers/SDMolSupplier.cpp +++ b/Code/GraphMol/FileParsers/SDMolSupplier.cpp @@ -84,7 +84,9 @@ void SDMolSupplier::init() { void SDMolSupplier::setDataCommon(const std::string &text, bool sanitize, bool removeHs) { - if (dp_inStream && df_owner) delete dp_inStream; + if (dp_inStream && df_owner) { + delete dp_inStream; + } init(); std::istream *tmpStream = nullptr; tmpStream = static_cast( diff --git a/Code/GraphMol/FileParsers/SDWriter.cpp b/Code/GraphMol/FileParsers/SDWriter.cpp index ce351580e..e8f601697 100644 --- a/Code/GraphMol/FileParsers/SDWriter.cpp +++ b/Code/GraphMol/FileParsers/SDWriter.cpp @@ -55,7 +55,9 @@ SDWriter::SDWriter(std::ostream *outStream, bool takeOwnership) { SDWriter::~SDWriter() { // close the writer if it's still open: - if (dp_ostream != nullptr) close(); + if (dp_ostream != nullptr) { + close(); + } } void SDWriter::setProps(const STR_VECT &propNames) { @@ -84,7 +86,9 @@ void _writePropToStream(std::ostream *dp_ostream, const ROMol &mol, // write the property header line (*dp_ostream) << "> <" << name << "> "; - if (d_molid >= 0) (*dp_ostream) << "(" << d_molid + 1 << ") "; + if (d_molid >= 0) { + (*dp_ostream) << "(" << d_molid + 1 << ") "; + } (*dp_ostream) << "\n"; (*dp_ostream) << pval << "\n"; diff --git a/Code/GraphMol/FileParsers/SVGParser.cpp b/Code/GraphMol/FileParsers/SVGParser.cpp index 56bcc6893..ea99b056e 100644 --- a/Code/GraphMol/FileParsers/SVGParser.cpp +++ b/Code/GraphMol/FileParsers/SVGParser.cpp @@ -44,7 +44,9 @@ void ptreeToMol(RWMol *mol, const pt::ptree &molE) { atE.second.get(".y", 0.0), atE.second.get(".z", 0.0)); pts.push_back(pt); - if (atE.second.get(".z", "0") != "0") is3D = true; + if (atE.second.get(".z", "0") != "0") { + is3D = true; + } } } for (const auto &atE : molE) { @@ -63,7 +65,7 @@ void ptreeToMol(RWMol *mol, const pt::ptree &molE) { mol->addBond(bond, takeOwnership); } } - Conformer *conf = new Conformer(mol->getNumAtoms()); + auto *conf = new Conformer(mol->getNumAtoms()); for (unsigned int i = 0; i < mol->getNumAtoms(); ++i) { conf->setAtomPos(i, pts[i]); } diff --git a/Code/GraphMol/FileParsers/SequenceParsers.cpp b/Code/GraphMol/FileParsers/SequenceParsers.cpp index d5911437f..efd5a6796 100644 --- a/Code/GraphMol/FileParsers/SequenceParsers.cpp +++ b/Code/GraphMol/FileParsers/SequenceParsers.cpp @@ -36,10 +36,11 @@ static Atom *CreateAAAtom(RWMol *mol, const char *name, atom = new Atom(16); } else if (name[0] == 'S' && name[1] == 'E') { atom = new Atom(34); - } else + } else { atom = new Atom(0); + } mol->addAtom(atom, true, true); - AtomPDBResidueInfo *copy = (AtomPDBResidueInfo *)info.copy(); + auto *copy = (AtomPDBResidueInfo *)info.copy(); copy->setName(name); atom->setMonomerInfo(copy); @@ -50,10 +51,11 @@ static Atom *CreateAAAtom(RWMol *mol, const char *name, static void CreateAABond(RWMol *mol, Atom *beg, Atom *end, unsigned int order) { Bond *bond; - if (order == 2) + if (order == 2) { bond = new Bond(Bond::DOUBLE); - else + } else { bond = new Bond(Bond::SINGLE); + } bond->setOwningMol(mol); bond->setBeginAtom(beg); bond->setEndAtom(end); @@ -72,10 +74,11 @@ static void CreateAABackbone(RWMol *mol, Atom *&r1, Atom *&r2, Atom *&cb, CreateAABond(mol, r2, o, 2); CreateAABond(mol, ca, cb, 1); - if (ldstereo > 0) // L-stereo + if (ldstereo > 0) { // L-stereo ca->setChiralTag(Atom::CHI_TETRAHEDRAL_CCW); - else if (ldstereo < 0) // D-stereo + } else if (ldstereo < 0) { // D-stereo ca->setChiralTag(Atom::CHI_TETRAHEDRAL_CW); + } } // aa is a three letter PDB residue code @@ -751,7 +754,9 @@ static RWMol *AASequenceToMol(const char *seq, bool lowerD) { CreateAminoAcid(mol, lowerD ? "DTY" : "TYR", r1, r2, r3, info); break; } - if (prev && r1) CreateAABond(mol, prev, r1, 1); + if (prev && r1) { + CreateAABond(mol, prev, r1, 1); + } prev = r2; seq++; } @@ -1000,8 +1005,9 @@ static RWMol *NASequenceToMol(const char *seq, bool Dna, case '.': if (prev) { - if (PCap3) + if (PCap3) { CreatePCap3(mol, prev, info); + } if (chain[0] < 'Z') { chain[0]++; info.setChainId(chain); @@ -1037,18 +1043,23 @@ static RWMol *NASequenceToMol(const char *seq, bool Dna, CreateNucleicAcid(mol, Dna ? " DU" : " U", r1, r2, info, PCap5); break; } - if (prev && r1) CreateAABond(mol, prev, r1, 1); + if (prev && r1) { + CreateAABond(mol, prev, r1, 1); + } prev = r2; seq++; } - if (prev && PCap3) + if (prev && PCap3) { CreatePCap3(mol, prev, info); + } return mol; } RWMol *SequenceToMol(const char *seq, bool sanitize, int flavor) { - if (!seq) return (RWMol *)nullptr; + if (!seq) { + return (RWMol *)nullptr; + } RWMol *mol; switch (flavor) { @@ -1071,8 +1082,9 @@ RWMol *SequenceToMol(const char *seq, bool sanitize, int flavor) { default: return (RWMol *)nullptr; } - if (sanitize && mol) + if (sanitize && mol) { MolOps::sanitizeMol(*mol); + } return mol; } @@ -1090,15 +1102,21 @@ RWMol *SequenceToMol(const std::string &seq, bool sanitize, bool lowerD) { } RWMol *FASTAToMol(const char *seq, bool sanitize, int flavor) { - if (!seq) return (RWMol *)nullptr; + if (!seq) { + return (RWMol *)nullptr; + } std::string title; if (seq[0] == '>') { seq++; - while (*seq && *seq != '\n' && *seq != '\r') title += *seq++; + while (*seq && *seq != '\n' && *seq != '\r') { + title += *seq++; + } } RWMol *mol = SequenceToMol(seq, sanitize, flavor); - if (!title.empty()) mol->setProp(common_properties::_Name, title); + if (!title.empty()) { + mol->setProp(common_properties::_Name, title); + } return mol; } @@ -1171,146 +1189,246 @@ static const char *GetHELMOneLetterCode(char ch) { } static bool IsHELMMonomerIDChar(char ch) { - if (ch >= 'A' && ch <= 'Z') return true; - if (ch >= 'a' && ch <= 'z') return true; - if (ch >= '0' && ch <= '9') return true; + if (ch >= 'A' && ch <= 'Z') { + return true; + } + if (ch >= 'a' && ch <= 'z') { + return true; + } + if (ch >= '0' && ch <= '9') { + return true; + } return false; } static const char *LookupHELMPeptideMonomer(const char *ptr) { switch (ptr[0]) { case 'A': - if (ptr[1] == '\0') return "ALA"; - if (ptr[1] == 'b' && ptr[2] == 'u' && ptr[3] == '\0') return "ABA"; + if (ptr[1] == '\0') { + return "ALA"; + } + if (ptr[1] == 'b' && ptr[2] == 'u' && ptr[3] == '\0') { + return "ABA"; + } break; case 'C': - if (ptr[1] == '\0') return "CYS"; + if (ptr[1] == '\0') { + return "CYS"; + } break; case 'D': - if (ptr[1] == '\0') return "ASP"; + if (ptr[1] == '\0') { + return "ASP"; + } break; case 'E': - if (ptr[1] == '\0') return "GLU"; + if (ptr[1] == '\0') { + return "GLU"; + } break; case 'F': - if (ptr[1] == '\0') return "PHE"; + if (ptr[1] == '\0') { + return "PHE"; + } break; case 'G': - if (ptr[1] == '\0') return "GLY"; - if (ptr[1] == 'l' && ptr[2] == 'p' && ptr[3] == '\0') return "PCA"; + if (ptr[1] == '\0') { + return "GLY"; + } + if (ptr[1] == 'l' && ptr[2] == 'p' && ptr[3] == '\0') { + return "PCA"; + } break; case 'H': - if (ptr[1] == '\0') return "HIS"; + if (ptr[1] == '\0') { + return "HIS"; + } break; case 'I': - if (ptr[1] == '\0') return "ILE"; + if (ptr[1] == '\0') { + return "ILE"; + } break; case 'K': - if (ptr[1] == '\0') return "LYS"; + if (ptr[1] == '\0') { + return "LYS"; + } break; case 'L': - if (ptr[1] == '\0') return "LEU"; + if (ptr[1] == '\0') { + return "LEU"; + } break; case 'M': - if (ptr[1] == '\0') return "MET"; + if (ptr[1] == '\0') { + return "MET"; + } break; case 'N': - if (ptr[1] == '\0') return "ASN"; - if (ptr[1] == 'a' && ptr[2] == 'l' && ptr[3] == '\0') return "NAL"; - if (ptr[1] == 'l' && ptr[2] == 'e' && ptr[3] == '\0') return "NLE"; - if (ptr[1] == 'v' && ptr[2] == 'a' && ptr[3] == '\0') return "NVA"; + if (ptr[1] == '\0') { + return "ASN"; + } + if (ptr[1] == 'a' && ptr[2] == 'l' && ptr[3] == '\0') { + return "NAL"; + } + if (ptr[1] == 'l' && ptr[2] == 'e' && ptr[3] == '\0') { + return "NLE"; + } + if (ptr[1] == 'v' && ptr[2] == 'a' && ptr[3] == '\0') { + return "NVA"; + } break; case 'O': - if (ptr[1] == 'r' && ptr[2] == 'n' && ptr[3] == '\0') return "ORN"; + if (ptr[1] == 'r' && ptr[2] == 'n' && ptr[3] == '\0') { + return "ORN"; + } break; case 'P': - if (ptr[1] == '\0') return "PRO"; + if (ptr[1] == '\0') { + return "PRO"; + } break; case 'Q': - if (ptr[1] == '\0') return "GLN"; + if (ptr[1] == '\0') { + return "GLN"; + } break; case 'R': - if (ptr[1] == '\0') return "ARG"; + if (ptr[1] == '\0') { + return "ARG"; + } break; case 'S': - if (ptr[1] == '\0') return "SER"; - if (ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == '\0') return "SAR"; + if (ptr[1] == '\0') { + return "SER"; + } + if (ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == '\0') { + return "SAR"; + } break; case 'T': - if (ptr[1] == '\0') return "THR"; + if (ptr[1] == '\0') { + return "THR"; + } break; case 'V': - if (ptr[1] == '\0') return "VAL"; + if (ptr[1] == '\0') { + return "VAL"; + } break; case 'W': - if (ptr[1] == '\0') return "TRP"; + if (ptr[1] == '\0') { + return "TRP"; + } break; case 'Y': - if (ptr[1] == '\0') return "TYR"; + if (ptr[1] == '\0') { + return "TYR"; + } break; case 'd': switch (ptr[1]) { case 'A': - if (ptr[2] == '\0') return "DAL"; + if (ptr[2] == '\0') { + return "DAL"; + } break; case 'C': - if (ptr[2] == '\0') return "DCY"; + if (ptr[2] == '\0') { + return "DCY"; + } break; case 'D': - if (ptr[2] == '\0') return "DAS"; + if (ptr[2] == '\0') { + return "DAS"; + } break; case 'E': - if (ptr[2] == '\0') return "DGL"; + if (ptr[2] == '\0') { + return "DGL"; + } break; case 'F': - if (ptr[2] == '\0') return "DPN"; + if (ptr[2] == '\0') { + return "DPN"; + } break; case 'H': - if (ptr[2] == '\0') return "DHI"; + if (ptr[2] == '\0') { + return "DHI"; + } break; case 'I': - if (ptr[2] == '\0') return "DIL"; + if (ptr[2] == '\0') { + return "DIL"; + } break; case 'K': - if (ptr[2] == '\0') return "DLY"; + if (ptr[2] == '\0') { + return "DLY"; + } break; case 'L': - if (ptr[2] == '\0') return "DLE"; + if (ptr[2] == '\0') { + return "DLE"; + } break; case 'M': - if (ptr[2] == '\0') return "MED"; + if (ptr[2] == '\0') { + return "MED"; + } break; case 'N': - if (ptr[2] == '\0') return "DSG"; + if (ptr[2] == '\0') { + return "DSG"; + } break; case 'P': - if (ptr[2] == '\0') return "DPR"; + if (ptr[2] == '\0') { + return "DPR"; + } break; case 'Q': - if (ptr[2] == '\0') return "DGN"; + if (ptr[2] == '\0') { + return "DGN"; + } break; case 'R': - if (ptr[2] == '\0') return "DAR"; + if (ptr[2] == '\0') { + return "DAR"; + } break; case 'S': - if (ptr[2] == '\0') return "DSN"; + if (ptr[2] == '\0') { + return "DSN"; + } break; case 'T': - if (ptr[2] == '\0') return "DTH"; + if (ptr[2] == '\0') { + return "DTH"; + } break; case 'V': - if (ptr[2] == '\0') return "DVA"; + if (ptr[2] == '\0') { + return "DVA"; + } break; case 'W': - if (ptr[2] == '\0') return "DTR"; + if (ptr[2] == '\0') { + return "DTR"; + } break; case 'Y': - if (ptr[2] == '\0') return "DTY"; + if (ptr[2] == '\0') { + return "DTY"; + } break; } break; case 's': - if (ptr[1] == 'e' && ptr[2] == 'C' && ptr[3] == '\0') return "MSE"; + if (ptr[1] == 'e' && ptr[2] == 'C' && ptr[3] == '\0') { + return "MSE"; + } break; } return (const char *)nullptr; @@ -1323,7 +1441,9 @@ static const char *ParseHELMPeptide(RWMol *mol, const char *ptr, HELMMonomer curr; vseq.clear(); - if (ptr[0] == '}') return ptr; + if (ptr[0] == '}') { + return ptr; + } AtomPDBResidueInfo info; info.setSerialNumber(1); @@ -1333,7 +1453,9 @@ static const char *ParseHELMPeptide(RWMol *mol, const char *ptr, info.setChainId(chain); if (ptr[0] == '[' && ptr[1] == 'a' && ptr[2] == 'c' && ptr[3] == ']') { - if (ptr[4] != '.') return (const char *)nullptr; + if (ptr[4] != '.') { + return (const char *)nullptr; + } info.setResidueNumber(-2); CreateAminoAcid(mol, "ACE", curr.r1, curr.r2, curr.r3, info); vseq.push_back(curr); @@ -1347,12 +1469,19 @@ static const char *ParseHELMPeptide(RWMol *mol, const char *ptr, if (*ptr == '[') { std::string tmp; ptr++; - while (IsHELMMonomerIDChar(*ptr)) tmp += *ptr++; - if (*ptr != ']') return (char *)nullptr; + while (IsHELMMonomerIDChar(*ptr)) { + tmp += *ptr++; + } + if (*ptr != ']') { + return (char *)nullptr; + } name = LookupHELMPeptideMonomer(tmp.c_str()); - } else + } else { name = GetHELMOneLetterCode(*ptr); - if (!name) return (const char *)nullptr; + } + if (!name) { + return (const char *)nullptr; + } ptr++; CreateAminoAcid(mol, name, curr.r1, curr.r2, curr.r3, info); @@ -1366,7 +1495,9 @@ static const char *ParseHELMPeptide(RWMol *mol, const char *ptr, if (*ptr == '.') { if (ptr[1] == '[' && ptr[2] == 'a' && ptr[3] == 'm' && ptr[4] == ']' && ptr[5] == '}') { - if (!vseq[len - 1].r2) return (const char *)nullptr; + if (!vseq[len - 1].r2) { + return (const char *)nullptr; + } int resno = info.getResidueNumber(); info.setResidueNumber(resno + 1); info.setIsHeteroAtom(true); @@ -1380,20 +1511,24 @@ static const char *ParseHELMPeptide(RWMol *mol, const char *ptr, } ptr++; } else if (*ptr == '}') { - if (!vseq[len - 1].r2) return (const char *)nullptr; + if (!vseq[len - 1].r2) { + return (const char *)nullptr; + } Atom *oxt = CreateAAAtom(mol, " OXT", info); CreateAABond(mol, vseq[len - 1].r2, oxt, 1); vseq[len - 1].oxt = oxt; return ptr; - } else + } else { return (const char *)nullptr; + } } } static const char *ParseHELMNucleic(RWMol *mol, const char *ptr, const char *chain) { - if (ptr[0] == '}') + if (ptr[0] == '}') { return ptr; + } bool PCap5 = false; Atom *prev = nullptr; @@ -1410,8 +1545,9 @@ static const char *ParseHELMNucleic(RWMol *mol, const char *ptr, if (*ptr=='P') { PCap5 = true; ptr++; - if (*ptr=='.') + if (*ptr == '.') { ptr++; + } } for (;;) { @@ -1472,26 +1608,34 @@ static const char *ParseHELMNucleic(RWMol *mol, const char *ptr, } } } - if (!name) return (const char *)nullptr; + if (!name) { + return (const char *)nullptr; + } CreateNucleicAcid(mol,name,r1,r2,info,PCap5); - if (prev && r1) + if (prev && r1) { CreateAABond(mol, prev, r1, 1); + } prev = r2; - if (*ptr == '}') + if (*ptr == '}') { return ptr; - if (*ptr == '.') + } + if (*ptr == '.') { ptr++; - if (*ptr != 'P') return (const char *)nullptr; + } + if (*ptr != 'P') { + return (const char *)nullptr; + } ptr++; if (*ptr == '}') { CreatePCap3(mol,prev,info); return ptr; } PCap5 = true; - if (*ptr == '.') + if (*ptr == '.') { ptr++; + } } } @@ -1509,33 +1653,54 @@ static bool ParseHELM(RWMol *mol, const char *ptr) { ptr[4] == 'I' && ptr[5] == 'D' && ptr[6] == 'E' && ptr[7] >= '1' && ptr[7] <= '9') { ptr += 8; - while (*ptr >= '0' && *ptr <= '9') ptr++; - if (*ptr != '{') return false; + while (*ptr >= '0' && *ptr <= '9') { + ptr++; + } + if (*ptr != '{') { + return false; + } std::string id(orig, ptr - orig); chain[0] = 'A' + (orig[7] - '1'); ptr = ParseHELMPeptide(mol, ptr + 1, chain, seqs[id]); - if (!ptr || *ptr != '}') return false; + if (!ptr || *ptr != '}') { + return false; + } ptr++; } else if (ptr[0]=='R' && ptr[1]=='N' && ptr[2]=='A' && ptr[3]>='1' && ptr[3]<='9') { ptr += 4; - while (*ptr >= '0' && *ptr <= '9') ptr++; - if (*ptr != '{') return false; + while (*ptr >= '0' && *ptr <= '9') { + ptr++; + } + if (*ptr != '{') { + return false; + } chain[0] = 'A' + (orig[3] - '1'); ptr = ParseHELMNucleic(mol, ptr + 1, chain); - if (!ptr || *ptr != '}') return false; + if (!ptr || *ptr != '}') { + return false; + } ptr++; - } else + } else { return false; + } - if (*ptr == '$') break; - if (*ptr == '\0') return true; - if (*ptr != '|') return false; + if (*ptr == '$') { + break; + } + if (*ptr == '\0') { + return true; + } + if (*ptr != '|') { + return false; + } ptr++; } ptr++; - if (ptr[0] == '$' && ptr[1] == '$' && ptr[2] == '$') return true; + if (ptr[0] == '$' && ptr[1] == '$' && ptr[2] == '$') { + return true; + } for (;;) { orig = ptr; @@ -1543,10 +1708,15 @@ static bool ParseHELM(RWMol *mol, const char *ptr) { ptr[4] == 'I' && ptr[5] == 'D' && ptr[6] == 'E' && ptr[7] >= '1' && ptr[7] <= '9') { ptr += 8; - } else + } else { return false; - while (*ptr >= '0' && *ptr <= '9') ptr++; - if (*ptr != ',') return false; + } + while (*ptr >= '0' && *ptr <= '9') { + ptr++; + } + if (*ptr != ',') { + return false; + } std::string id1(orig, ptr - orig); ptr++; @@ -1556,10 +1726,15 @@ static bool ParseHELM(RWMol *mol, const char *ptr) { ptr[4] == 'I' && ptr[5] == 'D' && ptr[6] == 'E' && ptr[7] >= '1' && ptr[7] <= '9') { ptr += 8; - } else + } else { return false; - while (*ptr >= '0' && *ptr <= '9') ptr++; - if (*ptr != ',') return false; + } + while (*ptr >= '0' && *ptr <= '9') { + ptr++; + } + if (*ptr != ',') { + return false; + } std::string id2(orig, ptr - orig); ptr++; @@ -1571,38 +1746,55 @@ static bool ParseHELM(RWMol *mol, const char *ptr) { if (*ptr >= '1' && *ptr <= '9') { res1 = (*ptr++) - '0'; - while (*ptr >= '0' && *ptr <= '9') res1 = 10 * res1 + ((*ptr++) - '0'); - } else + while (*ptr >= '0' && *ptr <= '9') { + res1 = 10 * res1 + ((*ptr++) - '0'); + } + } else { return false; + } if (ptr[0] == ':' && ptr[1] == 'R' && ptr[2] >= '1' && ptr[2] <= '9') { res1r = ptr[2] - '0'; ptr += 3; - } else + } else { return false; - if (*ptr != '-') return false; + } + if (*ptr != '-') { + return false; + } ptr++; if (*ptr >= '1' && *ptr <= '9') { res2 = (*ptr++) - '0'; - while (*ptr >= '0' && *ptr <= '9') res2 = 10 * res2 + ((*ptr++) - '0'); - } else + while (*ptr >= '0' && *ptr <= '9') { + res2 = 10 * res2 + ((*ptr++) - '0'); + } + } else { return false; + } if (ptr[0] == ':' && ptr[1] == 'R' && ptr[2] >= '1' && ptr[2] <= '9') { res2r = ptr[2] - '0'; ptr += 3; - } else + } else { return false; + } // printf("%s:%u:R%u - %s:%u:R%u\n",id1.c_str(),res1,res1r, // id2.c_str(),res2,res2r); - if (res1 < 1 || res2 < 1) return false; - if (seqs.find(id1) == seqs.end() || seqs.find(id2) == seqs.end()) + if (res1 < 1 || res2 < 1) { return false; + } + if (seqs.find(id1) == seqs.end() || seqs.find(id2) == seqs.end()) { + return false; + } std::vector *vseq1 = &seqs[id1]; - if (res1 > (unsigned int)vseq1->size()) return false; + if (res1 > (unsigned int)vseq1->size()) { + return false; + } std::vector *vseq2 = &seqs[id2]; - if (res2 > (unsigned int)vseq2->size()) return false; + if (res2 > (unsigned int)vseq2->size()) { + return false; + } if (res1r == 3 && res2r == 3) { Atom *src = (*vseq1)[res1 - 1].r3; @@ -1611,8 +1803,9 @@ static bool ParseHELM(RWMol *mol, const char *ptr) { CreateAABond(mol, src, dst, 1); (*vseq1)[res1 - 1].r3 = (Atom *)nullptr; (*vseq2)[res2 - 1].r3 = (Atom *)nullptr; - } else + } else { return false; + } } else if (res1r == 1 && res2r == 2) { Atom *src = (*vseq1)[res1 - 1].r1; Atom *dst = (*vseq2)[res2 - 1].r2; @@ -1622,8 +1815,9 @@ static bool ParseHELM(RWMol *mol, const char *ptr) { CreateAABond(mol, src, dst, 1); (*vseq1)[res1 - 1].r1 = (Atom *)nullptr; (*vseq2)[res2 - 1].r2 = (Atom *)nullptr; - } else + } else { return false; + } } else if (res1r == 2 && res2r == 1) { Atom *src = (*vseq2)[res2 - 1].r1; Atom *dst = (*vseq1)[res1 - 1].r2; @@ -1633,13 +1827,19 @@ static bool ParseHELM(RWMol *mol, const char *ptr) { CreateAABond(mol, dst, src, 1); (*vseq1)[res1 - 1].r2 = (Atom *)nullptr; (*vseq2)[res2 - 1].r1 = (Atom *)nullptr; - } else + } else { return false; - } else + } + } else { return false; + } - if (*ptr == '$') break; - if (*ptr != '|') return false; + if (*ptr == '$') { + break; + } + if (*ptr != '|') { + return false; + } ptr++; } ptr++; @@ -1650,11 +1850,14 @@ RWMol *HELMToMol(const char *helm, bool sanitize) { auto *mol = new RWMol(); const char *ptr = helm; - if (ptr[0] == '$' && ptr[1] == '$' && ptr[2] == '$' && ptr[3] == '$') + if (ptr[0] == '$' && ptr[1] == '$' && ptr[2] == '$' && ptr[3] == '$') { return mol; + } if (ParseHELM(mol, ptr)) { - if (sanitize) MolOps::sanitizeMol(*mol); + if (sanitize) { + MolOps::sanitizeMol(*mol); + } return mol; } delete mol; diff --git a/Code/GraphMol/FileParsers/SequenceWriters.cpp b/Code/GraphMol/FileParsers/SequenceWriters.cpp index 47ed886dd..f3b38002b 100644 --- a/Code/GraphMol/FileParsers/SequenceWriters.cpp +++ b/Code/GraphMol/FileParsers/SequenceWriters.cpp @@ -22,67 +22,145 @@ static char getOneLetterAACode(const AtomPDBResidueInfo *info) { const char *ptr = info->getResidueName().c_str(); switch (ptr[0]) { case 'A': - if (!strcmp(ptr, "ALA")) return 'A'; - if (!strcmp(ptr, "ARG")) return 'R'; - if (!strcmp(ptr, "ASN")) return 'N'; - if (!strcmp(ptr, "ASP")) return 'D'; + if (!strcmp(ptr, "ALA")) { + return 'A'; + } + if (!strcmp(ptr, "ARG")) { + return 'R'; + } + if (!strcmp(ptr, "ASN")) { + return 'N'; + } + if (!strcmp(ptr, "ASP")) { + return 'D'; + } break; case 'C': - if (!strcmp(ptr, "CYS")) return 'C'; + if (!strcmp(ptr, "CYS")) { + return 'C'; + } break; case 'D': - if (!strcmp(ptr, "DAL")) return 'a'; - if (!strcmp(ptr, "DAR")) return 'r'; - if (!strcmp(ptr, "DAS")) return 'd'; - if (!strcmp(ptr, "DCY")) return 'c'; - if (!strcmp(ptr, "DGL")) return 'e'; - if (!strcmp(ptr, "DGN")) return 'q'; - if (!strcmp(ptr, "DHI")) return 'h'; - if (!strcmp(ptr, "DIL")) return 'i'; - if (!strcmp(ptr, "DLE")) return 'l'; - if (!strcmp(ptr, "DLY")) return 'k'; - if (!strcmp(ptr, "DPN")) return 'f'; - if (!strcmp(ptr, "DPR")) return 'p'; - if (!strcmp(ptr, "DSG")) return 'n'; - if (!strcmp(ptr, "DSN")) return 's'; - if (!strcmp(ptr, "DTH")) return 't'; - if (!strcmp(ptr, "DTR")) return 'w'; - if (!strcmp(ptr, "DTY")) return 'y'; - if (!strcmp(ptr, "DVA")) return 'v'; + if (!strcmp(ptr, "DAL")) { + return 'a'; + } + if (!strcmp(ptr, "DAR")) { + return 'r'; + } + if (!strcmp(ptr, "DAS")) { + return 'd'; + } + if (!strcmp(ptr, "DCY")) { + return 'c'; + } + if (!strcmp(ptr, "DGL")) { + return 'e'; + } + if (!strcmp(ptr, "DGN")) { + return 'q'; + } + if (!strcmp(ptr, "DHI")) { + return 'h'; + } + if (!strcmp(ptr, "DIL")) { + return 'i'; + } + if (!strcmp(ptr, "DLE")) { + return 'l'; + } + if (!strcmp(ptr, "DLY")) { + return 'k'; + } + if (!strcmp(ptr, "DPN")) { + return 'f'; + } + if (!strcmp(ptr, "DPR")) { + return 'p'; + } + if (!strcmp(ptr, "DSG")) { + return 'n'; + } + if (!strcmp(ptr, "DSN")) { + return 's'; + } + if (!strcmp(ptr, "DTH")) { + return 't'; + } + if (!strcmp(ptr, "DTR")) { + return 'w'; + } + if (!strcmp(ptr, "DTY")) { + return 'y'; + } + if (!strcmp(ptr, "DVA")) { + return 'v'; + } break; case 'G': - if (!strcmp(ptr, "GLU")) return 'E'; - if (!strcmp(ptr, "GLN")) return 'Q'; - if (!strcmp(ptr, "GLY")) return 'G'; + if (!strcmp(ptr, "GLU")) { + return 'E'; + } + if (!strcmp(ptr, "GLN")) { + return 'Q'; + } + if (!strcmp(ptr, "GLY")) { + return 'G'; + } break; case 'H': - if (!strcmp(ptr, "HIS")) return 'H'; + if (!strcmp(ptr, "HIS")) { + return 'H'; + } break; case 'I': - if (!strcmp(ptr, "ILE")) return 'I'; + if (!strcmp(ptr, "ILE")) { + return 'I'; + } break; case 'L': - if (!strcmp(ptr, "LEU")) return 'L'; - if (!strcmp(ptr, "LYS")) return 'K'; + if (!strcmp(ptr, "LEU")) { + return 'L'; + } + if (!strcmp(ptr, "LYS")) { + return 'K'; + } break; case 'M': - if (!strcmp(ptr, "MET")) return 'M'; - if (!strcmp(ptr, "MED")) return 'm'; + if (!strcmp(ptr, "MET")) { + return 'M'; + } + if (!strcmp(ptr, "MED")) { + return 'm'; + } break; case 'P': - if (!strcmp(ptr, "PHE")) return 'F'; - if (!strcmp(ptr, "PRO")) return 'P'; + if (!strcmp(ptr, "PHE")) { + return 'F'; + } + if (!strcmp(ptr, "PRO")) { + return 'P'; + } break; case 'S': - if (!strcmp(ptr, "SER")) return 'S'; + if (!strcmp(ptr, "SER")) { + return 'S'; + } break; case 'T': - if (!strcmp(ptr, "THR")) return 'T'; - if (!strcmp(ptr, "TRP")) return 'W'; - if (!strcmp(ptr, "TYR")) return 'Y'; + if (!strcmp(ptr, "THR")) { + return 'T'; + } + if (!strcmp(ptr, "TRP")) { + return 'W'; + } + if (!strcmp(ptr, "TYR")) { + return 'Y'; + } break; case 'V': - if (!strcmp(ptr, "VAL")) return 'V'; + if (!strcmp(ptr, "VAL")) { + return 'V'; + } break; } return 'X'; @@ -112,7 +190,7 @@ std::string MolToSequence(const ROMol &mol) { for (ROMol::ConstAtomIterator atomIt = mol.beginAtoms(); atomIt != mol.endAtoms(); ++atomIt) { const Atom *atom = *atomIt; - AtomPDBResidueInfo *info = (AtomPDBResidueInfo *)(atom->getMonomerInfo()); + auto *info = (AtomPDBResidueInfo *)(atom->getMonomerInfo()); if (info && info->getMonomerType() == AtomMonomerInfo::PDBRESIDUE) { if (info->getName() == " CA ") { if (!chain.empty() && chain != info->getChainId()) { @@ -134,11 +212,15 @@ std::string MolToSequence(const ROMol &mol) { std::string MolToFASTA(const ROMol &mol) { std::string seq = MolToSequence(mol); - if (seq.empty()) return ""; + if (seq.empty()) { + return ""; + } std::string result = ">"; std::string name; - if (mol.getPropIfPresent(common_properties::_Name, name)) result += name; + if (mol.getPropIfPresent(common_properties::_Name, name)) { + result += name; + } result += '\n'; result += seq; result += '\n'; @@ -149,101 +231,193 @@ static const char *getHELMAAMonomer(const AtomPDBResidueInfo *info) { const char *ptr = info->getResidueName().c_str(); switch (ptr[0]) { case 'A': - if (!strcmp(ptr, "ALA")) return "A"; - if (!strcmp(ptr, "ARG")) return "R"; - if (!strcmp(ptr, "ASN")) return "N"; - if (!strcmp(ptr, "ASP")) return "D"; + if (!strcmp(ptr, "ALA")) { + return "A"; + } + if (!strcmp(ptr, "ARG")) { + return "R"; + } + if (!strcmp(ptr, "ASN")) { + return "N"; + } + if (!strcmp(ptr, "ASP")) { + return "D"; + } break; case 'C': - if (!strcmp(ptr, "CYS")) return "C"; + if (!strcmp(ptr, "CYS")) { + return "C"; + } break; case 'D': - if (!strcmp(ptr, "DAL")) return "[dA]"; - if (!strcmp(ptr, "DAR")) return "[dR]"; - if (!strcmp(ptr, "DAS")) return "[dD]"; - if (!strcmp(ptr, "DCY")) return "[dC]"; - if (!strcmp(ptr, "DGL")) return "[dE]"; - if (!strcmp(ptr, "DGN")) return "[dQ]"; - if (!strcmp(ptr, "DHI")) return "[dH]"; - if (!strcmp(ptr, "DLE")) return "[dL]"; - if (!strcmp(ptr, "DLY")) return "[dK]"; - if (!strcmp(ptr, "DPN")) return "[dF]"; - if (!strcmp(ptr, "DPR")) return "[dP]"; - if (!strcmp(ptr, "DSG")) return "[dN]"; - if (!strcmp(ptr, "DSN")) return "[dS]"; - if (!strcmp(ptr, "DTR")) return "[dW]"; - if (!strcmp(ptr, "DTY")) return "[dY]"; - if (!strcmp(ptr, "DVA")) return "[dV]"; + if (!strcmp(ptr, "DAL")) { + return "[dA]"; + } + if (!strcmp(ptr, "DAR")) { + return "[dR]"; + } + if (!strcmp(ptr, "DAS")) { + return "[dD]"; + } + if (!strcmp(ptr, "DCY")) { + return "[dC]"; + } + if (!strcmp(ptr, "DGL")) { + return "[dE]"; + } + if (!strcmp(ptr, "DGN")) { + return "[dQ]"; + } + if (!strcmp(ptr, "DHI")) { + return "[dH]"; + } + if (!strcmp(ptr, "DLE")) { + return "[dL]"; + } + if (!strcmp(ptr, "DLY")) { + return "[dK]"; + } + if (!strcmp(ptr, "DPN")) { + return "[dF]"; + } + if (!strcmp(ptr, "DPR")) { + return "[dP]"; + } + if (!strcmp(ptr, "DSG")) { + return "[dN]"; + } + if (!strcmp(ptr, "DSN")) { + return "[dS]"; + } + if (!strcmp(ptr, "DTR")) { + return "[dW]"; + } + if (!strcmp(ptr, "DTY")) { + return "[dY]"; + } + if (!strcmp(ptr, "DVA")) { + return "[dV]"; + } break; case 'G': - if (!strcmp(ptr, "GLU")) return "E"; - if (!strcmp(ptr, "GLN")) return "Q"; - if (!strcmp(ptr, "GLY")) return "G"; + if (!strcmp(ptr, "GLU")) { + return "E"; + } + if (!strcmp(ptr, "GLN")) { + return "Q"; + } + if (!strcmp(ptr, "GLY")) { + return "G"; + } break; case 'H': - if (!strcmp(ptr, "HIS")) return "H"; + if (!strcmp(ptr, "HIS")) { + return "H"; + } break; case 'I': - if (!strcmp(ptr, "ILE")) return "I"; + if (!strcmp(ptr, "ILE")) { + return "I"; + } break; case 'L': - if (!strcmp(ptr, "LEU")) return "L"; - if (!strcmp(ptr, "LYS")) return "K"; + if (!strcmp(ptr, "LEU")) { + return "L"; + } + if (!strcmp(ptr, "LYS")) { + return "K"; + } break; case 'M': - if (!strcmp(ptr, "MET")) return "M"; - if (!strcmp(ptr, "MED")) return "[dM]"; - if (!strcmp(ptr, "MSE")) return "[seC]"; + if (!strcmp(ptr, "MET")) { + return "M"; + } + if (!strcmp(ptr, "MED")) { + return "[dM]"; + } + if (!strcmp(ptr, "MSE")) { + return "[seC]"; + } break; case 'N': - if (!strcmp(ptr, "NLE")) return "[Nle]"; - if (!strcmp(ptr, "NVA")) return "[Nva]"; + if (!strcmp(ptr, "NLE")) { + return "[Nle]"; + } + if (!strcmp(ptr, "NVA")) { + return "[Nva]"; + } break; case 'O': - if (!strcmp(ptr, "ORN")) return "[Orn]"; + if (!strcmp(ptr, "ORN")) { + return "[Orn]"; + } break; case 'P': - if (!strcmp(ptr, "PHE")) return "F"; - if (!strcmp(ptr, "PRO")) return "P"; + if (!strcmp(ptr, "PHE")) { + return "F"; + } + if (!strcmp(ptr, "PRO")) { + return "P"; + } break; case 'S': - if (!strcmp(ptr, "SER")) return "S"; + if (!strcmp(ptr, "SER")) { + return "S"; + } break; case 'T': - if (!strcmp(ptr, "THR")) return "T"; - if (!strcmp(ptr, "TRP")) return "W"; - if (!strcmp(ptr, "TYR")) return "Y"; + if (!strcmp(ptr, "THR")) { + return "T"; + } + if (!strcmp(ptr, "TRP")) { + return "W"; + } + if (!strcmp(ptr, "TYR")) { + return "Y"; + } break; case 'V': - if (!strcmp(ptr, "VAL")) return "V"; + if (!strcmp(ptr, "VAL")) { + return "V"; + } break; } return (const char *)nullptr; } static bool IsEupeptideBond(AtomPDBResidueInfo *src, AtomPDBResidueInfo *dst) { - if (src->getChainId() != dst->getChainId()) return false; + if (src->getChainId() != dst->getChainId()) { + return false; + } int sresno = src->getResidueNumber(); int dresno = dst->getResidueNumber(); // Peptides if (src->getName() == " C " && dst->getName() == " N ") { - if (sresno != dresno) return dresno > sresno; + if (sresno != dresno) { + return dresno > sresno; + } return dst->getInsertionCode() > src->getInsertionCode(); } if (src->getName() == " N " && dst->getName() == " C ") { - if (sresno != dresno) return dresno < sresno; + if (sresno != dresno) { + return dresno < sresno; + } return dst->getInsertionCode() < src->getInsertionCode(); } // Nucleic acids if (src->getName() == " O3'" && dst->getName() == " P ") { - if (sresno != dresno) return dresno > sresno; + if (sresno != dresno) { + return dresno > sresno; + } return dst->getInsertionCode() > src->getInsertionCode(); } if (src->getName() == " P " && dst->getName() == " O3'") { - if (sresno != dresno) return dresno > sresno; + if (sresno != dresno) { + return dresno > sresno; + } return dst->getInsertionCode() > src->getInsertionCode(); } return false; @@ -253,12 +427,17 @@ static bool IsSupportedHELMBond(AtomPDBResidueInfo *src, AtomPDBResidueInfo *dst) { if (src->getName() == " SG " && dst->getName() == " SG ") { if ((src->getResidueName() == "CYS" || src->getResidueName() == "DCY") && - (dst->getResidueName() == "CYS" || dst->getResidueName() == "DCY")) + (dst->getResidueName() == "CYS" || dst->getResidueName() == "DCY")) { return true; + } } - if (src->getName() == " N " && dst->getName() == " C ") return true; - if (src->getName() == " C " && dst->getName() == " N ") return true; + if (src->getName() == " N " && dst->getName() == " C ") { + return true; + } + if (src->getName() == " C " && dst->getName() == " N ") { + return true; + } #if 0 printf("%s%d%s.%s - %s%d%s.%s\n", src->getResidueName().c_str(),src->getResidueNumber(), @@ -276,18 +455,19 @@ static bool FindHELMAtom(std::vector *seq, char ch; const char *ptr = info->getName().c_str(); - if (ptr[0] == ' ' && ptr[1] == 'S' && ptr[2] == 'G' && ptr[3] == ' ') + if (ptr[0] == ' ' && ptr[1] == 'S' && ptr[2] == 'G' && ptr[3] == ' ') { ch = '3'; - else if (ptr[0] == ' ' && ptr[1] == 'N' && ptr[2] == ' ' && ptr[3] == ' ') + } else if (ptr[0] == ' ' && ptr[1] == 'N' && ptr[2] == ' ' && ptr[3] == ' ') { ch = '1'; - else if (ptr[0] == ' ' && ptr[1] == 'C' && ptr[2] == ' ' && ptr[3] == ' ') + } else if (ptr[0] == ' ' && ptr[1] == 'C' && ptr[2] == ' ' && ptr[3] == ' ') { ch = '2'; - else + } else { return false; + } int resno = info->getResidueNumber(); for (unsigned int i = 1; i < 10; i++) { - unsigned int len = (unsigned int)seq[i].size(); + auto len = (unsigned int)seq[i].size(); for (unsigned int j = 0; j < len; j++) { AtomPDBResidueInfo *targ = seq[i][j]; if (targ->getResidueNumber() == resno && @@ -309,9 +489,13 @@ static std::string NameHELMBond(std::vector *seq, AtomPDBResidueInfo *src, AtomPDBResidueInfo *dst) { std::string id1, pos1; - if (!FindHELMAtom(seq, src, id1, pos1)) return ""; + if (!FindHELMAtom(seq, src, id1, pos1)) { + return ""; + } std::string id2, pos2; - if (!FindHELMAtom(seq, dst, id2, pos2)) return ""; + if (!FindHELMAtom(seq, dst, id2, pos2)) { + return ""; + } std::string result = id1; result += ','; @@ -369,14 +553,17 @@ std::string MolToHELM(const ROMol &mol) { for (ROMol::ConstAtomIterator atomIt = mol.beginAtoms(); atomIt != mol.endAtoms(); ++atomIt) { const Atom *atom = *atomIt; - AtomPDBResidueInfo *info = (AtomPDBResidueInfo *)(atom->getMonomerInfo()); + auto *info = (AtomPDBResidueInfo *)(atom->getMonomerInfo()); // We can only write HELM if all atoms have PDB residue information - if (!info || info->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) + if (!info || info->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) { return ""; + } if (info->getName() == " CA ") { const char *mono = getHELMAAMonomer(info); - if (!mono) return ""; + if (!mono) { + return ""; + } if (first) { chain = info->getChainId(); result = "PEPTIDE1{"; @@ -384,19 +571,24 @@ std::string MolToHELM(const ROMol &mol) { first = false; } else if (!peptide || info->getChainId() != chain) { // Nine chains should be enough? - if (id == 9) return ""; + if (id == 9) { + return ""; + } id++; chain = info->getChainId(); result += "}|PEPTIDE"; result += (char)(id + '0'); result += "{"; peptide = true; - } else + } else { result += "."; + } result += mono; seq[id].push_back(info); } else if (info->getResidueName() == "NH2" && info->getName() == " N ") { - if (first || !peptide) return ""; + if (first || !peptide) { + return ""; + } result += ".[am]"; } else if (info->getResidueName() == "ACE" && info->getName() == " C ") { if (first) { @@ -406,19 +598,24 @@ std::string MolToHELM(const ROMol &mol) { first = false; } else if (info->getChainId() != chain) { // Nine chains should be enough? - if (id == 9) return ""; + if (id == 9) { + return ""; + } id++; chain = info->getChainId(); result += "}|PEPTIDE"; result += (char)(id + '0'); result += "{[ac]"; peptide = true; - } else + } else { return ""; + } seq[id].push_back(info); } else if (info->getName() == " C1'") { const char *mono = getHELMNAMonomer(info); - if (!mono) return ""; + if (!mono) { + return ""; + } if (first) { chain = info->getChainId(); result = "RNA1{"; @@ -427,7 +624,9 @@ std::string MolToHELM(const ROMol &mol) { Pstate = 2; } else if (peptide || info->getChainId() != chain) { // Nine chains should be enough? - if (id == 9) return ""; + if (id == 9) { + return ""; + } id++; chain = info->getChainId(); result += "}|RNA"; @@ -435,8 +634,9 @@ std::string MolToHELM(const ROMol &mol) { result += "{"; peptide = false; Pstate = 2; - } else switch (Pstate) { - case 1: + } else { + switch (Pstate) { + case 1: #if 0 // Do the same as state 4 for Biovia friendly HELM Pstate = 3; break; @@ -447,6 +647,7 @@ std::string MolToHELM(const ROMol &mol) { break; default: return ""; + } } result += mono; } else if (info->getName() == " P ") { @@ -459,7 +660,9 @@ std::string MolToHELM(const ROMol &mol) { Pstate = 1; } else if (peptide || info->getChainId() != chain) { // Nine chains should be enough? - if (id == 9) return ""; + if (id == 9) { + return ""; + } id++; chain = info->getChainId(); result += "}|RNA"; @@ -467,21 +670,24 @@ std::string MolToHELM(const ROMol &mol) { result += "{P"; peptide = false; Pstate = 1; - } else switch (Pstate) { - case 2: - result += 'P'; - Pstate = 4; - break; - case 3: - result += ".P"; - Pstate = 1; - break; - default: - return ""; + } else { + switch (Pstate) { + case 2: + result += 'P'; + Pstate = 4; + break; + case 3: + result += ".P"; + Pstate = 1; + break; + default: + return ""; + } } } else if (info->getResidueName() == "2PO") { - if (first || peptide || info->getChainId() != chain) + if (first || peptide || info->getChainId() != chain) { return ""; + } switch (Pstate) { case 2: result += 'P'; @@ -497,7 +703,9 @@ std::string MolToHELM(const ROMol &mol) { } } - if (first) return ""; + if (first) { + return ""; + } result += "}$"; @@ -507,25 +715,39 @@ std::string MolToHELM(const ROMol &mol) { const Bond *bond = *bondIt; Atom *beg = bond->getBeginAtom(); Atom *end = bond->getEndAtom(); - if (!beg || !end) continue; - AtomPDBResidueInfo *binfo = (AtomPDBResidueInfo *)(beg->getMonomerInfo()); - AtomPDBResidueInfo *einfo = (AtomPDBResidueInfo *)(end->getMonomerInfo()); - if (!binfo || !einfo) continue; + if (!beg || !end) { + continue; + } + auto *binfo = (AtomPDBResidueInfo *)(beg->getMonomerInfo()); + auto *einfo = (AtomPDBResidueInfo *)(end->getMonomerInfo()); + if (!binfo || !einfo) { + continue; + } // Test if this is an uninteresting intra-residue bond if (binfo->getResidueNumber() == einfo->getResidueNumber() && binfo->getResidueName() == einfo->getResidueName() && binfo->getChainId() == einfo->getChainId() && - binfo->getInsertionCode() == einfo->getInsertionCode()) + binfo->getInsertionCode() == einfo->getInsertionCode()) { continue; - if (bond->getBondType() != Bond::SINGLE) return ""; - if (IsEupeptideBond(binfo, einfo)) continue; - if (!IsSupportedHELMBond(binfo, einfo)) return ""; + } + if (bond->getBondType() != Bond::SINGLE) { + return ""; + } + if (IsEupeptideBond(binfo, einfo)) { + continue; + } + if (!IsSupportedHELMBond(binfo, einfo)) { + return ""; + } std::string tmp = NameHELMBond(seq, binfo, einfo); - if (tmp.empty()) return ""; - if (!first) + if (tmp.empty()) { + return ""; + } + if (!first) { result += "|"; - else + } else { first = false; + } result += tmp; } diff --git a/Code/GraphMol/FileParsers/SmilesMolSupplier.cpp b/Code/GraphMol/FileParsers/SmilesMolSupplier.cpp index c63d86dd6..860e10ef9 100644 --- a/Code/GraphMol/FileParsers/SmilesMolSupplier.cpp +++ b/Code/GraphMol/FileParsers/SmilesMolSupplier.cpp @@ -101,7 +101,9 @@ void SmilesMolSupplier::init() { void SmilesMolSupplier::setData(const std::string &text, const std::string &delimiter, int smilesColumn, int nameColumn, bool titleLine, bool sanitize) { - if (dp_inStream && df_owner) delete dp_inStream; + if (dp_inStream && df_owner) { + delete dp_inStream; + } init(); dp_inStream = new std::stringstream(text); @@ -204,8 +206,9 @@ ROMol *SmilesMolSupplier::processLine(std::string inLine) { // ----------- unsigned int iprop = 0; for (unsigned int col = 0; col < recs.size(); col++) { - if (static_cast(col) == d_smi || static_cast(col) == d_name) + if (static_cast(col) == d_smi || static_cast(col) == d_name) { continue; + } std::string pname, pval; if (d_props.size() > col) { pname = d_props[col]; @@ -258,7 +261,9 @@ ROMol *SmilesMolSupplier::processLine(std::string inLine) { // -------------------------------------------------- std::string SmilesMolSupplier::nextLine() { PRECONDITION(dp_inStream, "bad stream"); - if (df_end) return ""; + if (df_end) { + return ""; + } std::string tempStr = getLine(dp_inStream); if (tempStr == "") { @@ -289,7 +294,9 @@ std::string SmilesMolSupplier::nextLine() { // long int SmilesMolSupplier::skipComments() { PRECONDITION(dp_inStream, "bad stream"); - if (this->atEnd()) return -1; + if (this->atEnd()) { + return -1; + } std::streampos prev = dp_inStream->tellg(); std::string tempStr = this->nextLine(); @@ -298,7 +305,9 @@ long int SmilesMolSupplier::skipComments() { while ((tempStr[0] == '#') || (strip(tempStr).size() == 0)) { prev = dp_inStream->tellg(); tempStr = this->nextLine(); - if (this->atEnd()) break; + if (this->atEnd()) { + break; + } } } // if we hit EOF without getting a proper line, return -1: @@ -387,7 +396,9 @@ void SmilesMolSupplier::moveTo(unsigned int idx) { if (d_molpos.empty()) { // if we are just starting out, process the title line dp_inStream->seekg(0); - if (df_title) this->processTitleLine(); + if (df_title) { + this->processTitleLine(); + } } else { // move to the last position we've seen: dp_inStream->seekg(d_molpos.back()); @@ -516,7 +527,9 @@ unsigned int SmilesMolSupplier::length() { this->skipComments(); } else { // process the title line if need be: - if (df_title) this->processTitleLine(); + if (df_title) { + this->processTitleLine(); + } } int pos = this->skipComments(); while (pos >= 0) { diff --git a/Code/GraphMol/FileParsers/SmilesWriter.cpp b/Code/GraphMol/FileParsers/SmilesWriter.cpp index 5f51507c8..4ad5c1d01 100644 --- a/Code/GraphMol/FileParsers/SmilesWriter.cpp +++ b/Code/GraphMol/FileParsers/SmilesWriter.cpp @@ -86,7 +86,9 @@ void SmilesWriter::dumpHeader() const { CHECK_INVARIANT(dp_ostream, "no output stream"); if (df_includeHeader) { (*dp_ostream) << "SMILES" << d_delim; - if (d_nameHeader != "") (*dp_ostream) << d_nameHeader << d_delim; + if (d_nameHeader != "") { + (*dp_ostream) << d_nameHeader << d_delim; + } if (d_props.size() > 0) { auto pi = d_props.begin(); @@ -103,7 +105,9 @@ void SmilesWriter::dumpHeader() const { SmilesWriter::~SmilesWriter() { // close the writer if it's still open: - if (dp_ostream != nullptr) close(); + if (dp_ostream != nullptr) { + close(); + } } void SmilesWriter::write(const ROMol &mol, int confId) { diff --git a/Code/GraphMol/FileParsers/TDTMolSupplier.cpp b/Code/GraphMol/FileParsers/TDTMolSupplier.cpp index bd9d557b6..d01b2ff98 100644 --- a/Code/GraphMol/FileParsers/TDTMolSupplier.cpp +++ b/Code/GraphMol/FileParsers/TDTMolSupplier.cpp @@ -134,7 +134,9 @@ TDTMolSupplier::~TDTMolSupplier() { void TDTMolSupplier::setData(const std::string &text, const std::string &nameRecord, int confId2D, int confId3D, bool sanitize) { - if (dp_inStream && df_owner) delete dp_inStream; + if (dp_inStream && df_owner) { + delete dp_inStream; + } init(); d_confId2D = confId2D; d_confId3D = confId3D; @@ -156,7 +158,9 @@ bool TDTMolSupplier::advanceToNextRecord() { std::streampos pos; bool res = false; while (1) { - if (dp_inStream->eof()) return false; + if (dp_inStream->eof()) { + return false; + } pos = dp_inStream->tellg(); std::string inL; std::getline(*dp_inStream, inL); @@ -272,8 +276,9 @@ ROMol *TDTMolSupplier::parseMol(std::string inLine) { } else { std::string propVal = inLine.substr(startP, endP - startP); res->setProp(propName, propVal); - if (propName == d_nameProp) + if (propName == d_nameProp) { res->setProp(common_properties::_Name, propVal); + } } } std::getline(*dp_inStream, inLine); diff --git a/Code/GraphMol/FileParsers/TDTWriter.cpp b/Code/GraphMol/FileParsers/TDTWriter.cpp index 5a38b42b6..269ef8058 100644 --- a/Code/GraphMol/FileParsers/TDTWriter.cpp +++ b/Code/GraphMol/FileParsers/TDTWriter.cpp @@ -61,7 +61,9 @@ TDTWriter::TDTWriter(std::ostream *outStream, bool takeOwnership) { TDTWriter::~TDTWriter() { // close the writer if it's still open: - if (dp_ostream != nullptr) close(); + if (dp_ostream != nullptr) { + close(); + } } void TDTWriter::setProps(const STR_VECT &propNames) { @@ -111,7 +113,9 @@ void TDTWriter::write(const ROMol &mol, int confId) { (*dp_ostream) << "," << std::setprecision(d_numDigits) << coords[atomOrdering[i]].z; } - if (i != nAts - 1) (*dp_ostream) << ","; + if (i != nAts - 1) { + (*dp_ostream) << ","; + } } (*dp_ostream) << ";>\n"; } diff --git a/Code/GraphMol/FileParsers/TplFileParser.cpp b/Code/GraphMol/FileParsers/TplFileParser.cpp index 85b1c1af3..680b41b17 100644 --- a/Code/GraphMol/FileParsers/TplFileParser.cpp +++ b/Code/GraphMol/FileParsers/TplFileParser.cpp @@ -43,19 +43,18 @@ void ParseTPLAtomLine(std::string text, unsigned int lineNum, RWMol *mol, atomId = mol->addAtom(atom, false, true); atom->setFormalCharge(FileParserUtils::stripSpacesAndCast(splitLine[2])); - double partialChg = FileParserUtils::stripSpacesAndCast(splitLine[3]); + auto partialChg = FileParserUtils::stripSpacesAndCast(splitLine[3]); atom->setProp("TPLCharge", partialChg); - double xp = FileParserUtils::stripSpacesAndCast(splitLine[4]); - double yp = FileParserUtils::stripSpacesAndCast(splitLine[5]); - double zp = FileParserUtils::stripSpacesAndCast(splitLine[6]); + auto xp = FileParserUtils::stripSpacesAndCast(splitLine[4]); + auto yp = FileParserUtils::stripSpacesAndCast(splitLine[5]); + auto zp = FileParserUtils::stripSpacesAndCast(splitLine[6]); // coords in TPL files are in picometers, adjust: xp /= 100.; yp /= 100.; zp /= 100.; conf->setAtomPos(atomId, RDGeom::Point3D(xp, yp, zp)); - unsigned int nBonds = - FileParserUtils::stripSpacesAndCast(splitLine[7]); + auto nBonds = FileParserUtils::stripSpacesAndCast(splitLine[7]); // the only remaining info we care about is stereochem, and then only if // the number of bonds is 4: if (nBonds == 4 && splitLine.size() > 8 + nBonds) { @@ -151,9 +150,9 @@ Conformer *ParseConfData(std::istream *inStream, unsigned int &line, RWMol *mol, << " while reading conformer " << confId << std::endl; throw FileParseException(errout.str()); } - double xp = FileParserUtils::stripSpacesAndCast(splitLine[0]); - double yp = FileParserUtils::stripSpacesAndCast(splitLine[1]); - double zp = FileParserUtils::stripSpacesAndCast(splitLine[2]); + auto xp = FileParserUtils::stripSpacesAndCast(splitLine[0]); + auto yp = FileParserUtils::stripSpacesAndCast(splitLine[1]); + auto zp = FileParserUtils::stripSpacesAndCast(splitLine[2]); // coords in TPL files are in picometers, adjust: xp /= 100.; yp /= 100.; diff --git a/Code/GraphMol/FileParsers/TplFileWriter.cpp b/Code/GraphMol/FileParsers/TplFileWriter.cpp index 3c475d119..c7b4566c2 100644 --- a/Code/GraphMol/FileParsers/TplFileWriter.cpp +++ b/Code/GraphMol/FileParsers/TplFileWriter.cpp @@ -137,7 +137,9 @@ std::string MolToTPLText(const ROMol &mol, const std::string &partialChargeProp, // write the additional conformations: res << "CONFS " << mol.getNumConformers() - 1 << std::endl; - if (!writeFirstConfTwice) ++confIt; + if (!writeFirstConfTwice) { + ++confIt; + } while (confIt != mol.endConformers()) { std::stringstream tmpStrm; std::string confName; diff --git a/Code/GraphMol/FileParsers/catch_tests.cpp b/Code/GraphMol/FileParsers/catch_tests.cpp index 69e8e6ca3..0cc6b6d90 100644 --- a/Code/GraphMol/FileParsers/catch_tests.cpp +++ b/Code/GraphMol/FileParsers/catch_tests.cpp @@ -733,7 +733,7 @@ M END bool sanitize = false; std::unique_ptr mol(MolBlockToMol(molblock, sanitize)); REQUIRE(mol); - QueryAtom *at = static_cast(mol->getAtomWithIdx(1)); + auto *at = static_cast(mol->getAtomWithIdx(1)); REQUIRE(at->hasQuery()); CHECK(at->getQuery()->getDescription() == "AtomNull"); } diff --git a/Code/GraphMol/FileParsers/test1.cpp b/Code/GraphMol/FileParsers/test1.cpp index d7cf7a341..e68f39034 100644 --- a/Code/GraphMol/FileParsers/test1.cpp +++ b/Code/GraphMol/FileParsers/test1.cpp @@ -1892,7 +1892,7 @@ void testAtomParity() { // add a bogus chiral spec: m->getAtomWithIdx(0)->setChiralTag(Atom::CHI_TETRAHEDRAL_CW); std::string molBlock = MolToMolBlock(*m); - RWMol *m2 = (RWMol *)MolOps::removeHs(*((ROMol *)m)); + auto *m2 = (RWMol *)MolOps::removeHs(*((ROMol *)m)); molBlock = MolToMolBlock(*m2); delete m2; m2 = MolBlockToMol(molBlock, true, false); @@ -2553,7 +2553,7 @@ void test3V3K() { RWMol *m = SmilesToMol(smiles); TEST_ASSERT(m); TEST_ASSERT(m->getNumAtoms() == 1024); - Conformer *conf = new Conformer(m->getNumAtoms()); + auto *conf = new Conformer(m->getNumAtoms()); m->addConformer(conf, true); std::string mb = MolToMolBlock(*m); TEST_ASSERT(mb.find("V2000") == std::string::npos); @@ -3772,8 +3772,8 @@ void testPDBFile() { TEST_ASSERT(feq(m->getConformer().getAtomPos(0).z, 3.625)); // test adding hydrogens - ROMol *nm = MolOps::addHs(*m, false, false, NULL, true); - AtomPDBResidueInfo *info = + ROMol *nm = MolOps::addHs(*m, false, false, nullptr, true); + auto *info = (AtomPDBResidueInfo *)(nm->getAtomWithIdx(nm->getNumAtoms() - 1) ->getMonomerInfo()); TEST_ASSERT(info->getMonomerType() == AtomMonomerInfo::PDBRESIDUE); @@ -4313,8 +4313,9 @@ void testGithub210() { namespace { std::string getResidue(const ROMol &, const Atom *at) { - if (at->getMonomerInfo()->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) + if (at->getMonomerInfo()->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) { return ""; + } return static_cast(at->getMonomerInfo()) ->getResidueName(); } @@ -4641,7 +4642,9 @@ void testParseCHG() { RWMol *m = MolBlockToMol(molblock_chg); size_t i = 0; while (1) { - if (charges[i] == 0) break; + if (charges[i] == 0) { + break; + } TEST_ASSERT( m->getAtomWithIdx((unsigned int)charges[i] - 1)->getFormalCharge() == diff --git a/Code/GraphMol/FileParsers/testMolSupplier.cpp b/Code/GraphMol/FileParsers/testMolSupplier.cpp index 39f2ffba3..681989671 100644 --- a/Code/GraphMol/FileParsers/testMolSupplier.cpp +++ b/Code/GraphMol/FileParsers/testMolSupplier.cpp @@ -272,13 +272,13 @@ int testMolSup() { { // Test Maestro PDB property reading fname = rdbase + "/Code/GraphMol/FileParsers/test_data/1kv1.maegz"; - gzstream *strm = new gzstream(fname); + auto *strm = new gzstream(fname); MaeMolSupplier maesup(strm); std::shared_ptr nmol; nmol.reset(maesup.next()); const Atom *atom = nmol->getAtomWithIdx(0); - AtomPDBResidueInfo *info = (AtomPDBResidueInfo *)(atom->getMonomerInfo()); + auto *info = (AtomPDBResidueInfo *)(atom->getMonomerInfo()); TEST_ASSERT(info->getResidueName() == "ARG "); TEST_ASSERT(info->getChainId() == "A"); TEST_ASSERT(info->getResidueNumber() == 5); @@ -1436,7 +1436,9 @@ void testSDSupplierFromTextStrLax1() { while (!reader.atEnd()) { ROMol *mol = reader.next(); TEST_ASSERT(mol->hasProp(common_properties::_Name)); - if (i == 0) TEST_ASSERT(!mol->hasProp("ID")); + if (i == 0) { + TEST_ASSERT(!mol->hasProp("ID")); + } TEST_ASSERT(!mol->hasProp("ANOTHER_PROPERTY")); i++; delete mol; @@ -1571,7 +1573,9 @@ void testSDSupplierStrLax1() { while (!reader.atEnd()) { ROMol *mol = reader.next(); TEST_ASSERT(mol->hasProp(common_properties::_Name)); - if (i == 0) TEST_ASSERT(!mol->hasProp("ID")); + if (i == 0) { + TEST_ASSERT(!mol->hasProp("ID")); + } TEST_ASSERT(!mol->hasProp("ANOTHER_PROPERTY")); i++; delete mol; @@ -1737,7 +1741,9 @@ void testIssue381() { count = 0; while (!sdsup->atEnd()) { nmol = sdsup->next(); - if (nmol) delete nmol; + if (nmol) { + delete nmol; + } count++; } TEST_ASSERT(sdsup->atEnd()); @@ -1759,10 +1765,14 @@ void testSetStreamIndices() { std::streampos pos = 0; std::string line; while (notEof) { - if (addIndex) pos = ifs.tellg(); + if (addIndex) { + pos = ifs.tellg(); + } notEof = (std::getline(ifs, line) ? true : false); if (notEof) { - if (addIndex) indices.push_back(pos); + if (addIndex) { + indices.push_back(pos); + } addIndex = (line.substr(0, 4) == "$$$$"); } } @@ -1780,7 +1790,9 @@ void testSetStreamIndices() { count = 0; while (!sdsup->atEnd()) { nmol = sdsup->next(); - if (nmol) delete nmol; + if (nmol) { + delete nmol; + } count++; } TEST_ASSERT(sdsup->atEnd()); @@ -2248,8 +2260,12 @@ int testForwardSDSupplier() { while (!strm.eof()) { std::string line; std::getline(strm, line); - if (!strm.eof()) ++i; - if (i > 1000) break; + if (!strm.eof()) { + ++i; + } + if (i > 1000) { + break; + } } TEST_ASSERT(i == 998); } @@ -2259,8 +2275,12 @@ int testForwardSDSupplier() { while (!strm.eof()) { std::string line; std::getline(strm, line); - if (!strm.eof()) ++i; - if (i > 1000) break; + if (!strm.eof()) { + ++i; + } + if (i > 1000) { + break; + } } TEST_ASSERT(i == 997); } @@ -2297,8 +2317,12 @@ int testForwardSDSupplier() { while (!strm.eof()) { std::string line; std::getline(strm, line); - if (!strm.eof()) ++i; - if (i > 1700) break; + if (!strm.eof()) { + ++i; + } + if (i > 1700) { + break; + } } TEST_ASSERT(i == 1663); } @@ -2309,14 +2333,18 @@ int testForwardSDSupplier() { while (!strm.eof()) { std::string line; std::getline(strm, line); - if (!strm.eof()) ++i; - if (i > 1700) break; + if (!strm.eof()) { + ++i; + } + if (i > 1700) { + break; + } } TEST_ASSERT(i == 1663); } // looks good, now do a supplier: { - gzstream *strm = new gzstream(maefname2); + auto *strm = new gzstream(maefname2); MaeMolSupplier maesup(strm); unsigned int i = 0; @@ -2521,7 +2549,9 @@ CC(C)(C)(C)C duff2 unsigned int cnt = 0; while (!suppl.atEnd()) { std::unique_ptr mol(suppl.next()); - if (cnt % 2) TEST_ASSERT(mol); + if (cnt % 2) { + TEST_ASSERT(mol); + } ++cnt; } TEST_ASSERT(cnt == 5); @@ -2770,7 +2800,7 @@ void testGitHub2881() { } )DATA"; { - std::istringstream *iss = new std::istringstream(data); + auto *iss = new std::istringstream(data); bool sanitize = false; bool takeOwnership = true; MaeMolSupplier suppl(iss, takeOwnership, sanitize); diff --git a/Code/GraphMol/FilterCatalog/FilterCatalog.cpp b/Code/GraphMol/FilterCatalog/FilterCatalog.cpp index 60b6e92ac..016b466f5 100644 --- a/Code/GraphMol/FilterCatalog/FilterCatalog.cpp +++ b/Code/GraphMol/FilterCatalog/FilterCatalog.cpp @@ -47,7 +47,7 @@ bool FilterCatalogParams::addCatalog(FilterCatalogs catalog) { // meh, not the best here... perhaps make num_catalogs? for (unsigned int i = 0; i < sizeof(catalog) * CHAR_BIT; ++i) { if ((catalog & (1u << i)) & FilterCatalogParams::ALL) { - FilterCatalogs cat = static_cast(catalog & (1u << i)); + auto cat = static_cast(catalog & (1u << i)); if (GetNumEntries(cat)) { d_catalogs.push_back(cat); addedCatalog = true; @@ -155,13 +155,16 @@ unsigned int FilterCatalog::addEntry(SENTRY entry, bool updateFPLength) { const FilterCatalog::entryType_t *FilterCatalog::getEntryWithIdx( unsigned int idx) const { - if (idx < d_entries.size()) return d_entries[idx].get(); + if (idx < d_entries.size()) { + return d_entries[idx].get(); + } return nullptr; } FilterCatalog::CONST_SENTRY FilterCatalog::getEntry(unsigned int idx) const { - if(idx >= d_entries.size()) + if (idx >= d_entries.size()) { throw IndexErrorException(idx); + } return d_entries[idx]; } @@ -185,14 +188,18 @@ bool FilterCatalog::removeEntry(FilterCatalog::CONST_SENTRY entry) { unsigned int FilterCatalog::getIdxForEntry(const entryType_t *entry) const { for (size_t i = 0; i < d_entries.size(); ++i) { - if (d_entries[i].get() == entry) return i; + if (d_entries[i].get() == entry) { + return i; + } } return UINT_MAX; } unsigned int FilterCatalog::getIdxForEntry(CONST_SENTRY entry) const { for (size_t i = 0; i < d_entries.size(); ++i) { - if (d_entries[i] == entry) return i; + if (d_entries[i] == entry) { + return i; + } } return UINT_MAX; } @@ -210,7 +217,9 @@ bool FilterCatalog::hasMatch(const ROMol &mol) const { FilterCatalog::CONST_SENTRY FilterCatalog::getFirstMatch( const ROMol &mol) const { for (const auto &d_entry : d_entries) { - if (d_entry->hasFilterMatch(mol)) return d_entry; + if (d_entry->hasFilterMatch(mol)) { + return d_entry; + } } return CONST_SENTRY(); } @@ -219,7 +228,9 @@ const std::vector FilterCatalog::getMatches( const ROMol &mol) const { std::vector result; for (const auto &d_entry : d_entries) { - if (d_entry->hasFilterMatch(mol)) result.push_back(d_entry); + if (d_entry->hasFilterMatch(mol)) { + result.push_back(d_entry); + } } return result; } diff --git a/Code/GraphMol/FilterCatalog/FilterCatalogEntry.cpp b/Code/GraphMol/FilterCatalog/FilterCatalogEntry.cpp index 67db97d39..f9734d7c0 100644 --- a/Code/GraphMol/FilterCatalog/FilterCatalogEntry.cpp +++ b/Code/GraphMol/FilterCatalog/FilterCatalogEntry.cpp @@ -81,7 +81,9 @@ FilterCatalogEntry *MakeFilterCatalogEntry(const FilterData_t &data, const int debugParse = 0; const bool mergeHs = true; ROMOL_SPTR pattern(SmartsToMol(data.smarts, debugParse, mergeHs)); - if (!pattern.get()) return nullptr; + if (!pattern.get()) { + return nullptr; + } // The filter has the concept of the maximum number of times the pattern is // allowed diff --git a/Code/GraphMol/FilterCatalog/FilterCatalogRunner.cpp b/Code/GraphMol/FilterCatalog/FilterCatalogRunner.cpp index 3902929bc..a39183831 100644 --- a/Code/GraphMol/FilterCatalog/FilterCatalogRunner.cpp +++ b/Code/GraphMol/FilterCatalog/FilterCatalogRunner.cpp @@ -52,11 +52,12 @@ std::vector>> RunFilterC // There is one result per input smiles std::vector> results(smiles.size()); -#ifdef RDK_THREADSAFE_SSS - if (numThreads == -1) +#ifdef RDK_THREADSAFE_SSS + if (numThreads == -1) { numThreads = (int)getNumThreadsToUse(numThreads); - else + } else { numThreads = std::min(numThreads, (int)getNumThreadsToUse(numThreads)); + } std::vector> thread_group; for (int thread_group_idx = 0; thread_group_idx < numThreads+1; diff --git a/Code/GraphMol/FilterCatalog/FilterMatchers.cpp b/Code/GraphMol/FilterCatalog/FilterMatchers.cpp index 2e9070f7d..4819acb31 100644 --- a/Code/GraphMol/FilterCatalog/FilterMatchers.cpp +++ b/Code/GraphMol/FilterCatalog/FilterMatchers.cpp @@ -93,7 +93,9 @@ bool SmartsMatcher::getMatches(const ROMol &mol, if (d_min_count == 1 && d_max_count == UINT_MAX) { RDKit::MatchVectType match; onPatExists = RDKit::SubstructMatch(mol, *d_pattern.get(), match); - if (onPatExists) matchVect.push_back(FilterMatch(copy(), match)); + if (onPatExists) { + matchVect.push_back(FilterMatch(copy(), match)); + } } else { // need to count const bool uniquify = true; unsigned int count = diff --git a/Code/GraphMol/FilterCatalog/FunctionalGroupHierarchy.cpp b/Code/GraphMol/FilterCatalog/FunctionalGroupHierarchy.cpp index 33d6088af..ad682e717 100644 --- a/Code/GraphMol/FilterCatalog/FunctionalGroupHierarchy.cpp +++ b/Code/GraphMol/FilterCatalog/FunctionalGroupHierarchy.cpp @@ -254,7 +254,9 @@ const FilterCatalog &GetFunctionalGroupHierarchy() { const std::map &GetFlattenedFunctionalGroupHierarchy( bool normalize) { GetFunctionalGroupHierarchy(); - if (normalize) return flatten_normalized_get(); + if (normalize) { + return flatten_normalized_get(); + } return flatten_get(); } } diff --git a/Code/GraphMol/FilterCatalog/Wrap/FilterCatalog.cpp b/Code/GraphMol/FilterCatalog/Wrap/FilterCatalog.cpp index b45ef7271..964833c05 100644 --- a/Code/GraphMol/FilterCatalog/Wrap/FilterCatalog.cpp +++ b/Code/GraphMol/FilterCatalog/Wrap/FilterCatalog.cpp @@ -121,10 +121,11 @@ python::object FilterCatalog_Serialize(const FilterCatalog &cat) { int GetMatchVectItem(std::pair &pair, size_t idx) { static const int def = 0xDEADBEEF; - if (idx == 0) + if (idx == 0) { return pair.first; - else if (idx == 1) + } else if (idx == 1) { return pair.second; + } PyErr_SetString(PyExc_IndexError, "Index out of bounds"); python::throw_error_already_set(); return def; @@ -154,7 +155,9 @@ class PythonFilterMatch : public FilterMatcherBase { } ~PythonFilterMatch() override { - if (incref) python::decref(functor); + if (incref) { + python::decref(functor); + } } bool isValid() const override { return python::call_method(functor, "IsValid"); diff --git a/Code/GraphMol/FilterCatalog/filtercatalogtest.cpp b/Code/GraphMol/FilterCatalog/filtercatalogtest.cpp index d074fc436..302eb3543 100644 --- a/Code/GraphMol/FilterCatalog/filtercatalogtest.cpp +++ b/Code/GraphMol/FilterCatalog/filtercatalogtest.cpp @@ -98,8 +98,9 @@ void testFilterCatalog() { {8, 16}, {9, 21}}; MatchVectType matchvec1; - for (auto i : match1) + for (auto i : match1) { matchvec1.push_back(std::make_pair(i.first, i.second)); + } const IntPair match2[13] = {{0, 11}, {1, 12}, @@ -115,8 +116,9 @@ void testFilterCatalog() { {11, 17}, {12, 16}}; MatchVectType matchvec2; - for (auto i : match2) + for (auto i : match2) { matchvec2.push_back(std::make_pair(i.first, i.second)); + } const IntPair match3[12] = {{0, 0}, {1, 1}, @@ -131,8 +133,9 @@ void testFilterCatalog() { {10, 15}, {11, 16}}; MatchVectType matchvec3; - for (auto i : match3) + for (auto i : match3) { matchvec3.push_back(std::make_pair(i.first, i.second)); + } int count = 0; while (!suppl.atEnd()) { mol.reset(suppl.next()); diff --git a/Code/GraphMol/FindRings.cpp b/Code/GraphMol/FindRings.cpp index e08911155..58d15377d 100644 --- a/Code/GraphMol/FindRings.cpp +++ b/Code/GraphMol/FindRings.cpp @@ -38,16 +38,20 @@ std::uint32_t computeRingInvariant(INT_VECT ring, unsigned int nAtoms) { void convertToBonds(const INT_VECT &ring, INT_VECT &bondRing, const ROMol &mol) { - const unsigned int rsiz = rdcast(ring.size()); + const auto rsiz = rdcast(ring.size()); bondRing.resize(rsiz); for (unsigned int i = 0; i < (rsiz - 1); i++) { const Bond *bnd = mol.getBondBetweenAtoms(ring[i], ring[i + 1]); - if (!bnd) throw ValueErrorException("expected bond not found"); + if (!bnd) { + throw ValueErrorException("expected bond not found"); + } bondRing[i] = bnd->getIdx(); } // bond from last to first atom const Bond *bnd = mol.getBondBetweenAtoms(ring[rsiz - 1], ring[0]); - if (!bnd) throw ValueErrorException("expected bond not found"); + if (!bnd) { + throw ValueErrorException("expected bond not found"); + } bondRing[rsiz - 1] = bnd->getIdx(); } @@ -92,7 +96,9 @@ void markUselessD2s(unsigned int root, const ROMol &tMol, while (beg != end) { const Bond *bond = tMol[*beg]; ++beg; - if (!activeBonds[bond->getIdx()]) continue; + if (!activeBonds[bond->getIdx()]) { + continue; + } unsigned int oIdx = bond->getOtherAtomIdx(root); if (!forb[oIdx] && atomDegrees[oIdx] == 2) { forb[oIdx] = 1; @@ -146,7 +152,7 @@ void findSSSRforDupCands(const ROMol &mol, VECT_INT_VECT &res, if (dupCands.size() > 1) { // we have duplicate candidates. VECT_INT_VECT nrings; - unsigned int minSiz = static_cast(MAX_INT); + auto minSiz = static_cast(MAX_INT); for (int dupCand : dupCands) { // now break bonds for all the d2 nodes for that give the same rings as // with (*dupi) and recompute smallest ring with (*dupi) @@ -226,8 +232,12 @@ void removeExtraRings(VECT_INT_VECT &res, unsigned int nexpt, for (unsigned int i = 0; i < res.size(); ++i) { // skip this ring if we've already seen all of its bonds - if (bitBrings[i].is_subset_of(munion)) availRings.set(i, 0); - if (!availRings[i]) continue; + if (bitBrings[i].is_subset_of(munion)) { + availRings.set(i, 0); + } + if (!availRings[i]) { + continue; + } munion |= bitBrings[i]; keepRings.set(i); @@ -253,7 +263,9 @@ void removeExtraRings(VECT_INT_VECT &res, unsigned int nexpt, for (unsigned int j = i + 1; j < res.size() && bitBrings[j].count() == bitBrings[i].count(); ++j) { - if (!consider[j] || !availRings[j]) continue; + if (!consider[j] || !availRings[j]) { + continue; + } int overlap = rdcast((bitBrings[j] & munion).count()); if (overlap > bestOverlap) { bestOverlap = overlap; @@ -430,17 +442,23 @@ void findRingsD3Node(const ROMol &tMol, VECT_INT_VECT &res, ROMol::OEDGE_ITER beg, end; boost::tie(beg, end) = tMol.getAtomBonds(tMol.getAtomWithIdx(cand)); - while (beg != end && !activeBonds[tMol[*beg]->getIdx()]) ++beg; + while (beg != end && !activeBonds[tMol[*beg]->getIdx()]) { + ++beg; + } CHECK_INVARIANT(beg != end, "neighbor not found"); n1 = tMol[*beg]->getOtherAtomIdx(cand); ++beg; - while (beg != end && !activeBonds[tMol[*beg]->getIdx()]) ++beg; + while (beg != end && !activeBonds[tMol[*beg]->getIdx()]) { + ++beg; + } CHECK_INVARIANT(beg != end, "neighbor not found"); n2 = tMol[*beg]->getOtherAtomIdx(cand); ++beg; - while (beg != end && !activeBonds[tMol[*beg]->getIdx()]) ++beg; + while (beg != end && !activeBonds[tMol[*beg]->getIdx()]) { + ++beg; + } CHECK_INVARIANT(beg != end, "neighbor not found"); n3 = tMol[*beg]->getOtherAtomIdx(cand); @@ -583,9 +601,13 @@ void trimBonds(unsigned int cand, const ROMol &tMol, INT_SET &changed, while (beg != end) { const Bond *bond = tMol[*beg]; ++beg; - if (!activeBonds[bond->getIdx()]) continue; + if (!activeBonds[bond->getIdx()]) { + continue; + } unsigned int oIdx = bond->getOtherAtomIdx(cand); - if (atomDegrees[oIdx] <= 2) changed.insert(oIdx); + if (atomDegrees[oIdx] <= 2) { + changed.insert(oIdx); + } activeBonds[bond->getIdx()] = 0; atomDegrees[oIdx] -= 1; atomDegrees[cand] -= 1; @@ -659,7 +681,9 @@ int smallestRingsBfs(const ROMol &mol, int root, VECT_INT_VECT &rings, while (beg != end) { const Bond *bond = mol[*beg]; ++beg; - if (!activeBonds[bond->getIdx()]) continue; + if (!activeBonds[bond->getIdx()]) { + continue; + } int nbrIdx = bond->getOtherAtomIdx(curr); if ((std::find(cpath.begin(), cpath.end(), nbrIdx) == cpath.end()) && done[nbrIdx] != BLACK) { @@ -689,7 +713,9 @@ int smallestRingsBfs(const ROMol &mol, int root, VECT_INT_VECT &rings, if (std::find(npath.begin(), npath.end(), (*ci)) != npath.end()) { com++; id = (*ci); - if (id != root) break; + if (id != root) { + break; + } } } // end of found stuff in common with neighbor @@ -861,7 +887,9 @@ int findSSSR(const ROMol &mol, VECT_INT_VECT &res) { boost::tie(firstB, lastB) = mol.getEdges(); while (firstB != lastB) { const Bond *bond = mol[*firstB]; - if (bond->getBondType() == Bond::ZERO) activeBonds[bond->getIdx()] = 0; + if (bond->getBondType() == Bond::ZERO) { + activeBonds[bond->getIdx()] = 0; + } ++firstB; } @@ -879,7 +907,9 @@ int findSSSR(const ROMol &mol, VECT_INT_VECT &res) { boost::tie(beg, end) = mol.getAtomBonds(atom); while (beg != end) { const Bond *bond = mol[*beg]; - if (bond->getBondType() == Bond::ZERO) atomDegrees[i]--; + if (bond->getBondType() == Bond::ZERO) { + atomDegrees[i]--; + } ++beg; } } @@ -893,7 +923,9 @@ int findSSSR(const ROMol &mol, VECT_INT_VECT &res) { VECT_INT_VECT fragRes; curFrag = frags[fi]; - if (curFrag.size() < 3) continue; + if (curFrag.size() < 3) { + continue; + } // the following is the list of atoms that are useful in the next round of // trimming @@ -919,7 +951,9 @@ int findSSSR(const ROMol &mol, VECT_INT_VECT &res) { "fragment graph has a dangling degree"); bndcnt_with_zero_order_bonds = bndcnt_with_zero_order_bonds / 2; int num_possible_rings = bndcnt_with_zero_order_bonds - curFrag.size() + 1; - if (num_possible_rings < 1) continue; + if (num_possible_rings < 1) { + continue; + } CHECK_INVARIANT(nbnds % 2 == 0, "fragment graph problem when including zero-order bonds"); @@ -1035,7 +1069,9 @@ int findSSSR(const ROMol &mol, VECT_INT_VECT &res) { while (possibleBonds.size()) { bool ringFound = FindRings::findRingConnectingAtoms( mol, possibleBonds[0], fragRes, invars, ringBonds, ringAtoms); - if (!ringFound) deadBonds.set(possibleBonds[0]->getIdx(), 1); + if (!ringFound) { + deadBonds.set(possibleBonds[0]->getIdx(), 1); + } possibleBonds.clear(); // check if we need to repeat the process: for (unsigned int i = 0; i < nbnds; ++i) { @@ -1257,7 +1293,9 @@ void fastFindRings(const ROMol &mol) { INT_VECT atomColors(nats, 0); for (unsigned int i = 0; i < nats; ++i) { - if (atomColors[i]) continue; + if (atomColors[i]) { + continue; + } if (mol.getAtomWithIdx(i)->getDegree() < 2) { atomColors[i] = 2; continue; @@ -1286,7 +1324,7 @@ void findRingFamilies(const ROMol &mol) { RDL_addUEdge(graph, (*cbi)->getBeginAtomIdx(), (*cbi)->getEndAtomIdx()); } RDL_data *urfdata = RDL_calculate(graph); - if (urfdata == NULL) { + if (urfdata == nullptr) { RDL_deleteGraph(graph); mol.getRingInfo()->dp_urfData.reset(); throw ValueErrorException("Cannot get URFs"); diff --git a/Code/GraphMol/Fingerprints/AtomPairGenerator.cpp b/Code/GraphMol/Fingerprints/AtomPairGenerator.cpp index f66ae3598..f36912514 100644 --- a/Code/GraphMol/Fingerprints/AtomPairGenerator.cpp +++ b/Code/GraphMol/Fingerprints/AtomPairGenerator.cpp @@ -89,7 +89,7 @@ OutputType AtomPairAtomEnv::getBitId( (atomInvariants->size() >= d_atomIdSecond), "bad atom invariants size"); - AtomPairArguments *atomPairArguments = + auto *atomPairArguments = dynamic_cast *>(arguments); std::uint32_t codeSizeLimit = @@ -144,7 +144,7 @@ AtomPairEnvGenerator::getEnvironments( additionalOutput->atomToBits->size() == atomCount, "bad atomToBits size in AdditionalOutput"); - AtomPairArguments *atomPairArguments = + auto *atomPairArguments = dynamic_cast *>(arguments); std::vector *> result = std::vector *>(); @@ -178,7 +178,7 @@ AtomPairEnvGenerator::getEnvironments( fromAtoms->end())) { continue; } - unsigned int distance = + auto distance = static_cast(floor(distanceMatrix[i * atomCount + j])); if (distance >= atomPairArguments->d_minDistance && diff --git a/Code/GraphMol/Fingerprints/AtomPairs.cpp b/Code/GraphMol/Fingerprints/AtomPairs.cpp index 864eb5744..6abca41ee 100644 --- a/Code/GraphMol/Fingerprints/AtomPairs.cpp +++ b/Code/GraphMol/Fingerprints/AtomPairs.cpp @@ -37,7 +37,7 @@ void setAtomPairBit(std::uint32_t i, std::uint32_t j, const std::vector &atomCodes, const double *dm, T *bv, unsigned int minLength, unsigned int maxLength, bool includeChirality) { - unsigned int dist = static_cast(floor(dm[i * nAtoms + j])); + auto dist = static_cast(floor(dm[i * nAtoms + j])); if (dist >= minLength && dist <= maxLength) { std::uint32_t bitId = getAtomPairCode(atomCodes[i], atomCodes[j], dist, includeChirality); @@ -185,8 +185,7 @@ SparseIntVect *getHashedAtomPairFingerprint( j) != ignoreAtoms->end()) { continue; } - unsigned int dist = - static_cast(floor(dm[i * nAtoms + j])); + auto dist = static_cast(floor(dm[i * nAtoms + j])); if (dist >= minLength && dist <= maxLength) { std::uint32_t bit = 0; gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j])); @@ -202,8 +201,7 @@ SparseIntVect *getHashedAtomPairFingerprint( j) != ignoreAtoms->end()) { continue; } - unsigned int dist = - static_cast(floor(dm[i * nAtoms + j])); + auto dist = static_cast(floor(dm[i * nAtoms + j])); if (dist >= minLength && dist <= maxLength) { std::uint32_t bit = 0; gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j])); @@ -238,8 +236,9 @@ ExplicitBitVect *getHashedAtomPairFingerprintAsBitVect( BOOST_FOREACH (SparseIntVect::StorageType::value_type val, sres->getNonzeroElements()) { for (unsigned int i = 0; i < nBitsPerEntry; ++i) { - if (val.second > static_cast(i)) + if (val.second > static_cast(i)) { res->setBit(val.first * nBitsPerEntry + i); + } } } } else { @@ -476,8 +475,9 @@ ExplicitBitVect *getHashedTopologicalTorsionFingerprintAsBitVect( BOOST_FOREACH (SparseIntVect::StorageType::value_type val, sres->getNonzeroElements()) { for (unsigned int i = 0; i < nBitsPerEntry; ++i) { - if (val.second > static_cast(i)) + if (val.second > static_cast(i)) { res->setBit(val.first * nBitsPerEntry + i); + } } } } else { diff --git a/Code/GraphMol/Fingerprints/FingerprintGenerator.cpp b/Code/GraphMol/Fingerprints/FingerprintGenerator.cpp index c2b8833c6..bcd6ee4ab 100644 --- a/Code/GraphMol/Fingerprints/FingerprintGenerator.cpp +++ b/Code/GraphMol/Fingerprints/FingerprintGenerator.cpp @@ -260,7 +260,7 @@ SparseBitVect *FingerprintGenerator::getSparseFingerprint( mol, fromAtoms, ignoreAtoms, confId, additionalOutput, customAtomInvariants, customBondInvariants, effectiveSize); - SparseBitVect *result = new SparseBitVect(resultSize); + auto *result = new SparseBitVect(resultSize); BOOST_FOREACH (auto val, tempResult->getNonzeroElements()) { if (dp_fingerprintArguments->d_countSimulation) { @@ -296,7 +296,7 @@ SparseIntVect customAtomInvariants, customBondInvariants, dp_fingerprintArguments->d_fpSize); - SparseIntVect *result = + auto *result = new SparseIntVect(dp_fingerprintArguments->d_fpSize); BOOST_FOREACH (auto val, tempResult->getNonzeroElements()) { result->setVal(val.first, val.second); @@ -323,8 +323,7 @@ ExplicitBitVect *FingerprintGenerator::getFingerprint( mol, fromAtoms, ignoreAtoms, confId, additionalOutput, customAtomInvariants, customBondInvariants, effectiveSize); - ExplicitBitVect *result = - new ExplicitBitVect(dp_fingerprintArguments->d_fpSize); + auto *result = new ExplicitBitVect(dp_fingerprintArguments->d_fpSize); BOOST_FOREACH (auto val, tempResult->getNonzeroElements()) { if (dp_fingerprintArguments->d_countSimulation) { for (unsigned int i = 0; @@ -457,8 +456,7 @@ std::vector *> *getSparseCountFPBulk( "Fingerprint type not implemented for getSparseCountFP"); } } - std::vector *> *res = - new std::vector *>(); + auto *res = new std::vector *>(); BOOST_FOREACH (const ROMol *mol, molVector) { res->push_back(generator->getSparseCountFingerprint(*mol)); @@ -494,7 +492,7 @@ std::vector *getSparseFPBulk( "Fingerprint type not implemented for getSparseFP"); } } - std::vector *res = new std::vector(); + auto *res = new std::vector(); BOOST_FOREACH (const ROMol *mol, molVector) { res->push_back(generator->getSparseFingerprint(*mol)); @@ -530,8 +528,7 @@ std::vector *> *getCountFPBulk( "Fingerprint type not implemented for getCountFP"); } } - std::vector *> *res = - new std::vector *>(); + auto *res = new std::vector *>(); BOOST_FOREACH (const ROMol *mol, molVector) { res->push_back(generator->getCountFingerprint(*mol)); @@ -567,7 +564,7 @@ std::vector *getFPBulk( "Fingerprint type not implemented for getFP"); } } - std::vector *res = new std::vector(); + auto *res = new std::vector(); BOOST_FOREACH (const ROMol *mol, molVector) { res->push_back(generator->getFingerprint(*mol)); diff --git a/Code/GraphMol/Fingerprints/FingerprintUtil.cpp b/Code/GraphMol/Fingerprints/FingerprintUtil.cpp index a9c2a9ff3..57c52c252 100644 --- a/Code/GraphMol/Fingerprints/FingerprintUtil.cpp +++ b/Code/GraphMol/Fingerprints/FingerprintUtil.cpp @@ -49,7 +49,7 @@ unsigned int numPiElectrons(const Atom *atom) { if (atom->getIsAromatic()) { res = 1; } else if (atom->getHybridization() != Atom::SP3) { - unsigned int val = static_cast(atom->getExplicitValence()); + auto val = static_cast(atom->getExplicitValence()); val -= atom->getNumExplicitHs(); CHECK_INVARIANT(val >= atom->getDegree(), "explicit valence exceeds atom degree"); @@ -85,7 +85,9 @@ std::uint32_t getAtomCode(const Atom *atom, unsigned int branchSubtract, } ++typeIdx; } - if (typeIdx == nTypes) --typeIdx; + if (typeIdx == nTypes) { + --typeIdx; + } code |= typeIdx << (numBranchBits + numPiBits); if (includeChirality) { std::string cipCode; @@ -371,7 +373,9 @@ std::vector generateBondHashes( atomDegrees[bi->getEndAtomIdx()]++; atomsInPath.set(bi->getBeginAtomIdx()); atomsInPath.set(bi->getEndAtomIdx()); - if (isQueryBond[path[i]]) queryInPath = true; + if (isQueryBond[path[i]]) { + queryInPath = true; + } } if (queryInPath) { return bondHashes; diff --git a/Code/GraphMol/Fingerprints/Fingerprints.cpp b/Code/GraphMol/Fingerprints/Fingerprints.cpp index e5b71215d..a99f37717 100644 --- a/Code/GraphMol/Fingerprints/Fingerprints.cpp +++ b/Code/GraphMol/Fingerprints/Fingerprints.cpp @@ -482,7 +482,9 @@ ExplicitBitVect *LayeredFingerprintMol( boost::tie(firstA, lastA) = mol.getVertices(); while (firstA != lastA) { const Atom *atom = mol[*firstA]; - if (isAtomAromatic(atom)) aromaticAtoms[atom->getIdx()] = true; + if (isAtomAromatic(atom)) { + aromaticAtoms[atom->getIdx()] = true; + } anums[atom->getIdx()] = atom->getAtomicNum(); ++firstA; } @@ -528,7 +530,9 @@ ExplicitBitVect *LayeredFingerprintMol( std::vector> hashLayers(maxFingerprintLayers); for (unsigned int i = 0; i < maxFingerprintLayers; ++i) { - if (layerFlags & (0x1 << i)) hashLayers[i].reserve(maxPath); + if (layerFlags & (0x1 << i)) { + hashLayers[i].reserve(maxPath); + } } // details about what kinds of query features appear on the path: @@ -648,7 +652,9 @@ ExplicitBitVect *LayeredFingerprintMol( bool a1Hash = aromaticAtoms[bi->getBeginAtomIdx()]; bool a2Hash = aromaticAtoms[bi->getEndAtomIdx()]; - if ((!a1Hash) && a2Hash) std::swap(a1Hash, a2Hash); + if ((!a1Hash) && a2Hash) { + std::swap(a1Hash, a2Hash); + } ourHash = a1Hash; ourHash |= a2Hash << 1; ourHash |= (bondNbrs[i] % 8) << 5; @@ -659,7 +665,9 @@ ExplicitBitVect *LayeredFingerprintMol( bool flaggedPath = false; for (auto layerIt = hashLayers.begin(); layerIt != hashLayers.end(); ++layerIt, ++l) { - if (!layerIt->size()) continue; + if (!layerIt->size()) { + continue; + } // ---- std::sort(layerIt->begin(), layerIt->end()); diff --git a/Code/GraphMol/Fingerprints/MACCS.cpp b/Code/GraphMol/Fingerprints/MACCS.cpp index ffbe55b37..830acfb67 100644 --- a/Code/GraphMol/Fingerprints/MACCS.cpp +++ b/Code/GraphMol/Fingerprints/MACCS.cpp @@ -318,14 +318,16 @@ void GenerateFP(const RDKit::ROMol &mol, ExplicitBitVect &fp) { PRECONDITION(fp.size() == 167, "bad fingerprint"); fp.clearBits(); - if (!mol.getNumAtoms()) return; + if (!mol.getNumAtoms()) { + return; + } std::vector matches; RDKit::RWMol::ConstAtomIterator atom; RDKit::MatchVectType match; unsigned int count; - for (atom = mol.beginAtoms(); atom != mol.endAtoms(); ++atom) + for (atom = mol.beginAtoms(); atom != mol.endAtoms(); ++atom) { switch ((*atom)->getAtomicNum()) { case 3: case 11: @@ -458,164 +460,450 @@ void GenerateFP(const RDKit::ROMol &mol, ExplicitBitVect &fp) { fp.setBit(2); break; } + } - if (RDKit::SubstructMatch(mol, *pats.bit_8, match, true)) fp.setBit(8); - if (RDKit::SubstructMatch(mol, *pats.bit_11, match, true)) fp.setBit(11); - if (RDKit::SubstructMatch(mol, *pats.bit_13, match, true)) fp.setBit(13); - if (RDKit::SubstructMatch(mol, *pats.bit_14, match, true)) fp.setBit(14); - if (RDKit::SubstructMatch(mol, *pats.bit_15, match, true)) fp.setBit(15); - if (RDKit::SubstructMatch(mol, *pats.bit_16, match, true)) fp.setBit(16); - if (RDKit::SubstructMatch(mol, *pats.bit_17, match, true)) fp.setBit(17); - if (RDKit::SubstructMatch(mol, *pats.bit_19, match, true)) fp.setBit(19); - if (RDKit::SubstructMatch(mol, *pats.bit_20, match, true)) fp.setBit(20); - if (RDKit::SubstructMatch(mol, *pats.bit_21, match, true)) fp.setBit(21); - if (RDKit::SubstructMatch(mol, *pats.bit_22, match, true)) fp.setBit(22); - if (RDKit::SubstructMatch(mol, *pats.bit_23, match, true)) fp.setBit(23); - if (RDKit::SubstructMatch(mol, *pats.bit_24, match, true)) fp.setBit(24); - if (RDKit::SubstructMatch(mol, *pats.bit_25, match, true)) fp.setBit(25); - if (RDKit::SubstructMatch(mol, *pats.bit_26, match, true)) fp.setBit(26); - if (RDKit::SubstructMatch(mol, *pats.bit_28, match, true)) fp.setBit(28); - if (RDKit::SubstructMatch(mol, *pats.bit_30, match, true)) fp.setBit(30); - if (RDKit::SubstructMatch(mol, *pats.bit_31, match, true)) fp.setBit(31); - if (RDKit::SubstructMatch(mol, *pats.bit_32, match, true)) fp.setBit(32); - if (RDKit::SubstructMatch(mol, *pats.bit_33, match, true)) fp.setBit(33); - if (RDKit::SubstructMatch(mol, *pats.bit_34, match, true)) fp.setBit(34); - if (RDKit::SubstructMatch(mol, *pats.bit_36, match, true)) fp.setBit(36); - if (RDKit::SubstructMatch(mol, *pats.bit_37, match, true)) fp.setBit(37); - if (RDKit::SubstructMatch(mol, *pats.bit_38, match, true)) fp.setBit(38); - if (RDKit::SubstructMatch(mol, *pats.bit_39, match, true)) fp.setBit(39); - if (RDKit::SubstructMatch(mol, *pats.bit_40, match, true)) fp.setBit(40); - if (RDKit::SubstructMatch(mol, *pats.bit_41, match, true)) fp.setBit(41); - if (RDKit::SubstructMatch(mol, *pats.bit_43, match, true)) fp.setBit(43); - if (RDKit::SubstructMatch(mol, *pats.bit_44, match, true)) fp.setBit(44); - if (RDKit::SubstructMatch(mol, *pats.bit_45, match, true)) fp.setBit(45); - if (RDKit::SubstructMatch(mol, *pats.bit_47, match, true)) fp.setBit(47); - if (RDKit::SubstructMatch(mol, *pats.bit_48, match, true)) fp.setBit(48); - if (RDKit::SubstructMatch(mol, *pats.bit_49, match, true)) fp.setBit(49); - if (RDKit::SubstructMatch(mol, *pats.bit_50, match, true)) fp.setBit(50); - if (RDKit::SubstructMatch(mol, *pats.bit_51, match, true)) fp.setBit(51); - if (RDKit::SubstructMatch(mol, *pats.bit_52, match, true)) fp.setBit(52); - if (RDKit::SubstructMatch(mol, *pats.bit_53, match, true)) fp.setBit(53); - if (RDKit::SubstructMatch(mol, *pats.bit_54, match, true)) fp.setBit(54); - if (RDKit::SubstructMatch(mol, *pats.bit_55, match, true)) fp.setBit(55); - if (RDKit::SubstructMatch(mol, *pats.bit_56, match, true)) fp.setBit(56); - if (RDKit::SubstructMatch(mol, *pats.bit_57, match, true)) fp.setBit(57); - if (RDKit::SubstructMatch(mol, *pats.bit_58, match, true)) fp.setBit(58); - if (RDKit::SubstructMatch(mol, *pats.bit_59, match, true)) fp.setBit(59); - if (RDKit::SubstructMatch(mol, *pats.bit_60, match, true)) fp.setBit(60); - if (RDKit::SubstructMatch(mol, *pats.bit_61, match, true)) fp.setBit(61); - if (RDKit::SubstructMatch(mol, *pats.bit_62, match, true)) fp.setBit(62); - if (RDKit::SubstructMatch(mol, *pats.bit_63, match, true)) fp.setBit(63); - if (RDKit::SubstructMatch(mol, *pats.bit_64, match, true)) fp.setBit(64); - if (RDKit::SubstructMatch(mol, *pats.bit_65, match, true)) fp.setBit(65); - if (RDKit::SubstructMatch(mol, *pats.bit_66, match, true)) fp.setBit(66); - if (RDKit::SubstructMatch(mol, *pats.bit_67, match, true)) fp.setBit(67); - if (RDKit::SubstructMatch(mol, *pats.bit_68, match, true)) fp.setBit(68); - if (RDKit::SubstructMatch(mol, *pats.bit_69, match, true)) fp.setBit(69); - if (RDKit::SubstructMatch(mol, *pats.bit_70, match, true)) fp.setBit(70); - if (RDKit::SubstructMatch(mol, *pats.bit_71, match, true)) fp.setBit(71); - if (RDKit::SubstructMatch(mol, *pats.bit_72, match, true)) fp.setBit(72); - if (RDKit::SubstructMatch(mol, *pats.bit_73, match, true)) fp.setBit(73); - if (RDKit::SubstructMatch(mol, *pats.bit_74, match, true)) fp.setBit(74); - if (RDKit::SubstructMatch(mol, *pats.bit_75, match, true)) fp.setBit(75); - if (RDKit::SubstructMatch(mol, *pats.bit_76, match, true)) fp.setBit(76); - if (RDKit::SubstructMatch(mol, *pats.bit_77, match, true)) fp.setBit(77); - if (RDKit::SubstructMatch(mol, *pats.bit_78, match, true)) fp.setBit(78); - if (RDKit::SubstructMatch(mol, *pats.bit_79, match, true)) fp.setBit(79); - if (RDKit::SubstructMatch(mol, *pats.bit_80, match, true)) fp.setBit(80); - if (RDKit::SubstructMatch(mol, *pats.bit_81, match, true)) fp.setBit(81); - if (RDKit::SubstructMatch(mol, *pats.bit_82, match, true)) fp.setBit(82); - if (RDKit::SubstructMatch(mol, *pats.bit_83, match, true)) fp.setBit(83); - if (RDKit::SubstructMatch(mol, *pats.bit_84, match, true)) fp.setBit(84); - if (RDKit::SubstructMatch(mol, *pats.bit_85, match, true)) fp.setBit(85); - if (RDKit::SubstructMatch(mol, *pats.bit_86, match, true)) fp.setBit(86); - if (RDKit::SubstructMatch(mol, *pats.bit_87, match, true)) fp.setBit(87); - if (RDKit::SubstructMatch(mol, *pats.bit_89, match, true)) fp.setBit(89); - if (RDKit::SubstructMatch(mol, *pats.bit_90, match, true)) fp.setBit(90); - if (RDKit::SubstructMatch(mol, *pats.bit_91, match, true)) fp.setBit(91); - if (RDKit::SubstructMatch(mol, *pats.bit_92, match, true)) fp.setBit(92); - if (RDKit::SubstructMatch(mol, *pats.bit_93, match, true)) fp.setBit(93); - if (RDKit::SubstructMatch(mol, *pats.bit_94, match, true)) fp.setBit(94); - if (RDKit::SubstructMatch(mol, *pats.bit_95, match, true)) fp.setBit(95); - if (RDKit::SubstructMatch(mol, *pats.bit_96, match, true)) fp.setBit(96); - if (RDKit::SubstructMatch(mol, *pats.bit_97, match, true)) fp.setBit(97); - if (RDKit::SubstructMatch(mol, *pats.bit_98, match, true)) fp.setBit(98); - if (RDKit::SubstructMatch(mol, *pats.bit_99, match, true)) fp.setBit(99); - if (RDKit::SubstructMatch(mol, *pats.bit_100, match, true)) fp.setBit(100); - if (RDKit::SubstructMatch(mol, *pats.bit_101, match, true)) fp.setBit(101); - if (RDKit::SubstructMatch(mol, *pats.bit_102, match, true)) fp.setBit(102); - if (RDKit::SubstructMatch(mol, *pats.bit_104, match, true)) fp.setBit(104); - if (RDKit::SubstructMatch(mol, *pats.bit_105, match, true)) fp.setBit(105); - if (RDKit::SubstructMatch(mol, *pats.bit_106, match, true)) fp.setBit(106); - if (RDKit::SubstructMatch(mol, *pats.bit_107, match, true)) fp.setBit(107); - if (RDKit::SubstructMatch(mol, *pats.bit_108, match, true)) fp.setBit(108); - if (RDKit::SubstructMatch(mol, *pats.bit_109, match, true)) fp.setBit(109); - if (RDKit::SubstructMatch(mol, *pats.bit_110, match, true)) fp.setBit(110); - if (RDKit::SubstructMatch(mol, *pats.bit_111, match, true)) fp.setBit(111); - if (RDKit::SubstructMatch(mol, *pats.bit_112, match, true)) fp.setBit(112); - if (RDKit::SubstructMatch(mol, *pats.bit_113, match, true)) fp.setBit(113); - if (RDKit::SubstructMatch(mol, *pats.bit_114, match, true)) fp.setBit(114); - if (RDKit::SubstructMatch(mol, *pats.bit_115, match, true)) fp.setBit(115); - if (RDKit::SubstructMatch(mol, *pats.bit_116, match, true)) fp.setBit(116); - if (RDKit::SubstructMatch(mol, *pats.bit_117, match, true)) fp.setBit(117); - if (RDKit::SubstructMatch(mol, *pats.bit_118, matches, true, true) > 1) + if (RDKit::SubstructMatch(mol, *pats.bit_8, match, true)) { + fp.setBit(8); + } + if (RDKit::SubstructMatch(mol, *pats.bit_11, match, true)) { + fp.setBit(11); + } + if (RDKit::SubstructMatch(mol, *pats.bit_13, match, true)) { + fp.setBit(13); + } + if (RDKit::SubstructMatch(mol, *pats.bit_14, match, true)) { + fp.setBit(14); + } + if (RDKit::SubstructMatch(mol, *pats.bit_15, match, true)) { + fp.setBit(15); + } + if (RDKit::SubstructMatch(mol, *pats.bit_16, match, true)) { + fp.setBit(16); + } + if (RDKit::SubstructMatch(mol, *pats.bit_17, match, true)) { + fp.setBit(17); + } + if (RDKit::SubstructMatch(mol, *pats.bit_19, match, true)) { + fp.setBit(19); + } + if (RDKit::SubstructMatch(mol, *pats.bit_20, match, true)) { + fp.setBit(20); + } + if (RDKit::SubstructMatch(mol, *pats.bit_21, match, true)) { + fp.setBit(21); + } + if (RDKit::SubstructMatch(mol, *pats.bit_22, match, true)) { + fp.setBit(22); + } + if (RDKit::SubstructMatch(mol, *pats.bit_23, match, true)) { + fp.setBit(23); + } + if (RDKit::SubstructMatch(mol, *pats.bit_24, match, true)) { + fp.setBit(24); + } + if (RDKit::SubstructMatch(mol, *pats.bit_25, match, true)) { + fp.setBit(25); + } + if (RDKit::SubstructMatch(mol, *pats.bit_26, match, true)) { + fp.setBit(26); + } + if (RDKit::SubstructMatch(mol, *pats.bit_28, match, true)) { + fp.setBit(28); + } + if (RDKit::SubstructMatch(mol, *pats.bit_30, match, true)) { + fp.setBit(30); + } + if (RDKit::SubstructMatch(mol, *pats.bit_31, match, true)) { + fp.setBit(31); + } + if (RDKit::SubstructMatch(mol, *pats.bit_32, match, true)) { + fp.setBit(32); + } + if (RDKit::SubstructMatch(mol, *pats.bit_33, match, true)) { + fp.setBit(33); + } + if (RDKit::SubstructMatch(mol, *pats.bit_34, match, true)) { + fp.setBit(34); + } + if (RDKit::SubstructMatch(mol, *pats.bit_36, match, true)) { + fp.setBit(36); + } + if (RDKit::SubstructMatch(mol, *pats.bit_37, match, true)) { + fp.setBit(37); + } + if (RDKit::SubstructMatch(mol, *pats.bit_38, match, true)) { + fp.setBit(38); + } + if (RDKit::SubstructMatch(mol, *pats.bit_39, match, true)) { + fp.setBit(39); + } + if (RDKit::SubstructMatch(mol, *pats.bit_40, match, true)) { + fp.setBit(40); + } + if (RDKit::SubstructMatch(mol, *pats.bit_41, match, true)) { + fp.setBit(41); + } + if (RDKit::SubstructMatch(mol, *pats.bit_43, match, true)) { + fp.setBit(43); + } + if (RDKit::SubstructMatch(mol, *pats.bit_44, match, true)) { + fp.setBit(44); + } + if (RDKit::SubstructMatch(mol, *pats.bit_45, match, true)) { + fp.setBit(45); + } + if (RDKit::SubstructMatch(mol, *pats.bit_47, match, true)) { + fp.setBit(47); + } + if (RDKit::SubstructMatch(mol, *pats.bit_48, match, true)) { + fp.setBit(48); + } + if (RDKit::SubstructMatch(mol, *pats.bit_49, match, true)) { + fp.setBit(49); + } + if (RDKit::SubstructMatch(mol, *pats.bit_50, match, true)) { + fp.setBit(50); + } + if (RDKit::SubstructMatch(mol, *pats.bit_51, match, true)) { + fp.setBit(51); + } + if (RDKit::SubstructMatch(mol, *pats.bit_52, match, true)) { + fp.setBit(52); + } + if (RDKit::SubstructMatch(mol, *pats.bit_53, match, true)) { + fp.setBit(53); + } + if (RDKit::SubstructMatch(mol, *pats.bit_54, match, true)) { + fp.setBit(54); + } + if (RDKit::SubstructMatch(mol, *pats.bit_55, match, true)) { + fp.setBit(55); + } + if (RDKit::SubstructMatch(mol, *pats.bit_56, match, true)) { + fp.setBit(56); + } + if (RDKit::SubstructMatch(mol, *pats.bit_57, match, true)) { + fp.setBit(57); + } + if (RDKit::SubstructMatch(mol, *pats.bit_58, match, true)) { + fp.setBit(58); + } + if (RDKit::SubstructMatch(mol, *pats.bit_59, match, true)) { + fp.setBit(59); + } + if (RDKit::SubstructMatch(mol, *pats.bit_60, match, true)) { + fp.setBit(60); + } + if (RDKit::SubstructMatch(mol, *pats.bit_61, match, true)) { + fp.setBit(61); + } + if (RDKit::SubstructMatch(mol, *pats.bit_62, match, true)) { + fp.setBit(62); + } + if (RDKit::SubstructMatch(mol, *pats.bit_63, match, true)) { + fp.setBit(63); + } + if (RDKit::SubstructMatch(mol, *pats.bit_64, match, true)) { + fp.setBit(64); + } + if (RDKit::SubstructMatch(mol, *pats.bit_65, match, true)) { + fp.setBit(65); + } + if (RDKit::SubstructMatch(mol, *pats.bit_66, match, true)) { + fp.setBit(66); + } + if (RDKit::SubstructMatch(mol, *pats.bit_67, match, true)) { + fp.setBit(67); + } + if (RDKit::SubstructMatch(mol, *pats.bit_68, match, true)) { + fp.setBit(68); + } + if (RDKit::SubstructMatch(mol, *pats.bit_69, match, true)) { + fp.setBit(69); + } + if (RDKit::SubstructMatch(mol, *pats.bit_70, match, true)) { + fp.setBit(70); + } + if (RDKit::SubstructMatch(mol, *pats.bit_71, match, true)) { + fp.setBit(71); + } + if (RDKit::SubstructMatch(mol, *pats.bit_72, match, true)) { + fp.setBit(72); + } + if (RDKit::SubstructMatch(mol, *pats.bit_73, match, true)) { + fp.setBit(73); + } + if (RDKit::SubstructMatch(mol, *pats.bit_74, match, true)) { + fp.setBit(74); + } + if (RDKit::SubstructMatch(mol, *pats.bit_75, match, true)) { + fp.setBit(75); + } + if (RDKit::SubstructMatch(mol, *pats.bit_76, match, true)) { + fp.setBit(76); + } + if (RDKit::SubstructMatch(mol, *pats.bit_77, match, true)) { + fp.setBit(77); + } + if (RDKit::SubstructMatch(mol, *pats.bit_78, match, true)) { + fp.setBit(78); + } + if (RDKit::SubstructMatch(mol, *pats.bit_79, match, true)) { + fp.setBit(79); + } + if (RDKit::SubstructMatch(mol, *pats.bit_80, match, true)) { + fp.setBit(80); + } + if (RDKit::SubstructMatch(mol, *pats.bit_81, match, true)) { + fp.setBit(81); + } + if (RDKit::SubstructMatch(mol, *pats.bit_82, match, true)) { + fp.setBit(82); + } + if (RDKit::SubstructMatch(mol, *pats.bit_83, match, true)) { + fp.setBit(83); + } + if (RDKit::SubstructMatch(mol, *pats.bit_84, match, true)) { + fp.setBit(84); + } + if (RDKit::SubstructMatch(mol, *pats.bit_85, match, true)) { + fp.setBit(85); + } + if (RDKit::SubstructMatch(mol, *pats.bit_86, match, true)) { + fp.setBit(86); + } + if (RDKit::SubstructMatch(mol, *pats.bit_87, match, true)) { + fp.setBit(87); + } + if (RDKit::SubstructMatch(mol, *pats.bit_89, match, true)) { + fp.setBit(89); + } + if (RDKit::SubstructMatch(mol, *pats.bit_90, match, true)) { + fp.setBit(90); + } + if (RDKit::SubstructMatch(mol, *pats.bit_91, match, true)) { + fp.setBit(91); + } + if (RDKit::SubstructMatch(mol, *pats.bit_92, match, true)) { + fp.setBit(92); + } + if (RDKit::SubstructMatch(mol, *pats.bit_93, match, true)) { + fp.setBit(93); + } + if (RDKit::SubstructMatch(mol, *pats.bit_94, match, true)) { + fp.setBit(94); + } + if (RDKit::SubstructMatch(mol, *pats.bit_95, match, true)) { + fp.setBit(95); + } + if (RDKit::SubstructMatch(mol, *pats.bit_96, match, true)) { + fp.setBit(96); + } + if (RDKit::SubstructMatch(mol, *pats.bit_97, match, true)) { + fp.setBit(97); + } + if (RDKit::SubstructMatch(mol, *pats.bit_98, match, true)) { + fp.setBit(98); + } + if (RDKit::SubstructMatch(mol, *pats.bit_99, match, true)) { + fp.setBit(99); + } + if (RDKit::SubstructMatch(mol, *pats.bit_100, match, true)) { + fp.setBit(100); + } + if (RDKit::SubstructMatch(mol, *pats.bit_101, match, true)) { + fp.setBit(101); + } + if (RDKit::SubstructMatch(mol, *pats.bit_102, match, true)) { + fp.setBit(102); + } + if (RDKit::SubstructMatch(mol, *pats.bit_104, match, true)) { + fp.setBit(104); + } + if (RDKit::SubstructMatch(mol, *pats.bit_105, match, true)) { + fp.setBit(105); + } + if (RDKit::SubstructMatch(mol, *pats.bit_106, match, true)) { + fp.setBit(106); + } + if (RDKit::SubstructMatch(mol, *pats.bit_107, match, true)) { + fp.setBit(107); + } + if (RDKit::SubstructMatch(mol, *pats.bit_108, match, true)) { + fp.setBit(108); + } + if (RDKit::SubstructMatch(mol, *pats.bit_109, match, true)) { + fp.setBit(109); + } + if (RDKit::SubstructMatch(mol, *pats.bit_110, match, true)) { + fp.setBit(110); + } + if (RDKit::SubstructMatch(mol, *pats.bit_111, match, true)) { + fp.setBit(111); + } + if (RDKit::SubstructMatch(mol, *pats.bit_112, match, true)) { + fp.setBit(112); + } + if (RDKit::SubstructMatch(mol, *pats.bit_113, match, true)) { + fp.setBit(113); + } + if (RDKit::SubstructMatch(mol, *pats.bit_114, match, true)) { + fp.setBit(114); + } + if (RDKit::SubstructMatch(mol, *pats.bit_115, match, true)) { + fp.setBit(115); + } + if (RDKit::SubstructMatch(mol, *pats.bit_116, match, true)) { + fp.setBit(116); + } + if (RDKit::SubstructMatch(mol, *pats.bit_117, match, true)) { + fp.setBit(117); + } + if (RDKit::SubstructMatch(mol, *pats.bit_118, matches, true, true) > 1) { fp.setBit(118); - if (RDKit::SubstructMatch(mol, *pats.bit_119, match, true)) fp.setBit(119); - if (RDKit::SubstructMatch(mol, *pats.bit_120, matches, true, true) > 1) + } + if (RDKit::SubstructMatch(mol, *pats.bit_119, match, true)) { + fp.setBit(119); + } + if (RDKit::SubstructMatch(mol, *pats.bit_120, matches, true, true) > 1) { fp.setBit(120); - if (RDKit::SubstructMatch(mol, *pats.bit_121, match, true)) fp.setBit(121); - if (RDKit::SubstructMatch(mol, *pats.bit_122, match, true)) fp.setBit(122); - if (RDKit::SubstructMatch(mol, *pats.bit_123, match, true)) fp.setBit(123); + } + if (RDKit::SubstructMatch(mol, *pats.bit_121, match, true)) { + fp.setBit(121); + } + if (RDKit::SubstructMatch(mol, *pats.bit_122, match, true)) { + fp.setBit(122); + } + if (RDKit::SubstructMatch(mol, *pats.bit_123, match, true)) { + fp.setBit(123); + } count = RDKit::SubstructMatch(mol, *pats.bit_124, matches, true, true); - if (count > 0) fp.setBit(124); - if (count > 1) fp.setBit(130); - if (RDKit::SubstructMatch(mol, *pats.bit_126, match, true)) fp.setBit(126); + if (count > 0) { + fp.setBit(124); + } + if (count > 1) { + fp.setBit(130); + } + if (RDKit::SubstructMatch(mol, *pats.bit_126, match, true)) { + fp.setBit(126); + } count = RDKit::SubstructMatch(mol, *pats.bit_127, matches, true, true); - if (count > 1) fp.setBit(127); - if (count > 0) fp.setBit(143); - if (RDKit::SubstructMatch(mol, *pats.bit_128, match, true)) fp.setBit(128); - if (RDKit::SubstructMatch(mol, *pats.bit_129, match, true)) fp.setBit(129); - if (RDKit::SubstructMatch(mol, *pats.bit_131, matches, true, true) > 1) + if (count > 1) { + fp.setBit(127); + } + if (count > 0) { + fp.setBit(143); + } + if (RDKit::SubstructMatch(mol, *pats.bit_128, match, true)) { + fp.setBit(128); + } + if (RDKit::SubstructMatch(mol, *pats.bit_129, match, true)) { + fp.setBit(129); + } + if (RDKit::SubstructMatch(mol, *pats.bit_131, matches, true, true) > 1) { fp.setBit(131); - if (RDKit::SubstructMatch(mol, *pats.bit_132, match, true)) fp.setBit(132); - if (RDKit::SubstructMatch(mol, *pats.bit_133, match, true)) fp.setBit(133); - if (RDKit::SubstructMatch(mol, *pats.bit_135, match, true)) fp.setBit(135); - if (RDKit::SubstructMatch(mol, *pats.bit_136, matches, true, true) > 1) + } + if (RDKit::SubstructMatch(mol, *pats.bit_132, match, true)) { + fp.setBit(132); + } + if (RDKit::SubstructMatch(mol, *pats.bit_133, match, true)) { + fp.setBit(133); + } + if (RDKit::SubstructMatch(mol, *pats.bit_135, match, true)) { + fp.setBit(135); + } + if (RDKit::SubstructMatch(mol, *pats.bit_136, matches, true, true) > 1) { fp.setBit(136); - if (RDKit::SubstructMatch(mol, *pats.bit_137, match, true)) fp.setBit(137); + } + if (RDKit::SubstructMatch(mol, *pats.bit_137, match, true)) { + fp.setBit(137); + } count = RDKit::SubstructMatch(mol, *pats.bit_138, matches, true, true); - if (count > 1) fp.setBit(138); - if (count > 0) fp.setBit(153); - if (RDKit::SubstructMatch(mol, *pats.bit_139, match, true)) fp.setBit(139); + if (count > 1) { + fp.setBit(138); + } + if (count > 0) { + fp.setBit(153); + } + if (RDKit::SubstructMatch(mol, *pats.bit_139, match, true)) { + fp.setBit(139); + } count = RDKit::SubstructMatch(mol, *pats.bit_140, matches, true, true); - if (count > 3) fp.setBit(140); - if (count > 2) fp.setBit(146); - if (count > 1) fp.setBit(159); - if (count > 0) fp.setBit(164); - if (RDKit::SubstructMatch(mol, *pats.bit_141, matches, true, true) > 2) + if (count > 3) { + fp.setBit(140); + } + if (count > 2) { + fp.setBit(146); + } + if (count > 1) { + fp.setBit(159); + } + if (count > 0) { + fp.setBit(164); + } + if (RDKit::SubstructMatch(mol, *pats.bit_141, matches, true, true) > 2) { fp.setBit(141); + } count = RDKit::SubstructMatch(mol, *pats.bit_142, matches, true, true); - if (count > 1) fp.setBit(142); - if (count > 0) fp.setBit(161); - if (RDKit::SubstructMatch(mol, *pats.bit_144, match, true)) fp.setBit(144); + if (count > 1) { + fp.setBit(142); + } + if (count > 0) { + fp.setBit(161); + } + if (RDKit::SubstructMatch(mol, *pats.bit_144, match, true)) { + fp.setBit(144); + } count = RDKit::SubstructMatch(mol, *pats.bit_145, matches, true, true); - if (count > 1) fp.setBit(145); - if (count > 0) fp.setBit(163); - if (RDKit::SubstructMatch(mol, *pats.bit_147, match, true)) fp.setBit(147); - if (RDKit::SubstructMatch(mol, *pats.bit_148, match, true)) fp.setBit(148); + if (count > 1) { + fp.setBit(145); + } + if (count > 0) { + fp.setBit(163); + } + if (RDKit::SubstructMatch(mol, *pats.bit_147, match, true)) { + fp.setBit(147); + } + if (RDKit::SubstructMatch(mol, *pats.bit_148, match, true)) { + fp.setBit(148); + } count = RDKit::SubstructMatch(mol, *pats.bit_149, matches, true, true); - if (count > 1) fp.setBit(149); - if (count > 0) fp.setBit(160); - if (RDKit::SubstructMatch(mol, *pats.bit_150, match, true)) fp.setBit(150); - if (RDKit::SubstructMatch(mol, *pats.bit_151, match, true)) fp.setBit(151); - if (RDKit::SubstructMatch(mol, *pats.bit_152, match, true)) fp.setBit(152); - if (RDKit::SubstructMatch(mol, *pats.bit_154, match, true)) fp.setBit(154); - if (RDKit::SubstructMatch(mol, *pats.bit_155, match, true)) fp.setBit(155); - if (RDKit::SubstructMatch(mol, *pats.bit_156, match, true)) fp.setBit(156); - if (RDKit::SubstructMatch(mol, *pats.bit_157, match, true)) fp.setBit(157); - if (RDKit::SubstructMatch(mol, *pats.bit_158, match, true)) fp.setBit(158); - if (RDKit::SubstructMatch(mol, *pats.bit_162, match, true)) fp.setBit(162); - if (RDKit::SubstructMatch(mol, *pats.bit_165, match, true)) fp.setBit(165); + if (count > 1) { + fp.setBit(149); + } + if (count > 0) { + fp.setBit(160); + } + if (RDKit::SubstructMatch(mol, *pats.bit_150, match, true)) { + fp.setBit(150); + } + if (RDKit::SubstructMatch(mol, *pats.bit_151, match, true)) { + fp.setBit(151); + } + if (RDKit::SubstructMatch(mol, *pats.bit_152, match, true)) { + fp.setBit(152); + } + if (RDKit::SubstructMatch(mol, *pats.bit_154, match, true)) { + fp.setBit(154); + } + if (RDKit::SubstructMatch(mol, *pats.bit_155, match, true)) { + fp.setBit(155); + } + if (RDKit::SubstructMatch(mol, *pats.bit_156, match, true)) { + fp.setBit(156); + } + if (RDKit::SubstructMatch(mol, *pats.bit_157, match, true)) { + fp.setBit(157); + } + if (RDKit::SubstructMatch(mol, *pats.bit_158, match, true)) { + fp.setBit(158); + } + if (RDKit::SubstructMatch(mol, *pats.bit_162, match, true)) { + fp.setBit(162); + } + if (RDKit::SubstructMatch(mol, *pats.bit_165, match, true)) { + fp.setBit(165); + } /* BIT 125 */ RDKit::RingInfo *info = mol.getRingInfo(); @@ -625,23 +913,27 @@ void GenerateFP(const RDKit::ROMol &mol, ExplicitBitVect &fp) { bool isArom = true; const std::vector *ring = &info->bondRings()[i]; std::vector::const_iterator iter; - for (iter = ring->begin(); iter != ring->end(); ++iter) + for (iter = ring->begin(); iter != ring->end(); ++iter) { if (!mol.getBondWithIdx(*iter)->getIsAromatic()) { isArom = false; break; } + } if (isArom) { if (nArom) { fp.setBit(125); break; - } else + } else { nArom++; + } } } /* BIT 166 */ std::vector mapping; - if (RDKit::MolOps::getMolFrags(mol, mapping) > 1) fp.setBit(166); + if (RDKit::MolOps::getMolFrags(mol, mapping) > 1) { + fp.setBit(166); + } } } // namespace diff --git a/Code/GraphMol/Fingerprints/MorganFingerprints.cpp b/Code/GraphMol/Fingerprints/MorganFingerprints.cpp index ddbfba798..b48ea851d 100644 --- a/Code/GraphMol/Fingerprints/MorganFingerprints.cpp +++ b/Code/GraphMol/Fingerprints/MorganFingerprints.cpp @@ -117,8 +117,9 @@ void calcFingerprint(const ROMol &mol, unsigned int radius, fromAtoms->end()) { if (!onlyNonzeroInvariants || (*invariants)[i]) { uint32_t bit = updateElement(res, (*invariants)[i], useCounts); - if (atomsSettingBits) + if (atomsSettingBits) { (*atomsSettingBits)[bit].push_back(std::make_pair(i, 0)); + } } } } @@ -144,10 +145,11 @@ void calcFingerprint(const ROMol &mol, unsigned int radius, if (onlyNonzeroInvariants) { std::vector> ordering; for (unsigned int i = 0; i < nAtoms; ++i) { - if (!(*invariants)[i]) + if (!(*invariants)[i]) { ordering.push_back(std::make_pair(1, i)); - else + } else { ordering.push_back(std::make_pair(0, i)); + } } std::sort(ordering.begin(), ordering.end()); for (unsigned int i = 0; i < nAtoms; ++i) { @@ -262,9 +264,10 @@ void calcFingerprint(const ROMol &mol, unsigned int radius, if (!onlyNonzeroInvariants || invariantCpy[iter->get<2>()]) { if (includeAtoms[iter->get<2>()]) { uint32_t bit = updateElement(res, iter->get<1>(), useCounts); - if (atomsSettingBits) + if (atomsSettingBits) { (*atomsSettingBits)[bit].push_back( std::make_pair(iter->get<2>(), layer + 1)); + } } if (!fromAtoms || std::find(fromAtoms->begin(), fromAtoms->end(), iter->get<2>()) != fromAtoms->end()) { @@ -289,7 +292,9 @@ void calcFingerprint(const ROMol &mol, unsigned int radius, atomNeighborhoods = roundAtomNeighborhoods; } - if (owner) delete invariants; + if (owner) { + delete invariants; + } } SparseIntVect *getFingerprint(const ROMol &mol, unsigned int radius, diff --git a/Code/GraphMol/Fingerprints/MorganGenerator.cpp b/Code/GraphMol/Fingerprints/MorganGenerator.cpp index e325dd25d..9451d589a 100644 --- a/Code/GraphMol/Fingerprints/MorganGenerator.cpp +++ b/Code/GraphMol/Fingerprints/MorganGenerator.cpp @@ -172,7 +172,7 @@ MorganEnvGenerator::getEnvironments( unsigned int nAtoms = mol.getNumAtoms(); std::vector *> result = std::vector *>(); - MorganArguments *morganArguments = + auto *morganArguments = dynamic_cast *>(arguments); std::vector currentInvariants(atomInvariants->size()); @@ -203,10 +203,11 @@ MorganEnvGenerator::getEnvironments( if (morganArguments->df_onlyNonzeroInvariants) { std::vector> ordering; for (unsigned int i = 0; i < nAtoms; ++i) { - if (!currentInvariants[i]) + if (!currentInvariants[i]) { ordering.push_back(std::make_pair(1, i)); - else + } else { ordering.push_back(std::make_pair(0, i)); + } } std::sort(ordering.begin(), ordering.end()); for (unsigned int i = 0; i < nAtoms; ++i) { @@ -265,7 +266,7 @@ MorganEnvGenerator::getEnvironments( unsigned int oIdx = bond->getOtherAtomIdx(atomIdx); roundAtomNeighborhoods[atomIdx] |= atomNeighborhoods[oIdx]; - int32_t bt = static_cast((*bondInvariants)[bond->getIdx()]); + auto bt = static_cast((*bondInvariants)[bond->getIdx()]); neighborhoodInvariants.push_back( std::make_pair(bt, currentInvariants[oIdx])); diff --git a/Code/GraphMol/Fingerprints/PatternFingerprints.cpp b/Code/GraphMol/Fingerprints/PatternFingerprints.cpp index a4c9af977..bb0d541aa 100644 --- a/Code/GraphMol/Fingerprints/PatternFingerprints.cpp +++ b/Code/GraphMol/Fingerprints/PatternFingerprints.cpp @@ -107,7 +107,9 @@ void getAtomNumbers(const Atom *a, std::vector &atomNums) { return; } // negated things are always complex: - if (a->getQuery()->getNegation()) return; + if (a->getQuery()->getNegation()) { + return; + } std::string descr = a->getQuery()->getDescription(); if (descr == "AtomAtomicNum") { atomNums.push_back( @@ -155,13 +157,19 @@ void getAtomNumbers(const Atom *a, std::vector &atomNums) { namespace { bool isPatternComplexQuery(const Bond *b) { - if (!b->hasQuery()) return false; + if (!b->hasQuery()) { + return false; + } // negated things are always complex: - if (b->getQuery()->getNegation()) return true; + if (b->getQuery()->getNegation()) { + return true; + } std::string descr = b->getQuery()->getDescription(); // std::cerr<<" !!!!!! "<getIdx()<<" // "<getBeginAtomIdx()<<"-"<getEndAtomIdx()<<" "<getAtomicNum()); amap[p.first] = p.second; } - if (isQuery) continue; + if (isQuery) { + continue; + } ROMol::EDGE_ITER firstB, lastB; boost::tie(firstB, lastB) = patt->getEdges(); #ifdef VERBOSE_FINGERPRINTING diff --git a/Code/GraphMol/Fingerprints/RDKitFPGenerator.cpp b/Code/GraphMol/Fingerprints/RDKitFPGenerator.cpp index eb8e31c6d..eac4a88ea 100644 --- a/Code/GraphMol/Fingerprints/RDKitFPGenerator.cpp +++ b/Code/GraphMol/Fingerprints/RDKitFPGenerator.cpp @@ -38,7 +38,7 @@ namespace RDKitFP { std::vector *RDKitFPAtomInvGenerator::getAtomInvariants( const ROMol &mol) const { - std::vector *result = new std::vector(); + auto *result = new std::vector(); result->reserve(mol.getNumAtoms()); for (ROMol::ConstAtomIterator atomIt = mol.beginAtoms(); atomIt != mol.endAtoms(); ++atomIt) { @@ -101,9 +101,9 @@ OutputType RDKitFPAtomEnv::getBitId( } template -RDKitFPAtomEnv::RDKitFPAtomEnv( - const OutputType bitId, const boost::dynamic_bitset<> &atomsInPath) - : d_bitId(bitId), d_atomsInPath(atomsInPath) {} +RDKitFPAtomEnv::RDKitFPAtomEnv(const OutputType bitId, + boost::dynamic_bitset<> atomsInPath) + : d_bitId(bitId), d_atomsInPath(std::move(atomsInPath)) {} template std::string RDKitFPEnvGenerator::infoString() const { @@ -125,7 +125,7 @@ RDKitFPEnvGenerator::getEnvironments( PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(), "bad atomInvariants size"); - RDKitFPArguments *rDKitFPArguments = + auto *rDKitFPArguments = dynamic_cast *>(arguments); std::vector *> result; diff --git a/Code/GraphMol/Fingerprints/RDKitFPGenerator.h b/Code/GraphMol/Fingerprints/RDKitFPGenerator.h index 3c98ff23b..2eccfde30 100644 --- a/Code/GraphMol/Fingerprints/RDKitFPGenerator.h +++ b/Code/GraphMol/Fingerprints/RDKitFPGenerator.h @@ -86,8 +86,7 @@ class RDKIT_FINGERPRINTS_EXPORT RDKitFPAtomEnv \param atomsInPath holds atoms in this environment to set additional output */ - RDKitFPAtomEnv(const OutputType bitId, - const boost::dynamic_bitset<> &atomsInPath); + RDKitFPAtomEnv(const OutputType bitId, boost::dynamic_bitset<> atomsInPath); }; template diff --git a/Code/GraphMol/Fingerprints/TopologicalTorsionGenerator.cpp b/Code/GraphMol/Fingerprints/TopologicalTorsionGenerator.cpp index 4d726599b..1bdbbf70b 100644 --- a/Code/GraphMol/Fingerprints/TopologicalTorsionGenerator.cpp +++ b/Code/GraphMol/Fingerprints/TopologicalTorsionGenerator.cpp @@ -66,7 +66,7 @@ TopologicalTorsionEnvGenerator::getEnvironments( const std::vector *atomInvariants, const std::vector *, // bondInvariants const bool hashResults) const { - TopologicalTorsionArguments *topologicalTorsionArguments = + auto *topologicalTorsionArguments = dynamic_cast *>(arguments); std::vector *> result = @@ -157,13 +157,10 @@ FingerprintGenerator *getTopologicalTorsionGenerator( AtomInvariantsGenerator *atomInvariantsGenerator, const bool countSimulation, const std::vector countBounds, const std::uint32_t fpSize, const bool ownsAtomInvGen) { - TopologicalTorsionEnvGenerator *envGenerator = - new TopologicalTorsionEnvGenerator(); + auto *envGenerator = new TopologicalTorsionEnvGenerator(); - TopologicalTorsionArguments *arguments = - new TopologicalTorsionArguments( - includeChirality, torsionAtomCount, countSimulation, countBounds, - fpSize); + auto *arguments = new TopologicalTorsionArguments( + includeChirality, torsionAtomCount, countSimulation, countBounds, fpSize); bool ownsAtomInvGenerator = ownsAtomInvGen; if (!atomInvariantsGenerator) { diff --git a/Code/GraphMol/Fingerprints/Wrap/FingerprintGeneratorWrapper.cpp b/Code/GraphMol/Fingerprints/Wrap/FingerprintGeneratorWrapper.cpp index 503ed4bca..ce622db90 100644 --- a/Code/GraphMol/Fingerprints/Wrap/FingerprintGeneratorWrapper.cpp +++ b/Code/GraphMol/Fingerprints/Wrap/FingerprintGeneratorWrapper.cpp @@ -201,8 +201,8 @@ python::list getSparseCountFPBulkPy(python::list &py_molVect, FPType fPType) { auto tempResult = getSparseCountFPBulk(molVect, fPType); python::list result; - for (auto it = tempResult->begin(); it != tempResult->end(); ++it) { - result.append((boost::shared_ptr>)*it); + for (auto &it : *tempResult) { + result.append((boost::shared_ptr>)it); } delete tempResult; return result; @@ -214,10 +214,10 @@ python::list getSparseFPBulkPy(python::list &py_molVect, FPType fpType) { auto tempResult = getSparseFPBulk(molVect, fpType); python::list result; - for (auto it = tempResult->begin(); it != tempResult->end(); ++it) { + for (auto &it : *tempResult) { // todo every other bulk method casts results to boost::shared_ptr, except // this one. It should also be boost::shared_ptr - result.append(*it); + result.append(it); } delete tempResult; return result; @@ -229,8 +229,8 @@ python::list getCountFPBulkPy(python::list &py_molVect, FPType fPType) { auto tempResult = getCountFPBulk(molVect, fPType); python::list result; - for (auto it = tempResult->begin(); it != tempResult->end(); ++it) { - result.append((boost::shared_ptr>)*it); + for (auto &it : *tempResult) { + result.append((boost::shared_ptr>)it); } delete tempResult; return result; @@ -242,8 +242,8 @@ python::list getFPBulkPy(python::list &py_molVect, FPType fPType) { auto tempResult = getFPBulk(molVect, fPType); python::list result; - for (auto it = tempResult->begin(); it != tempResult->end(); ++it) { - result.append((boost::shared_ptr)*it); + for (auto &it : *tempResult) { + result.append((boost::shared_ptr)it); } delete tempResult; return result; diff --git a/Code/GraphMol/Fingerprints/test1.cpp b/Code/GraphMol/Fingerprints/test1.cpp index 6658c8cd4..883dcfd66 100644 --- a/Code/GraphMol/Fingerprints/test1.cpp +++ b/Code/GraphMol/Fingerprints/test1.cpp @@ -615,7 +615,9 @@ void test2Layers() { atomCounts.clear(); atomCounts.resize(m1->getNumAtoms()); - for (unsigned int i = 0; i < m1->getNumAtoms(); ++i) atomCounts[i] = 0; + for (unsigned int i = 0; i < m1->getNumAtoms(); ++i) { + atomCounts[i] = 0; + } delete fp2; fp2 = LayeredFingerprintMol(*m1, 0xFFFFFFFF, 1, 7, 2048, &atomCounts); @@ -649,7 +651,9 @@ void test2Layers() { atomCounts.clear(); atomCounts.resize(m1->getNumAtoms()); - for (unsigned int i = 0; i < m1->getNumAtoms(); ++i) atomCounts[i] = 0; + for (unsigned int i = 0; i < m1->getNumAtoms(); ++i) { + atomCounts[i] = 0; + } ExplicitBitVect *fp3 = LayeredFingerprintMol(*m1, 0xFFFFFFFF, 1, 7, 2048, &atomCounts, fp2); @@ -2941,11 +2945,14 @@ void runblock(const std::vector &mols, unsigned int count, unsigned int nReps) { for (unsigned int j = 0; j < nReps; j++) { for (unsigned int i = 0; i < mols.size(); ++i) { - if (i % count != idx) continue; + if (i % count != idx) { + continue; + } ROMol *mol = mols[i]; ExplicitBitVect *lbv = PatternFingerprintMol(*mol, 2048); - if (referenceData.size() && referenceData[i]) + if (referenceData.size() && referenceData[i]) { TEST_ASSERT((*lbv) == (*referenceData[i])); + } delete lbv; } } @@ -2971,7 +2978,9 @@ void testMultithreadedPatternFP() { } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } mols.push_back(mol); } std::vector> tg; diff --git a/Code/GraphMol/Fingerprints/testFingerprintGenerators.cpp b/Code/GraphMol/Fingerprints/testFingerprintGenerators.cpp index 3ad52bef5..d6d2b7050 100644 --- a/Code/GraphMol/Fingerprints/testFingerprintGenerators.cpp +++ b/Code/GraphMol/Fingerprints/testFingerprintGenerators.cpp @@ -180,9 +180,8 @@ void testAtomPairOld() { fpu = atomPairGenerator->getSparseCountFingerprint(*mol); fp2 = new SparseIntVect(fpu->size()); std::map nz = fpu->getNonzeroElements(); - for (std::map::iterator it = nz.begin(); - it != nz.end(); it++) { - fp2->setVal(static_cast(it->first), it->second); + for (auto &it : nz) { + fp2->setVal(static_cast(it.first), it.second); } TEST_ASSERT(DiceSimilarity(*fp1, *fp2) == 1.0); @@ -960,8 +959,7 @@ void testMorganFPFeatureInvs() { ROMol *mol; mol = SmilesToMol("Cc1ccccc1"); TEST_ASSERT(mol); - MorganFingerprint::MorganFeatureAtomInvGenerator *invGen = - new MorganFingerprint::MorganFeatureAtomInvGenerator(); + auto *invGen = new MorganFingerprint::MorganFeatureAtomInvGenerator(); std::vector *invars = invGen->getAtomInvariants(*mol); TEST_ASSERT((*invars)[0] == 0); TEST_ASSERT((*invars)[1] != 0); @@ -978,8 +976,7 @@ void testMorganFPFeatureInvs() { ROMol *mol; mol = SmilesToMol("FCCCl"); TEST_ASSERT(mol); - MorganFingerprint::MorganFeatureAtomInvGenerator *invGen = - new MorganFingerprint::MorganFeatureAtomInvGenerator(); + auto *invGen = new MorganFingerprint::MorganFeatureAtomInvGenerator(); std::vector *invars = invGen->getAtomInvariants(*mol); TEST_ASSERT((*invars)[1] == (*invars)[2]); TEST_ASSERT((*invars)[1] == 0); @@ -1001,7 +998,7 @@ void testMorganFPFeatureInvs() { patterns[0] = static_cast(p); p = SmartsToMol("[a]"); patterns[1] = static_cast(p); - MorganFingerprint::MorganFeatureAtomInvGenerator *invGen = + auto *invGen = new MorganFingerprint::MorganFeatureAtomInvGenerator(&patterns); std::vector *invars = invGen->getAtomInvariants(*mol); @@ -1463,8 +1460,8 @@ void testRDKitFP() { // the same std::map nz = fpTemp->getNonzeroElements(); fpOld = new SparseIntVect(fp->getLength()); - for (auto it = nz.begin(); it != nz.end(); it++) { - fpOld->setVal(it->first, it->second); + for (auto &it : nz) { + fpOld->setVal(it.first, it.second); } TEST_ASSERT(DiceSimilarity(*fp, *fpOld) == 1.0); @@ -1595,9 +1592,8 @@ void testTopologicalTorsionFPOld() { fpOld = new SparseIntVect(fp->getLength()); std::map nz = fpSigned->getNonzeroElements(); - for (std::map::iterator it = nz.begin(); it != nz.end(); - it++) { - fpOld->setVal(static_cast(it->first), it->second); + for (auto &it : nz) { + fpOld->setVal(static_cast(it.first), it.second); } TEST_ASSERT(DiceSimilarity(*fp, *fpOld) == 1.0); diff --git a/Code/GraphMol/ForceFieldHelpers/MMFF/AtomTyper.cpp b/Code/GraphMol/ForceFieldHelpers/MMFF/AtomTyper.cpp index 6347b71a8..4d47285a1 100644 --- a/Code/GraphMol/ForceFieldHelpers/MMFF/AtomTyper.cpp +++ b/Code/GraphMol/ForceFieldHelpers/MMFF/AtomTyper.cpp @@ -147,19 +147,25 @@ RingMembershipSize::RingMembershipSize(const ROMol &mol) { unsigned int ringSize = atomRings[ringIdx].size(); std::uint32_t ringIdxWithAromaticFlag = ringIdx; bool ringIsAromatic = isRingAromatic(mol, atomRings[ringIdx]); - if (ringIsAromatic) ringIdxWithAromaticFlag |= IS_AROMATIC_BIT; + if (ringIsAromatic) { + ringIdxWithAromaticFlag |= IS_AROMATIC_BIT; + } auto it = d_ringSizeMembershipMap.find(ringSize); - if (it == d_ringSizeMembershipMap.end()) + if (it == d_ringSizeMembershipMap.end()) { it = d_ringSizeMembershipMap .insert(std::make_pair(ringSize, RingMembershipMap())) .first; + } for (int atomIdxIt : atomRings[ringIdx]) { auto it2 = it->second.find(atomIdxIt); - if (it2 == it->second.end()) + if (it2 == it->second.end()) { it2 = it->second.insert(std::make_pair(atomIdxIt, RingMembership())) .first; + } it2->second.getRingIdxSet().insert(ringIdxWithAromaticFlag); - if (ringIsAromatic) it2->second.setIsInAromaticRing(true); + if (ringIsAromatic) { + it2->second.setIsInAromaticRing(true); + } } } } @@ -172,7 +178,9 @@ bool RingMembershipSize::isAtomInAromaticRingOfSize( if (isAromatic) { auto it2 = it->second.find(atom->getIdx()); isAromatic = (it2 != it->second.end()); - if (isAromatic) isAromatic = it2->second.getIsInAromaticRing(); + if (isAromatic) { + isAromatic = it2->second.getIsInAromaticRing(); + } } return isAromatic; @@ -195,8 +203,9 @@ bool RingMembershipSize::areAtomsInSameAromaticRing(const Atom *atom1, std::back_inserter(intersectVect)); for (std::vector::const_iterator ivIt = intersectVect.begin(); - !areInSameAromaticRing && (ivIt != intersectVect.end()); ++ivIt) + !areInSameAromaticRing && (ivIt != intersectVect.end()); ++ivIt) { areInSameAromaticRing = *ivIt & IS_AROMATIC_BIT; + } } } @@ -220,7 +229,9 @@ bool RingMembershipSize::areAtomsInSameRingOfSize(const unsigned int ringSize, areInSameRingOfSize = false; unsigned int idx2 = va_arg(atoms, const Atom *)->getIdx(); auto it2 = it->second.find(idx2); - if (it2 == it->second.end()) break; + if (it2 == it->second.end()) { + break; + } std::set intersect; std::set_intersection(commonSet.begin(), commonSet.end(), it2->second.getRingIdxSet().begin(), @@ -294,9 +305,10 @@ bool isAromaticAtomType(const unsigned int atomType) { bool isRingAromatic(const ROMol &mol, const INT_VECT &ringIndxVect) { bool isAromatic = true; - for (unsigned int i = 0; isAromatic && (i < ringIndxVect.size() - 1); ++i) + for (unsigned int i = 0; isAromatic && (i < ringIndxVect.size() - 1); ++i) { isAromatic = (mol.getBondBetweenAtoms(ringIndxVect[i], ringIndxVect[i + 1]) ->getBondType() == Bond::AROMATIC); + } return isAromatic; } @@ -3048,7 +3060,7 @@ MMFFMolProperties::getMMFFTorsionEmpiricalRuleParams(const ROMol &mol, double W[2] = {0.0, 0.0}; double beta = 0.0; double pi_jk = 0.0; - const double N_jk = (double)((jMMFFProp->crd - 1) * (kMMFFProp->crd - 1)); + const auto N_jk = (double)((jMMFFProp->crd - 1) * (kMMFFProp->crd - 1)); int atomicNum[2] = {mol.getAtomWithIdx(idx2)->getAtomicNum(), mol.getAtomWithIdx(idx3)->getAtomicNum()}; @@ -3580,7 +3592,7 @@ void MMFFMolProperties::computeMMFFCharges(const ROMol &mol) { const Atom *atom = mol.getAtomWithIdx(idx); atomType = this->getMMFFAtomType(idx); double q0 = this->getMMFFFormalCharge(idx); - double M = (double)((*mmffProp)(atomType)->crd); + auto M = (double)((*mmffProp)(atomType)->crd); double v = (*mmffPBCI)(atomType)->fcadj; double sumFormalCharge = 0.0; double sumPartialCharge = 0.0; diff --git a/Code/GraphMol/ForceFieldHelpers/MMFF/Builder.cpp b/Code/GraphMol/ForceFieldHelpers/MMFF/Builder.cpp index 1f327c503..4f86bc4b4 100644 --- a/Code/GraphMol/ForceFieldHelpers/MMFF/Builder.cpp +++ b/Code/GraphMol/ForceFieldHelpers/MMFF/Builder.cpp @@ -99,7 +99,9 @@ void addBonds(const ROMol &mol, MMFFMolProperties *mmffMolProperties, } unsigned int twoBitCellPos(unsigned int nAtoms, int i, int j) { - if (j < i) std::swap(i, j); + if (j < i) { + std::swap(i, j); + } return i * (nAtoms - 1) + i * (1 - i) / 2 + j; } @@ -659,7 +661,9 @@ void addTorsions(const ROMol &mol, MMFFMolProperties *mmffMolProperties, : SmartsToMol(torsionBondSmarts); TEST_ASSERT(query); unsigned int nHits = SubstructMatch(mol, *query, matchVect); - if (query != defaultQuery) delete query; + if (query != defaultQuery) { + delete query; + } for (unsigned int i = 0; i < nHits; ++i) { MatchVectType match = matchVect[i]; @@ -896,8 +900,9 @@ void addEle(const ROMol &mol, int confId, MMFFMolProperties *mmffMolProperties, bool is1_4 = (cell == RELATION_1_4); if (cell >= RELATION_1_4) { if (isDoubleZero(mmffMolProperties->getMMFFPartialCharge(i)) || - isDoubleZero(mmffMolProperties->getMMFFPartialCharge(j))) + isDoubleZero(mmffMolProperties->getMMFFPartialCharge(j))) { continue; + } double dist = (conf.getAtomPos(i) - conf.getAtomPos(j)).length(); if (dist > nonBondedThresh) { continue; diff --git a/Code/GraphMol/ForceFieldHelpers/MMFF/testMMFFHelpers.cpp b/Code/GraphMol/ForceFieldHelpers/MMFF/testMMFFHelpers.cpp index fa64c9297..f4350b7a4 100644 --- a/Code/GraphMol/ForceFieldHelpers/MMFF/testMMFFHelpers.cpp +++ b/Code/GraphMol/ForceFieldHelpers/MMFF/testMMFFHelpers.cpp @@ -489,10 +489,12 @@ void testCalcEnergyPassedCoords() { TEST_ASSERT(field); field->initialize(); size_t l = 3 * field->numPoints(); - double *savedPos = new double[l]; + auto *savedPos = new double[l]; size_t i = 0; for (const auto pptr : field->positions()) { - for (size_t j = 0; j < 3; ++j) savedPos[i++] = (*pptr)[j]; + for (size_t j = 0; j < 3; ++j) { + savedPos[i++] = (*pptr)[j]; + } } TEST_ASSERT(i == l); e1 = field->calcEnergy(); @@ -526,28 +528,36 @@ void testCalcGrad() { TEST_ASSERT(field); field->initialize(); size_t l = 3 * field->numPoints(); - double *savedPos = new double[l]; - double *grad1 = new double[l]; - double *grad2 = new double[l]; + auto *savedPos = new double[l]; + auto *grad1 = new double[l]; + auto *grad2 = new double[l]; size_t i = 0; for (const auto pptr : field->positions()) { - for (size_t j = 0; j < 3; ++j) savedPos[i++] = (*pptr)[j]; + for (size_t j = 0; j < 3; ++j) { + savedPos[i++] = (*pptr)[j]; + } } TEST_ASSERT(i == l); std::memset(grad1, 0, l * sizeof(double)); field->calcGrad(grad1); - for (i = 0; i < l; ++i) TEST_ASSERT(!feq(grad1[i], 0.0, 0.001)); + for (i = 0; i < l; ++i) { + TEST_ASSERT(!feq(grad1[i], 0.0, 0.001)); + } field->minimize(10000, 1.0e-6, 1.0e-3); std::memset(grad2, 0, l * sizeof(double)); field->calcGrad(grad2); - for (i = 0; i < l; ++i) TEST_ASSERT(feq(grad2[i], 0.0, 0.001)); + for (i = 0; i < l; ++i) { + TEST_ASSERT(feq(grad2[i], 0.0, 0.001)); + } field->initialize(); std::memset(grad2, 0, l * sizeof(double)); field->calcGrad(savedPos, grad2); - for (i = 0; i < l; ++i) TEST_ASSERT(feq(grad1[i], grad2[i], 0.001)); + for (i = 0; i < l; ++i) { + TEST_ASSERT(feq(grad1[i], grad2[i], 0.001)); + } delete[] savedPos; delete[] grad1; @@ -863,7 +873,9 @@ void runblock_mmff(const std::vector &mols, unsigned int idx) { for (unsigned int rep = 0; rep < 100; ++rep) { for (unsigned int i = 0; i < mols.size(); ++i) { - if (i % count != idx) continue; + if (i % count != idx) { + continue; + } ROMol *mol = mols[i]; ForceFields::ForceField *field = nullptr; if (!(rep % 20)) { @@ -904,7 +916,9 @@ void testMMFFMultiThread() { } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } mols.push_back(mol); } diff --git a/Code/GraphMol/ForceFieldHelpers/MMFF/testMultiThread.cpp b/Code/GraphMol/ForceFieldHelpers/MMFF/testMultiThread.cpp index 37aa3e7c6..b8631b930 100644 --- a/Code/GraphMol/ForceFieldHelpers/MMFF/testMultiThread.cpp +++ b/Code/GraphMol/ForceFieldHelpers/MMFF/testMultiThread.cpp @@ -34,14 +34,13 @@ using namespace RDKit; #ifdef RDK_TEST_MULTITHREADED namespace { void runblock_mmff(const std::vector &mols) { - for (unsigned int i = 0; i < mols.size(); ++i) { - ROMol *mol = mols[i]; - ForceFields::ForceField *field = MMFF::constructForceField(*mol); - TEST_ASSERT(field); - field->initialize(); - field->minimize(1); - delete field; - } + for (auto mol : mols) { + ForceFields::ForceField *field = MMFF::constructForceField(*mol); + TEST_ASSERT(field); + field->initialize(); + field->minimize(1); + delete field; + } } } // namespace #include @@ -55,17 +54,20 @@ void testMMFFMultiThread() { SDMolSupplier suppl(pathName + "/bulk.sdf"); unsigned int count = 24; std::vector> mols; - for(unsigned int i=0;i()); - + for (unsigned int i = 0; i < count; ++i) { + mols.push_back(std::vector()); + } + while (!suppl.atEnd() && mols.size() < 100) { ROMol *mol = nullptr; try { mol = suppl.next(); for(unsigned int i=0;igetIdx() << std::endl; @@ -69,7 +71,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+5"; break; default: - if (tolerateChargeMismatch) atomKey += "+5"; + if (tolerateChargeMismatch) { + atomKey += "+5"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -88,7 +92,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+6"; break; default: - if (tolerateChargeMismatch) atomKey += "+6"; + if (tolerateChargeMismatch) { + atomKey += "+6"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -101,7 +107,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+2"; break; default: - if (tolerateChargeMismatch) atomKey += "+2"; + if (tolerateChargeMismatch) { + atomKey += "+2"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -113,7 +121,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+3"; break; default: - if (tolerateChargeMismatch) atomKey += "+3"; + if (tolerateChargeMismatch) { + atomKey += "+3"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -125,7 +135,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+3"; break; default: - if (tolerateChargeMismatch) atomKey += "+3"; + if (tolerateChargeMismatch) { + atomKey += "+3"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -137,7 +149,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+2"; break; default: - if (tolerateChargeMismatch) atomKey += "+2"; + if (tolerateChargeMismatch) { + atomKey += "+2"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -149,7 +163,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+2"; break; default: - if (tolerateChargeMismatch) atomKey += "+2"; + if (tolerateChargeMismatch) { + atomKey += "+2"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -161,7 +177,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+3"; break; default: - if (tolerateChargeMismatch) atomKey += "+3"; + if (tolerateChargeMismatch) { + atomKey += "+3"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -173,7 +191,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+3"; break; default: - if (tolerateChargeMismatch) atomKey += "+3"; + if (tolerateChargeMismatch) { + atomKey += "+3"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -185,7 +205,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+2"; break; default: - if (tolerateChargeMismatch) atomKey += "+2"; + if (tolerateChargeMismatch) { + atomKey += "+2"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -197,7 +219,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+2"; break; default: - if (tolerateChargeMismatch) atomKey += "+2"; + if (tolerateChargeMismatch) { + atomKey += "+2"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -209,7 +233,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+3"; break; default: - if (tolerateChargeMismatch) atomKey += "+3"; + if (tolerateChargeMismatch) { + atomKey += "+3"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -221,7 +247,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+3"; break; default: - if (tolerateChargeMismatch) atomKey += "+3"; + if (tolerateChargeMismatch) { + atomKey += "+3"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -233,7 +261,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+3"; break; default: - if (tolerateChargeMismatch) atomKey += "+3"; + if (tolerateChargeMismatch) { + atomKey += "+3"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -245,7 +275,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+2"; break; default: - if (tolerateChargeMismatch) atomKey += "+2"; + if (tolerateChargeMismatch) { + atomKey += "+2"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -259,7 +291,9 @@ void addAtomChargeFlags(const Atom *atom, std::string &atomKey, atomKey += "+3"; break; default: - if (tolerateChargeMismatch) atomKey += "+3"; + if (tolerateChargeMismatch) { + atomKey += "+3"; + } BOOST_LOG(rdErrorLog) << "UFFTYPER: Unrecognized charge state for atom: " << atom->getIdx() << std::endl; @@ -272,7 +306,9 @@ std::string getAtomLabel(const Atom *atom) { PRECONDITION(atom, "bad atom"); int atNum = atom->getAtomicNum(); std::string atomKey = atom->getSymbol(); - if (atomKey.size() == 1) atomKey += '_'; + if (atomKey.size() == 1) { + atomKey += '_'; + } PeriodicTable *table = PeriodicTable::getTable(); // FIX: handle main group/organometallic cases better: @@ -481,8 +517,12 @@ bool getUFFTorsionParams(const ROMol &mol, unsigned int idx1, unsigned int idx2, UFF::Utils::isInGroup6(atNum[1])) { double V2 = 6.8; double V3 = 6.8; - if (atNum[0] == 8) V2 = 2.0; - if (atNum[1] == 8) V3 = 2.0; + if (atNum[0] == 8) { + V2 = 2.0; + } + if (atNum[1] == 8) { + V3 = 2.0; + } uffTorsionParams.V = sqrt(V2 * V3); } } else if ((hyb[0] == RDKit::Atom::SP2) && (hyb[1] == RDKit::Atom::SP2)) { diff --git a/Code/GraphMol/ForceFieldHelpers/UFF/Builder.cpp b/Code/GraphMol/ForceFieldHelpers/UFF/Builder.cpp index 487dc585d..22c4f97c8 100644 --- a/Code/GraphMol/ForceFieldHelpers/UFF/Builder.cpp +++ b/Code/GraphMol/ForceFieldHelpers/UFF/Builder.cpp @@ -53,7 +53,9 @@ void addBonds(const ROMol &mol, const AtomicParamVect ¶ms, } unsigned int twoBitCellPos(unsigned int nAtoms, int i, int j) { - if (j < i) std::swap(i, j); + if (j < i) { + std::swap(i, j); + } return i * (nAtoms - 1) + i * (1 - i) / 2 + j; } @@ -146,14 +148,20 @@ void addAngles(const ROMol &mol, const AtomicParamVect ¶ms, unsigned int nAtoms = mol.getNumAtoms(); for (unsigned int j = 0; j < nAtoms; j++) { - if (!params[j]) continue; + if (!params[j]) { + continue; + } const Atom *atomJ = mol.getAtomWithIdx(j); - if (atomJ->getDegree() == 1) continue; + if (atomJ->getDegree() == 1) { + continue; + } boost::tie(nbr1Idx, end1Nbrs) = mol.getAtomNeighbors(atomJ); for (; nbr1Idx != end1Nbrs; nbr1Idx++) { const Atom *atomI = mol[*nbr1Idx]; unsigned int i = atomI->getIdx(); - if (!params[i]) continue; + if (!params[i]) { + continue; + } boost::tie(nbr2Idx, end2Nbrs) = mol.getAtomNeighbors(atomJ); for (; nbr2Idx != end2Nbrs; nbr2Idx++) { if (nbr2Idx < (nbr1Idx + 1)) { @@ -161,7 +169,9 @@ void addAngles(const ROMol &mol, const AtomicParamVect ¶ms, } const Atom *atomK = mol[*nbr2Idx]; unsigned int k = atomK->getIdx(); - if (!params[k]) continue; + if (!params[k]) { + continue; + } // skip special cases: if (!(atomJ->getHybridization() == Atom::SP3D && atomJ->getDegree() == 5)) { @@ -287,13 +297,16 @@ void addTrigonalBipyramidAngles(const Atom *atom, const ROMol &mol, int confId, while (beg1 != end1) { const Bond *bond = mol[*beg1]; ++beg1; - if (bond == ax1 || bond == ax2) continue; - if (!eq1) + if (bond == ax1 || bond == ax2) { + continue; + } + if (!eq1) { eq1 = bond; - else if (!eq2) + } else if (!eq2) { eq2 = bond; - else if (!eq3) + } else if (!eq3) { eq3 = bond; + } } CHECK_INVARIANT(eq1, "equatorial bond not found"); @@ -434,7 +447,9 @@ void addNonbonded(const ROMol &mol, int confId, const AtomicParamVect ¶ms, unsigned int nAtoms = mol.getNumAtoms(); const Conformer &conf = mol.getConformer(confId); for (unsigned int i = 0; i < nAtoms; i++) { - if (!params[i]) continue; + if (!params[i]) { + continue; + } for (unsigned int j = i + 1; j < nAtoms; j++) { if (!params[j] || (ignoreInterfragInteractions && fragMapping[i] != fragMapping[j])) { @@ -517,14 +532,18 @@ void addTorsions(const ROMol &mol, const AtomicParamVect ¶ms, : SmartsToMol(torsionBondSmarts); TEST_ASSERT(query); unsigned int nHits = SubstructMatch(mol, *query, matchVect); - if (query != defaultQuery) delete query; + if (query != defaultQuery) { + delete query; + } for (unsigned int i = 0; i < nHits; i++) { MatchVectType match = matchVect[i]; TEST_ASSERT(match.size() == 2); int idx1 = match[0].second; int idx2 = match[1].second; - if (!params[idx1] || !params[idx2]) continue; + if (!params[idx1] || !params[idx2]) { + continue; + } const Bond *bond = mol.getBondBetweenAtoms(idx1, idx2); std::vector contribsHere; TEST_ASSERT(bond); diff --git a/Code/GraphMol/ForceFieldHelpers/UFF/testUFFHelpers.cpp b/Code/GraphMol/ForceFieldHelpers/UFF/testUFFHelpers.cpp index 21c07c479..99f1601cf 100644 --- a/Code/GraphMol/ForceFieldHelpers/UFF/testUFFHelpers.cpp +++ b/Code/GraphMol/ForceFieldHelpers/UFF/testUFFHelpers.cpp @@ -733,10 +733,12 @@ void testCalcEnergyPassedCoords() { field = UFF::constructForceField(*mol); TEST_ASSERT(field); field->initialize(); - double *savedPos = new double[3 * field->numPoints()]; + auto *savedPos = new double[3 * field->numPoints()]; size_t i = 0; for (const auto pptr : field->positions()) { - for (size_t j = 0; j < 3; ++j) savedPos[i++] = (*pptr)[j]; + for (size_t j = 0; j < 3; ++j) { + savedPos[i++] = (*pptr)[j]; + } } e1 = field->calcEnergy(); field->minimize(10000, 1.0e-6, 1.0e-3); @@ -769,28 +771,36 @@ void testCalcGrad() { TEST_ASSERT(field); field->initialize(); size_t l = 3 * field->numPoints(); - double *savedPos = new double[l]; - double *grad1 = new double[l]; - double *grad2 = new double[l]; + auto *savedPos = new double[l]; + auto *grad1 = new double[l]; + auto *grad2 = new double[l]; size_t i = 0; for (const auto pptr : field->positions()) { - for (size_t j = 0; j < 3; ++j) savedPos[i++] = (*pptr)[j]; + for (size_t j = 0; j < 3; ++j) { + savedPos[i++] = (*pptr)[j]; + } } TEST_ASSERT(i == l); std::memset(grad1, 0, l * sizeof(double)); field->calcGrad(grad1); - for (i = 0; i < l; ++i) TEST_ASSERT(!feq(grad1[i], 0.0, 0.001)); + for (i = 0; i < l; ++i) { + TEST_ASSERT(!feq(grad1[i], 0.0, 0.001)); + } field->minimize(10000, 1.0e-6, 1.0e-3); std::memset(grad2, 0, l * sizeof(double)); field->calcGrad(grad2); - for (i = 0; i < l; ++i) TEST_ASSERT(feq(grad2[i], 0.0, 0.001)); + for (i = 0; i < l; ++i) { + TEST_ASSERT(feq(grad2[i], 0.0, 0.001)); + } field->initialize(); std::memset(grad2, 0, l * sizeof(double)); field->calcGrad(savedPos, grad2); - for (i = 0; i < l; ++i) TEST_ASSERT(feq(grad1[i], grad2[i], 0.001)); + for (i = 0; i < l; ++i) { + TEST_ASSERT(feq(grad1[i], grad2[i], 0.001)); + } delete[] savedPos; delete[] grad1; @@ -1190,7 +1200,9 @@ void runblock_uff(const std::vector &mols, unsigned int idx) { for (unsigned int rep = 0; rep < 200; ++rep) { for (unsigned int i = 0; i < mols.size(); ++i) { - if (i % count != idx) continue; + if (i % count != idx) { + continue; + } ROMol *mol = mols[i]; ForceFields::ForceField *field = nullptr; if (!(rep % 100)) { @@ -1231,7 +1243,9 @@ void testUFFMultiThread() { } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } mols.push_back(mol); } diff --git a/Code/GraphMol/FragCatalog/FragCatalogEntry.cpp b/Code/GraphMol/FragCatalog/FragCatalogEntry.cpp index bba14d11d..4b536c567 100644 --- a/Code/GraphMol/FragCatalog/FragCatalogEntry.cpp +++ b/Code/GraphMol/FragCatalog/FragCatalogEntry.cpp @@ -158,7 +158,9 @@ Subgraphs::DiscrimTuple FragCatalogEntry::getDiscrims() const { this->getProp(common_properties::Discrims, res); } else { PATH_TYPE path; - for (unsigned int i = 0; i < dp_mol->getNumBonds(); ++i) path.push_back(i); + for (unsigned int i = 0; i < dp_mol->getNumBonds(); ++i) { + path.push_back(i); + } // create invariant additions to reflect the functional groups attached to // the atoms diff --git a/Code/GraphMol/FragCatalog/Wrap/FragCatalog.cpp b/Code/GraphMol/FragCatalog/Wrap/FragCatalog.cpp index 972c14ef8..741267ad7 100644 --- a/Code/GraphMol/FragCatalog/Wrap/FragCatalog.cpp +++ b/Code/GraphMol/FragCatalog/Wrap/FragCatalog.cpp @@ -28,32 +28,46 @@ struct fragcatalog_pickle_suite : python::pickle_suite { }; }; unsigned int GetBitEntryId(const FragCatalog *self, unsigned int idx) { - if (idx > self->getFPLength()) throw_index_error(idx); + if (idx > self->getFPLength()) { + throw_index_error(idx); + } return self->getIdOfEntryWithBitId(idx); } unsigned int GetEntryBitId(const FragCatalog *self, unsigned int idx) { - if (idx > self->getNumEntries()) throw_index_error(idx); + if (idx > self->getNumEntries()) { + throw_index_error(idx); + } return self->getEntryWithIdx(idx)->getBitId(); } std::string GetEntryDescription(const FragCatalog *self, unsigned int idx) { - if (idx > self->getNumEntries()) throw_index_error(idx); + if (idx > self->getNumEntries()) { + throw_index_error(idx); + } return self->getEntryWithIdx(idx)->getDescription(); } std::string GetBitDescription(const FragCatalog *self, unsigned int idx) { - if (idx > self->getFPLength()) throw_index_error(idx); + if (idx > self->getFPLength()) { + throw_index_error(idx); + } return self->getEntryWithBitId(idx)->getDescription(); } unsigned int GetEntryOrder(const FragCatalog *self, unsigned int idx) { - if (idx > self->getNumEntries()) throw_index_error(idx); + if (idx > self->getNumEntries()) { + throw_index_error(idx); + } return self->getEntryWithIdx(idx)->getOrder(); } unsigned int GetBitOrder(const FragCatalog *self, unsigned int idx) { - if (idx > self->getFPLength()) throw_index_error(idx); + if (idx > self->getFPLength()) { + throw_index_error(idx); + } return self->getEntryWithBitId(idx)->getOrder(); } INT_VECT GetEntryFuncGroupIds(const FragCatalog *self, unsigned int idx) { - if (idx > self->getNumEntries()) throw_index_error(idx); + if (idx > self->getNumEntries()) { + throw_index_error(idx); + } INT_VECT res; INT_INT_VECT_MAP gps = self->getEntryWithIdx(idx)->getFuncGroupMap(); for (const auto &iv : gps) { @@ -64,7 +78,9 @@ INT_VECT GetEntryFuncGroupIds(const FragCatalog *self, unsigned int idx) { return res; } INT_VECT GetBitFuncGroupIds(const FragCatalog *self, unsigned int idx) { - if (idx > self->getFPLength()) throw_index_error(idx); + if (idx > self->getFPLength()) { + throw_index_error(idx); + } INT_VECT res; INT_INT_VECT_MAP gps = self->getEntryWithBitId(idx)->getFuncGroupMap(); for (const auto &iv : gps) { @@ -75,12 +91,16 @@ INT_VECT GetBitFuncGroupIds(const FragCatalog *self, unsigned int idx) { return res; } INT_VECT GetEntryDownIds(const FragCatalog *self, unsigned int idx) { - if (idx > self->getNumEntries()) throw_index_error(idx); + if (idx > self->getNumEntries()) { + throw_index_error(idx); + } return self->getDownEntryList(idx); } DOUBLE_VECT GetBitDiscrims(const FragCatalog *self, unsigned int idx) { - if (idx > self->getFPLength()) throw_index_error(idx); + if (idx > self->getFPLength()) { + throw_index_error(idx); + } DOUBLE_VECT res; const FragCatalogEntry *entry = self->getEntryWithBitId(idx); Subgraphs::DiscrimTuple tmp = entry->getDiscrims(); diff --git a/Code/GraphMol/Kekulize.cpp b/Code/GraphMol/Kekulize.cpp index 4274eebcf..ca4305958 100644 --- a/Code/GraphMol/Kekulize.cpp +++ b/Code/GraphMol/Kekulize.cpp @@ -83,7 +83,9 @@ void markDbondCands(RWMol &mol, const INT_VECT &allAtms, // if there's not at least one atom in the ring that's // marked as being aromatic or a dummy, // there's no point in continuing: - if (!hasAromaticOrDummyAtom) return; + if (!hasAromaticOrDummyAtom) { + return; + } std::vector makeSingle; @@ -130,7 +132,9 @@ void markDbondCands(RWMol &mol, const INT_VECT &allAtms, } else { int bondContrib = std::lround(bond->getValenceContrib(at)); sbo += bondContrib; - if (!bondContrib) ++nToIgnore; + if (!bondContrib) { + ++nToIgnore; + } } ++beg; } @@ -147,9 +151,13 @@ void markDbondCands(RWMol &mol, const INT_VECT &allAtms, sbo += at->getTotalNumHs(); int dv = PeriodicTable::getTable()->getDefaultValence(at->getAtomicNum()); int chrg = at->getFormalCharge(); - if (isEarlyAtom(at->getAtomicNum())) chrg *= -1; // fix for GitHub #65 + if (isEarlyAtom(at->getAtomicNum())) { + chrg *= -1; // fix for GitHub #65 + } // special case for carbon - see GitHub #539 - if (at->getAtomicNum() == 6 && chrg > 0) chrg = -chrg; + if (at->getAtomicNum() == 6 && chrg > 0) { + chrg = -chrg; + } dv += chrg; int tbo = at->getTotalValence(); int nRadicals = at->getNumRadicalElectrons(); @@ -411,7 +419,9 @@ bool permuteDummiesAndKekulize(RWMol &mol, const INT_VECT &allAtms, #endif // pick a new permutation of the questionable atoms: const INT_VECT &switchOff = qEnum.next(); - if (!switchOff.size()) break; + if (!switchOff.size()) { + break; + } boost::dynamic_bitset<> tCands = dBndCands; for (int it : switchOff) { tCands[it] = 0; @@ -490,7 +500,9 @@ void Kekulize(RWMol &mol, bool markAtomsBonds, unsigned int maxBackTracks) { bool foundAromatic = false; for (ROMol::BondIterator bi = mol.beginBonds(); bi != mol.endBonds() && !foundAromatic; ++bi) { - if ((*bi)->getIsAromatic()) foundAromatic = true; + if ((*bi)->getIsAromatic()) { + foundAromatic = true; + } } // before everything do implicit valence calculation and store them @@ -502,9 +514,13 @@ void Kekulize(RWMol &mol, bool markAtomsBonds, unsigned int maxBackTracks) { for (ROMol::AtomIterator ai = mol.beginAtoms(); ai != mol.endAtoms(); ++ai) { (*ai)->calcImplicitValence(false); valences.push_back((*ai)->getTotalValence()); - if (!foundAromatic && (*ai)->getIsAromatic()) foundAromatic = true; + if (!foundAromatic && (*ai)->getIsAromatic()) { + foundAromatic = true; + } + } + if (!foundAromatic) { + return; } - if (!foundAromatic) return; // A bit on the state of the molecule at this point // - aromatic and non aromatic atoms and bonds may be mixed up @@ -521,7 +537,9 @@ void Kekulize(RWMol &mol, bool markAtomsBonds, unsigned int maxBackTracks) { boost::dynamic_bitset<> dummyAts(mol.getNumAtoms()); for (ROMol::AtomIterator atit = mol.beginAtoms(); atit != mol.endAtoms(); ++atit) { - if (!(*atit)->getAtomicNum()) dummyAts[(*atit)->getIdx()] = 1; + if (!(*atit)->getAtomicNum()) { + dummyAts[(*atit)->getIdx()] = 1; + } } if (dummyAts.any()) { VECT_INT_VECT allrings; diff --git a/Code/GraphMol/MMPA/MMPA.cpp b/Code/GraphMol/MMPA/MMPA.cpp index 59fbe0b74..534b175a6 100644 --- a/Code/GraphMol/MMPA/MMPA.cpp +++ b/Code/GraphMol/MMPA/MMPA.cpp @@ -34,7 +34,9 @@ static inline unsigned long long computeMorganCodeHash(const ROMol& mol) { std::vector currCodes(nv); std::vector prevCodes(nv); size_t nIterations = mol.getNumBonds(); - if (nIterations > 5) nIterations = 5; + if (nIterations > 5) { + nIterations = 5; + } for (unsigned ai = 0; ai < nv; ai++) { const Atom& a = *mol.getAtomWithIdx(ai); @@ -46,7 +48,9 @@ static inline unsigned long long computeMorganCodeHash(const ROMol& mol) { } for (size_t iter = 0; iter < nIterations; iter++) { - for (size_t i = 0; i < nv; i++) prevCodes[i] = currCodes[i]; + for (size_t i = 0; i < nv; i++) { + prevCodes[i] = currCodes[i]; + } for (size_t bi = 0; bi < ne; bi++) { const Bond* bond = mol.getBondWithIdx(bi); @@ -77,8 +81,8 @@ static inline void convertMatchingToBondVect( matching_bonds.push_back(BondVector_t()); BondVector_t& mb = matching_bonds.back(); // current match // assume pattern is only one bond pattern - unsigned a1 = (unsigned)matching_atom[0].second; // mol atom 1 index - unsigned a2 = (unsigned)matching_atom[1].second; // mol atom 2 index + auto a1 = (unsigned)matching_atom[0].second; // mol atom 1 index + auto a2 = (unsigned)matching_atom[1].second; // mol atom 2 index mb.push_back(std::pair(a1, a2)); } } @@ -163,8 +167,10 @@ static void addResult(std::vector>& for (size_t i = 0; i < nFrags; i++) { unsigned nLabels = 0; for (int ai : frags[i]) { - if (isotope_track.end() != isotope_track.find(ai)) // new added atom + if (isotope_track.end() != + isotope_track.find(ai)) { // new added atom ++nLabels; // found connection point + } } if (nLabels >= maxCuts) { // looks like it should be selected as core ! ?????? @@ -191,10 +197,13 @@ static void addResult(std::vector>& unsigned nAttachments = 0; for (int ai : frags[i]) { if (isotope_track.end() != - isotope_track.find(ai)) // == if(a->hasProp("molAtomMapNumber")) + isotope_track.find(ai)) { // == if(a->hasProp("molAtomMapNumber")) ++nAttachments; + } + } + if (maxAttachments < nAttachments) { + maxAttachments = nAttachments; } - if (maxAttachments < nAttachments) maxAttachments = nAttachments; if (1 == nAttachments) { // build side-chain set of molecules from // selected fragment std::map @@ -211,8 +220,9 @@ static void addResult(std::vector>& const Bond* bond = em[*beg]; if (newAtomMap.end() == newAtomMap.find(bond->getBeginAtomIdx()) || newAtomMap.end() == newAtomMap.find(bond->getEndAtomIdx()) || - visitedBonds.end() != visitedBonds.find(bond->getIdx())) + visitedBonds.end() != visitedBonds.find(bond->getIdx())) { continue; + } unsigned ai1 = newAtomMap[bond->getBeginAtomIdx()]; unsigned ai2 = newAtomMap[bond->getEndAtomIdx()]; unsigned bi = side_chains->addBond(ai1, ai2, bond->getBondType()); @@ -226,10 +236,11 @@ static void addResult(std::vector>& std::cout << "Next CORE found. iCore=" << iCore << " New i=" << i << " nAttachments=" << nAttachments << "\n"; #endif - if (nAttachments >= maxAttachments) // Choose a fragment with maximal - // number of connection points as a - // core + if (nAttachments >= maxAttachments) { // Choose a fragment with maximal + // number of connection points as + // a core iCore = i; + } } } // build core molecule from selected fragment @@ -250,8 +261,9 @@ static void addResult(std::vector>& const Bond* bond = em[*beg]; if (newAtomMap.end() == newAtomMap.find(bond->getBeginAtomIdx()) || newAtomMap.end() == newAtomMap.find(bond->getEndAtomIdx()) || - visitedBonds.end() != visitedBonds.find(bond->getIdx())) + visitedBonds.end() != visitedBonds.find(bond->getIdx())) { continue; + } unsigned ai1 = newAtomMap[bond->getBeginAtomIdx()]; unsigned ai2 = newAtomMap[bond->getEndAtomIdx()]; unsigned bi = core->addBond(ai1, ai2, bond->getBondType()); @@ -390,18 +402,22 @@ static void addResult(std::vector>& //===================================================================== static inline void appendBonds(BondVector_t& bonds, const BondVector_t& matching_bonds) { - for (const auto& matching_bond : matching_bonds) + for (const auto& matching_bond : matching_bonds) { bonds.push_back(matching_bond); + } } static inline void processCuts( size_t i, size_t minCuts, size_t maxCuts, BondVector_t& bonds_selected, const std::vector& matching_bonds, const ROMol& mol, std::vector>& res) { - if (maxCuts < minCuts) + if (maxCuts < minCuts) { throw ValueErrorException("supplied maxCuts is less than minCuts"); + } - if (minCuts == 0) throw ValueErrorException("minCuts must be greater than 0"); + if (minCuts == 0) { + throw ValueErrorException("minCuts must be greater than 0"); + } for (size_t x = i; x < matching_bonds.size(); x++) { appendBonds(bonds_selected, matching_bonds[x]); @@ -457,8 +473,9 @@ bool fragmentMol(const ROMol& mol, std::cout << "total substructs =" << total << "\nmatching bonds (atom1, atom2):\n"; #endif - if (0 == total) // Not found. Return empty set of molecules + if (0 == total) { // Not found. Return empty set of molecules return false; + } #ifdef MMPA_DEBUG for (size_t i = 0; i < matching_atoms.size(); i++) { std::string symbol = @@ -488,7 +505,9 @@ bool fragmentMol(const ROMol& mol, std::vector matching_bonds; // List of matched query's bonds convertMatchingToBondVect(matching_bonds, matching_atoms, mol); - if (matching_bonds.size() > maxCutBonds) return false; + if (matching_bonds.size() > maxCutBonds) { + return false; + } #ifdef MMPA_DEBUG std::cout << "total matching_bonds = " << matching_bonds.size() << "\n"; #endif diff --git a/Code/GraphMol/MMPA/MMPA_UnitTest.cpp b/Code/GraphMol/MMPA/MMPA_UnitTest.cpp index 0bbc8f734..85f644bee 100644 --- a/Code/GraphMol/MMPA/MMPA_UnitTest.cpp +++ b/Code/GraphMol/MMPA/MMPA_UnitTest.cpp @@ -123,7 +123,9 @@ std::string getSmilesOnly( std::string* id = nullptr) { // remove label, because RDKit parse FAILED const char* sp = strchr(smiles, ' '); unsigned n = (sp ? sp - smiles + 1 : strlen(smiles)); - if (id) *id = std::string(smiles + (n--)); + if (id) { + *id = std::string(smiles + (n--)); + } return std::string(smiles, n); } @@ -313,14 +315,17 @@ void test1() { break; } } - if (j < 9) std::cout << " "; + if (j < 9) { + std::cout << " "; + } if (failed) { test_failed = true; std::cout << j + 1 << ": NOREF. Reference data NOT LISTED in test case." << ss.str() << "\n"; // << "FS: " << fs[j] <<"\n"; - } else + } else { std::cout << j + 1 << ": PASSED. matchedRefRes = " << matchedRefRes + 1 << "\n"; // ok: << "ss: " << ss.str() <<"\n"; + } std::cout.flush(); } std::cout << "\n --- UNMATCHED Reference RESULTS: --- \n"; @@ -332,7 +337,9 @@ void test1() { } std::cout << " -----------------------------------\n" << "DO TEST_ASSERT():\n"; - if (test_failed) n_failed++; + if (test_failed) { + n_failed++; + } TEST_ASSERT(!test_failed); } BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; @@ -407,10 +414,12 @@ void test2() { int token_num = 0; ref_str.str(""); while (getline(ss_token, s_token, ',')) { - if (token_num == 2) + if (token_num == 2) { ref_str << createCanonicalFromSmiles(s_token.c_str()) << ","; - if (token_num == 3) + } + if (token_num == 3) { ref_str << createCanonicalFromSmiles(s_token.c_str()); + } token_num++; } ref_map[ref_str.str()] = r; @@ -439,7 +448,9 @@ void test2() { std::stringstream res_str; res_str << first_res << "," << second_res; - if (res_idx < 9) std::cout << " "; + if (res_idx < 9) { + std::cout << " "; + } if (ref_map.find(res_str.str()) != ref_map.end()) { size_t matchedRefRes = ref_map[res_str.str()]; @@ -459,8 +470,9 @@ void test2() { n_failed++; std::cout << "\n --- UNMATCHED Reference RESULTS: --- \n"; for (size_t r = 0; r < sizeof(fs) / sizeof(fs[0]); r++) { - if (fs2res.end() == fs2res.find(r)) + if (fs2res.end() == fs2res.find(r)) { std::cout << (r < 9 ? " " : "") << r + 1 << ": " << fs[r] << "\n"; + } } } else { std::cout << "\n --- ALL PASSED --- \n"; @@ -495,9 +507,12 @@ void doTest(const char* smi, const char* fs[], unsigned fs_size) { int token_num = 0; ref_str.str(""); while (getline(ss_token, s_token, ',')) { - if (token_num == 2) + if (token_num == 2) { ref_str << createCanonicalFromSmiles(s_token.c_str()) << ","; - if (token_num == 3) ref_str << createCanonicalFromSmiles(s_token.c_str()); + } + if (token_num == 3) { + ref_str << createCanonicalFromSmiles(s_token.c_str()); + } token_num++; } ref_map[ref_str.str()] = r; @@ -505,7 +520,9 @@ void doTest(const char* smi, const char* fs[], unsigned fs_size) { bool has_failed = false; for (size_t res_idx = 0; res_idx < res.size(); res_idx++) { - if (res_idx < 9) std::cout << " "; + if (res_idx < 9) { + std::cout << " "; + } std::cout << res_idx + 1 << ": res= "; /* * Somehow canonical smiles does not return the same result after just @@ -527,7 +544,9 @@ void doTest(const char* smi, const char* fs[], unsigned fs_size) { std::stringstream res_str; res_str << first_res << "," << second_res; - if (res_idx < 9) std::cout << " "; + if (res_idx < 9) { + std::cout << " "; + } if (ref_map.find(res_str.str()) != ref_map.end()) { size_t matchedRefRes = ref_map[res_str.str()]; @@ -547,8 +566,9 @@ void doTest(const char* smi, const char* fs[], unsigned fs_size) { n_failed++; std::cout << "\n --- UNMATCHED Reference RESULTS: --- \n"; for (size_t r = 0; r < fs_size; r++) { - if (fs2res.end() == fs2res.find(r)) + if (fs2res.end() == fs2res.find(r)) { std::cout << (r < 9 ? " " : "") << r + 1 << ": " << fs[r] << "\n"; + } } } else { std::cout << "\n --- ALL PASSED --- \n"; @@ -702,8 +722,9 @@ int main() { if (0 != n_failed) { std::cout << n_failed << " TEST CASES FAILED \n"; TEST_ASSERT(0 != n_failed); - } else + } else { std::cout << " --- ALL TEST CASES PASSED --- \n"; + } BOOST_LOG(rdInfoLog) << "*******************************************************\n"; return 0; diff --git a/Code/GraphMol/Matrices.cpp b/Code/GraphMol/Matrices.cpp index 3a67c04a7..6df5f661f 100644 --- a/Code/GraphMol/Matrices.cpp +++ b/Code/GraphMol/Matrices.cpp @@ -175,7 +175,9 @@ double *getDistanceMat(const ROMol &mol, bool useBO, bool useAtomWts, } propName += "DistanceMatrix"; // make sure we don't use the nonBO cache for the BO matrix and vice versa: - if (useBO) propName += "BO"; + if (useBO) { + propName += "BO"; + } if (!force && mol.hasProp(propName)) { mol.getProp(propName, sptr); return sptr.get(); @@ -184,8 +186,12 @@ double *getDistanceMat(const ROMol &mol, bool useBO, bool useAtomWts, auto *dMat = new double[nAts * nAts]; int i, j; // initialize off diagonals to LOCAL_INF and diagonals to 0 - for (i = 0; i < nAts * nAts; i++) dMat[i] = LOCAL_INF; - for (i = 0; i < nAts; i++) dMat[i * nAts + i] = 0.0; + for (i = 0; i < nAts * nAts; i++) { + dMat[i] = LOCAL_INF; + } + for (i = 0; i < nAts; i++) { + dMat[i * nAts + i] = 0.0; + } ROMol::EDGE_ITER firstB, lastB; boost::tie(firstB, lastB) = mol.getEdges(); @@ -234,8 +240,12 @@ double *getDistanceMat(const ROMol &mol, const std::vector &activeAtoms, auto *dMat = new double[nAts * nAts]; int i, j; // initialize off diagonals to LOCAL_INF and diagonals to 0 - for (i = 0; i < nAts * nAts; i++) dMat[i] = LOCAL_INF; - for (i = 0; i < nAts; i++) dMat[i * nAts + i] = 0.0; + for (i = 0; i < nAts * nAts; i++) { + dMat[i] = LOCAL_INF; + } + for (i = 0; i < nAts; i++) { + dMat[i * nAts + i] = 0.0; + } for (auto bond : bonds) { i = rdcast(std::find(activeAtoms.begin(), activeAtoms.end(), diff --git a/Code/GraphMol/MolAlign/AlignMolecules.cpp b/Code/GraphMol/MolAlign/AlignMolecules.cpp index 9696b2321..6741bf0fd 100644 --- a/Code/GraphMol/MolAlign/AlignMolecules.cpp +++ b/Code/GraphMol/MolAlign/AlignMolecules.cpp @@ -106,8 +106,9 @@ double getBestRMS(ROMol &probeMol, ROMol &refMol, int probeId, int refId, } // Perform a final alignment to the best alignment... - if (&bestMatch != &matches.back()) + if (&bestMatch != &matches.back()) { alignMol(probeMol, refMol, probeId, refId, &bestMatch); + } return bestRMS; } diff --git a/Code/GraphMol/MolAlign/O3AAlignMolecules.cpp b/Code/GraphMol/MolAlign/O3AAlignMolecules.cpp index b1390c8fb..cd3e21ff7 100644 --- a/Code/GraphMol/MolAlign/O3AAlignMolecules.cpp +++ b/Code/GraphMol/MolAlign/O3AAlignMolecules.cpp @@ -565,15 +565,16 @@ MolHistogram::MolHistogram(const ROMol &mol, const double *dmat, d_h[y][j] = 0; } for (unsigned int j = 0; j < nAtoms; ++j) { - unsigned int dist = - static_cast(floor(dmat[i * nAtoms + j])); + auto dist = static_cast(floor(dmat[i * nAtoms + j])); if (dist < O3_MAX_H_BINS) { ++d_h[y][dist]; } } ++y; } - if (cleanupDmat) delete[] dmat; + if (cleanupDmat) { + delete[] dmat; + } } int o3aMMFFCostFunc(const unsigned int prbIdx, const unsigned int refIdx, @@ -660,7 +661,9 @@ void LAP::computeCostMatrix(const ROMol &prbMol, const MolHistogram &prbHist, for (k = 0, hSum = 0.0; k < n_bins; ++k) { int rhyk = refHist.get(y, k); int phxk = prbHist.get(x, k); - if ((!rhyk) && (!phxk)) continue; + if ((!rhyk) && (!phxk)) { + continue; + } hSum += (double)square(rhyk - phxk) / (double)(rhyk + phxk); } d_cost[y][x] = (*costFunc)(j, i, hSum, data); @@ -1034,10 +1037,14 @@ void SDM::fillFromDist(double threshold, boost::dynamic_bitset<> prbUsed(largestNAtoms); // loop over ref atoms for (unsigned int i = 0; i < refNAtoms; ++i) { - if (!refHvyAtoms[i]) continue; + if (!refHvyAtoms[i]) { + continue; + } // loop over prb atoms for (unsigned int j = 0; j < prbNAtoms; ++j) { - if (!prbHvyAtoms[j]) continue; + if (!prbHvyAtoms[j]) { + continue; + } double sqDist = (refPos[i] - prbPos[j]).lengthSq(); // if the distance between these two atoms is lower // than threshold, then include this pair in the SDM matrix @@ -1500,7 +1507,7 @@ O3A::O3A(ROMol &prbMol, const ROMol &refMol, void *prbProp, void *refProp, } } } - unsigned int pairs = rdcast(bestO3A->matches()->size()); + auto pairs = rdcast(bestO3A->matches()->size()); RDKit::MatchVectType *bestO3AMatchVect = new RDKit::MatchVectType(pairs); auto *bestO3AWeights = new RDNumeric::DoubleVector(pairs); d_o3aMatchVect = bestO3AMatchVect; @@ -1660,7 +1667,9 @@ void O3AHelper_(ROMol *prbMol, const ROMol *refMol, void *prbProp, unsigned int i = 0; for (ROMol::ConstConformerIterator cit = prbMol->beginConformers(); cit != prbMol->endConformers(); ++cit, ++i) { - if (i % numThreads != threadIdx) continue; + if (i % numThreads != threadIdx) { + continue; + } auto *lres = new O3A(*prbMol, *refMol, prbProp, refProp, args->atomTypes, diff --git a/Code/GraphMol/MolAlign/Wrap/rdMolAlign.cpp b/Code/GraphMol/MolAlign/Wrap/rdMolAlign.cpp index 694a4f91e..bcd709c68 100644 --- a/Code/GraphMol/MolAlign/Wrap/rdMolAlign.cpp +++ b/Code/GraphMol/MolAlign/Wrap/rdMolAlign.cpp @@ -111,7 +111,7 @@ void alignMolConfs(ROMol &mol, python::object atomIds, python::object confIds, delete cIds; } if (RMSvector) { - python::list &pyl = static_cast(RMSlist); + auto &pyl = static_cast(RMSlist); for (double &i : (*RMSvector)) { pyl.append(i); } @@ -123,8 +123,8 @@ PyObject *generateRmsdTransPyTuple(double rmsd, RDGeom::Transform3D &trans) { npy_intp dims[2]; dims[0] = 4; dims[1] = 4; - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); - double *resData = reinterpret_cast(PyArray_DATA(res)); + auto *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); + auto *resData = reinterpret_cast(PyArray_DATA(res)); unsigned int i, j, itab; const double *tdata = trans.getData(); for (i = 0; i < trans.numRows(); ++i) { @@ -212,7 +212,9 @@ double AlignMolecule(ROMol &prbMol, const ROMol &refMol, int prbCid = -1, double GetBestRMS(ROMol &prbMol, ROMol &refMol, int prbId, int refId, python::object map, int maxMatches) { std::vector aMapVec; - if (map != python::object()) aMapVec = _translateAtomMapVector(map); + if (map != python::object()) { + aMapVec = _translateAtomMapVector(map); + } double rmsd; { @@ -323,8 +325,12 @@ PyO3A *getMMFFO3A(ROMol &prbMol, ROMol &refMol, python::object prbProps, } auto *pyO3A = new PyO3A(o3a); - if (!prbPyMMFFMolProperties) delete prbMolProps; - if (!refPyMMFFMolProperties) delete refMolProps; + if (!prbPyMMFFMolProperties) { + delete prbMolProps; + } + if (!refPyMMFFMolProperties) { + delete refMolProps; + } if (cMap) { delete cMap; } @@ -401,8 +407,12 @@ python::tuple getMMFFO3AForConfs( pyres.append(new PyO3A(i)); } - if (!prbPyMMFFMolProperties) delete prbMolProps; - if (!refPyMMFFMolProperties) delete refMolProps; + if (!prbPyMMFFMolProperties) { + delete prbMolProps; + } + if (!refPyMMFFMolProperties) { + delete refMolProps; + } if (cMap) { delete cMap; } diff --git a/Code/GraphMol/MolAlign/testMolAlign.cpp b/Code/GraphMol/MolAlign/testMolAlign.cpp index 1692231d2..7ead8056c 100644 --- a/Code/GraphMol/MolAlign/testMolAlign.cpp +++ b/Code/GraphMol/MolAlign/testMolAlign.cpp @@ -616,7 +616,9 @@ void runblock_o3a_mmff(ROMol *refMol, const std::vector &mols, for (unsigned int rep = 0; rep < 10; ++rep) { MMFF::MMFFMolProperties refMP(*refMol); for (unsigned int i = 0; i < mols.size(); ++i) { - if (i % count != idx) continue; + if (i % count != idx) { + continue; + } if (!(rep % 10)) { BOOST_LOG(rdErrorLog) << "Rep: " << rep << " Mol:" << i << std::endl; } @@ -645,7 +647,9 @@ void runblock_o3a_crippen(ROMol *refMol, const std::vector &mols, refMRContribs, true, &refAtomTypes, &refAtomTypeLabels); for (unsigned int i = 0; i < mols.size(); ++i) { - if (i % count != idx) continue; + if (i % count != idx) { + continue; + } if (!(rep % 10)) { BOOST_LOG(rdErrorLog) << "Rep: " << rep << " Mol:" << i << std::endl; } @@ -684,7 +688,9 @@ void testMMFFO3AMultiThread() { } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } mols.push_back(mol); } @@ -735,7 +741,9 @@ void testCrippenO3AMultiThread() { } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } mols.push_back(mol); } @@ -801,7 +809,9 @@ void testGetO3AForProbeConfs() { TEST_ASSERT(prbMol); while (!psuppl.atEnd()) { ROMol *mol = psuppl.next(); - if (!mol) continue; + if (!mol) { + continue; + } auto *conf = new Conformer(mol->getConformer()); prbMol->addConformer(conf, true); delete mol; @@ -866,7 +876,9 @@ void testO3AMultiThreadBug() { std::vector mols; while (!suppl.atEnd()) { ROMol *mol = suppl.next(); - if (!mol) continue; + if (!mol) { + continue; + } while (mol->getNumConformers() < 20) { auto *conf = new Conformer(mol->getConformer(0)); diff --git a/Code/GraphMol/MolCatalog/Wrap/rdMolCatalog.cpp b/Code/GraphMol/MolCatalog/Wrap/rdMolCatalog.cpp index ac1a01b9a..131aff8d5 100644 --- a/Code/GraphMol/MolCatalog/Wrap/rdMolCatalog.cpp +++ b/Code/GraphMol/MolCatalog/Wrap/rdMolCatalog.cpp @@ -31,24 +31,34 @@ struct molcatalogentry_pickle_suite : python::pickle_suite { }; unsigned int GetBitEntryId(const MolCatalog *self, unsigned int idx) { - if (idx > self->getFPLength()) throw_index_error(idx); + if (idx > self->getFPLength()) { + throw_index_error(idx); + } return self->getIdOfEntryWithBitId(idx); } unsigned int GetEntryBitId(const MolCatalog *self, unsigned int idx) { - if (idx > self->getNumEntries()) throw_index_error(idx); + if (idx > self->getNumEntries()) { + throw_index_error(idx); + } return self->getEntryWithIdx(idx)->getBitId(); } std::string GetEntryDescription(const MolCatalog *self, unsigned int idx) { - if (idx > self->getNumEntries()) throw_index_error(idx); + if (idx > self->getNumEntries()) { + throw_index_error(idx); + } return self->getEntryWithIdx(idx)->getDescription(); } std::string GetBitDescription(const MolCatalog *self, unsigned int idx) { - if (idx > self->getFPLength()) throw_index_error(idx); + if (idx > self->getFPLength()) { + throw_index_error(idx); + } return self->getEntryWithBitId(idx)->getDescription(); } INT_VECT GetEntryDownIds(const MolCatalog *self, unsigned int idx) { - if (idx > self->getNumEntries()) throw_index_error(idx); + if (idx > self->getNumEntries()) { + throw_index_error(idx); + } return self->getDownEntryList(idx); } diff --git a/Code/GraphMol/MolChemicalFeatures/FeatureParser.cpp b/Code/GraphMol/MolChemicalFeatures/FeatureParser.cpp index c399ce24a..69cfc9bc3 100644 --- a/Code/GraphMol/MolChemicalFeatures/FeatureParser.cpp +++ b/Code/GraphMol/MolChemicalFeatures/FeatureParser.cpp @@ -31,7 +31,9 @@ typedef boost::tokenizer> CommaTokenizer; void getNextLine(std::istream &inStream, std::string &line, unsigned int &lineNo) { - if (inStream.eof() || inStream.fail()) return; + if (inStream.eof() || inStream.fail()) { + return; + } line = ""; bool continuationLine = false; while (!inStream.eof() && !inStream.fail()) { @@ -39,12 +41,16 @@ void getNextLine(std::istream &inStream, std::string &line, std::getline(inStream, tmpLine); lineNo++; // std::cerr << ">> " << lineNo << " " << tmpLine << std::endl; - if (tmpLine == "") continue; + if (tmpLine == "") { + continue; + } if (tmpLine[0] != '#') { // strip space at the end to check for a continuation line: std::string stripLine = boost::trim_right_copy_if(tmpLine, boost::is_any_of(" \t\r\n")); - if (stripLine == "") continue; + if (stripLine == "") { + continue; + } if (stripLine[stripLine.size() - 1] != '\\') { if (continuationLine) { // if it's a continuation line, strip any whitespace: @@ -293,7 +299,9 @@ int parseFeatureData(std::istream &inStream, } else if (token == "DEFINEFEATURE") { MolChemicalFeatureDef *fDef = Local::parseFeatureDef(inStream, inLine, lineNo, atomTypeDefs); - if (fDef) res.push_back(boost::shared_ptr(fDef)); + if (fDef) { + res.push_back(boost::shared_ptr(fDef)); + } } else { throw FeatureFileParseException(lineNo, inLine, "bad or missing keyword"); diff --git a/Code/GraphMol/MolChemicalFeatures/MolChemicalFeature.cpp b/Code/GraphMol/MolChemicalFeatures/MolChemicalFeature.cpp index d65a3f36a..9c892ed8a 100644 --- a/Code/GraphMol/MolChemicalFeatures/MolChemicalFeature.cpp +++ b/Code/GraphMol/MolChemicalFeatures/MolChemicalFeature.cpp @@ -35,7 +35,9 @@ RDGeom::Point3D MolChemicalFeature::getPos() const { RDGeom::Point3D MolChemicalFeature::getPos(int confId) const { PRECONDITION(dp_mol, "bad molecule"); PRECONDITION(dp_mol->getNumConformers(), "molecule has no conformers"); - if (confId == -1) confId = (*dp_mol->beginConformers())->getId(); + if (confId == -1) { + confId = (*dp_mol->beginConformers())->getId(); + } // ------------- // Check to see if we've got the value cached: diff --git a/Code/GraphMol/MolChemicalFeatures/MolChemicalFeatureDef.cpp b/Code/GraphMol/MolChemicalFeatures/MolChemicalFeatureDef.cpp index 8da3c1a7f..1f008a6c6 100644 --- a/Code/GraphMol/MolChemicalFeatures/MolChemicalFeatureDef.cpp +++ b/Code/GraphMol/MolChemicalFeatures/MolChemicalFeatureDef.cpp @@ -21,7 +21,7 @@ MolChemicalFeatureDef::MolChemicalFeatureDef(const std::string &smarts, std::string family, std::string type) : d_family(std::move(family)), d_type(std::move(type)), d_smarts(smarts) { - ROMol *mol = static_cast(SmartsToMol(smarts)); + auto *mol = static_cast(SmartsToMol(smarts)); dp_pattern.reset(mol); } void MolChemicalFeatureDef::normalizeWeights() { diff --git a/Code/GraphMol/MolChemicalFeatures/Wrap/MolChemicalFeatureFactory.cpp b/Code/GraphMol/MolChemicalFeatures/Wrap/MolChemicalFeatureFactory.cpp index 83a5612bd..e234b9cc9 100644 --- a/Code/GraphMol/MolChemicalFeatures/Wrap/MolChemicalFeatureFactory.cpp +++ b/Code/GraphMol/MolChemicalFeatures/Wrap/MolChemicalFeatureFactory.cpp @@ -68,7 +68,9 @@ python::tuple getFeatureFamilies(const MolChemicalFeatureFactory &factory) { for (iter = factory.beginFeatureDefs(); iter != factory.endFeatureDefs(); ++iter) { std::string fam = (*iter)->getFamily(); - if (res.count(fam) == 0) res.append(fam); + if (res.count(fam) == 0) { + res.append(fam); + } } return python::tuple(res); } diff --git a/Code/GraphMol/MolChemicalFeatures/Wrap/rdMolChemicalFeatures.cpp b/Code/GraphMol/MolChemicalFeatures/Wrap/rdMolChemicalFeatures.cpp index 6aa073660..1a38089bd 100644 --- a/Code/GraphMol/MolChemicalFeatures/Wrap/rdMolChemicalFeatures.cpp +++ b/Code/GraphMol/MolChemicalFeatures/Wrap/rdMolChemicalFeatures.cpp @@ -31,13 +31,13 @@ MolChemicalFeatureFactory *buildFeatFactory(std::string fileName) { PyErr_SetString(PyExc_IOError, errorstring.c_str()); python::throw_error_already_set(); } - std::istream &instrm = static_cast(inStream); + auto &instrm = static_cast(inStream); return buildFeatureFactory(instrm); } MolChemicalFeatureFactory *buildFeatFactoryFromString(std::string fdefString) { std::istringstream inStream(fdefString); - std::istream &instrm = static_cast(inStream); + auto &instrm = static_cast(inStream); return buildFeatureFactory(instrm); } } diff --git a/Code/GraphMol/MolChemicalFeatures/testFeatures.cpp b/Code/GraphMol/MolChemicalFeatures/testFeatures.cpp index c225be5af..aafc9191a 100644 --- a/Code/GraphMol/MolChemicalFeatures/testFeatures.cpp +++ b/Code/GraphMol/MolChemicalFeatures/testFeatures.cpp @@ -456,7 +456,7 @@ void test7() { std::ifstream inStream(fName.c_str()); TEST_ASSERT(inStream.is_open()); - std::istream &instrm = static_cast(inStream); + auto &instrm = static_cast(inStream); factory = buildFeatureFactory(instrm); TEST_ASSERT(factory); TEST_ASSERT(factory->getNumFeatureDefs() == 2); @@ -638,7 +638,7 @@ void testIssue346() { std::ifstream inStream(fName.c_str()); TEST_ASSERT(inStream.is_open()); - std::istream &instrm = static_cast(inStream); + auto &instrm = static_cast(inStream); factory = buildFeatureFactory(instrm); TEST_ASSERT(factory); TEST_ASSERT(factory->getNumFeatureDefs() == 2); diff --git a/Code/GraphMol/MolDiscriminators.cpp b/Code/GraphMol/MolDiscriminators.cpp index 795947396..9b2ca23bd 100644 --- a/Code/GraphMol/MolDiscriminators.cpp +++ b/Code/GraphMol/MolDiscriminators.cpp @@ -26,7 +26,9 @@ double computeBalabanJ(double *distMat, int nb, int nAts) { int nActive = nAts; int mu = nb - nActive + 1; - if (mu == -1) return 0.0; + if (mu == -1) { + return 0.0; + } for (int i = 0; i < nAts; i++) { int iTab = i * nAts; @@ -105,7 +107,9 @@ double computeBalabanJ(const ROMol &mol, bool useBO, bool force, delete[] dMat; } - if (cacheIt) mol.setProp(common_properties::BalabanJ, res, true); + if (cacheIt) { + mol.setProp(common_properties::BalabanJ, res, true); + } } return res; } diff --git a/Code/GraphMol/MolDraw2D/MolDraw2D.cpp b/Code/GraphMol/MolDraw2D/MolDraw2D.cpp index af7f036ea..63357d35c 100644 --- a/Code/GraphMol/MolDraw2D/MolDraw2D.cpp +++ b/Code/GraphMol/MolDraw2D/MolDraw2D.cpp @@ -43,7 +43,9 @@ void getBondHighlightsForAtoms(const ROMol &mol, for (auto ai = highlight_atoms.begin(); ai != highlight_atoms.end(); ++ai) { for (auto aj = ai + 1; aj != highlight_atoms.end(); ++aj) { const Bond *bnd = mol.getBondBetweenAtoms(*ai, *aj); - if (bnd) highlight_bonds.push_back(bnd->getIdx()); + if (bnd) { + highlight_bonds.push_back(bnd->getIdx()); + } } } } @@ -168,8 +170,9 @@ void MolDraw2D::drawMolecule(const ROMol &mol, activeMolIdx_++; int origWidth = curr_width_; - if (drawOptions().bondLineWidth >= 0) + if (drawOptions().bondLineWidth >= 0) { curr_width_ = drawOptions().bondLineWidth; + } if (!activeMolIdx_) { // on the first pass we need to do some work if (drawOptions().clearBackground) { @@ -414,7 +417,9 @@ void get2DCoordsForReaction(ChemicalReaction &rxn, const MolDrawOptions &opts, } ROMOL_SPTR reactant = rxn.getReactants()[midx]; int cid = -1; - if (confIds) cid = (*confIds)[midx]; + if (confIds) { + cid = (*confIds)[midx]; + } get2DCoordsMol(*(RWMol *)reactant.get(), offset, spacing, maxY, minY, cid, false, 1.0); } @@ -435,9 +440,10 @@ void get2DCoordsForReaction(ChemicalReaction &rxn, const MolDrawOptions &opts, } ROMOL_SPTR product = rxn.getProducts()[midx]; int cid = -1; - if (confIds) + if (confIds) { cid = (*confIds)[rxn.getNumReactantTemplates() + rxn.getNumAgentTemplates() + midx]; + } get2DCoordsMol(*(RWMol *)product.get(), offset, spacing, maxY, minY, cid, false, 1.0); } @@ -447,7 +453,9 @@ void get2DCoordsForReaction(ChemicalReaction &rxn, const MolDrawOptions &opts, for (unsigned int midx = 0; midx < rxn.getNumAgentTemplates(); ++midx) { ROMOL_SPTR agent = rxn.getAgents()[midx]; int cid = -1; - if (confIds) cid = (*confIds)[rxn.getNumReactantTemplates() + midx]; + if (confIds) { + cid = (*confIds)[rxn.getNumReactantTemplates() + midx]; + } get2DCoordsMol(*(RWMol *)agent.get(), offset, spacing, maxY, minY, cid, true, 0.45); } @@ -462,9 +470,10 @@ void get2DCoordsForReaction(ChemicalReaction &rxn, const MolDrawOptions &opts, for (unsigned int midx = 0; midx < rxn.getNumProductTemplates(); ++midx) { ROMOL_SPTR product = rxn.getProducts()[midx]; int cid = -1; - if (confIds) + if (confIds) { cid = (*confIds)[rxn.getNumReactantTemplates() + rxn.getNumAgentTemplates() + midx]; + } Conformer &conf = product->getConformer(cid); for (unsigned int aidx = 0; aidx < product->getNumAtoms(); ++aidx) { conf.getAtomPos(aidx).x += offset; @@ -655,7 +664,9 @@ void MolDraw2D::drawMolecules( PRECONDITION(!confIds || confIds->size() == mols.size(), "bad size"); PRECONDITION(panel_width_ != 0, "panel width cannot be zero"); PRECONDITION(panel_height_ != 0, "panel height cannot be zero"); - if (!mols.size()) return; + if (!mols.size()) { + return; + } std::vector tmols; tmols.reserve(mols.size()); @@ -668,8 +679,9 @@ void MolDraw2D::drawMolecules( continue; } tmols.push_back(*(mols[i])); - if (drawOptions().prepareMolsBeforeDrawing) + if (drawOptions().prepareMolsBeforeDrawing) { MolDraw2DUtils::prepareMolForDrawing(tmols[i]); + } Conformer &conf = tmols[i].getConformer(confIds ? (*confIds)[i] : -1); RDGeom::Point3D centroid = MolTransforms::computeCentroid(conf, false); for (unsigned int j = 0; j < conf.getNumAtoms(); ++j) { @@ -685,14 +697,20 @@ void MolDraw2D::drawMolecules( int nCols = width() / panelWidth(); int nRows = height() / panelHeight(); for (unsigned int i = 0; i < mols.size(); ++i) { - if (!mols[i]) continue; + if (!mols[i]) { + continue; + } int row = 0; // note that this also works when no panel size is specified since // the panel dimensions defaults to -1 - if (nRows > 1) row = i / nCols; + if (nRows > 1) { + row = i / nCols; + } int col = 0; - if (nCols > 1) col = i % nCols; + if (nCols > 1) { + col = i % nCols; + } setOffset(col * panelWidth(), row * panelHeight()); vector *lhighlight_bonds = nullptr; @@ -724,15 +742,21 @@ void MolDraw2D::drawMolecules( }; void MolDraw2D::highlightCloseContacts() { - if (drawOptions().flagCloseContactsDist < 0) return; + if (drawOptions().flagCloseContactsDist < 0) { + return; + } int tol = drawOptions().flagCloseContactsDist * drawOptions().flagCloseContactsDist; boost::dynamic_bitset<> flagged(at_cds_[activeMolIdx_].size()); for (unsigned int i = 0; i < at_cds_[activeMolIdx_].size(); ++i) { - if (flagged[i]) continue; + if (flagged[i]) { + continue; + } Point2D ci = getDrawCoords(at_cds_[activeMolIdx_][i]); for (unsigned int j = i + 1; j < at_cds_[activeMolIdx_].size(); ++j) { - if (flagged[j]) continue; + if (flagged[j]) { + continue; + } Point2D cj = getDrawCoords(at_cds_[activeMolIdx_][j]); double d = (cj - ci).lengthSq(); if (d <= tol) { @@ -787,9 +811,8 @@ Point2D MolDraw2D::getAtomCoords(const pair &screen_cds) const { } Point2D MolDraw2D::getAtomCoords(const pair &screen_cds) const { - double x = double(screen_cds.first / scale_ + x_min_ - x_trans_); - double y = - double(y_min_ - y_trans_ - (screen_cds.second - height()) / scale_); + auto x = double(screen_cds.first / scale_ + x_min_ - x_trans_); + auto y = double(y_min_ - y_trans_ - (screen_cds.second - height()) / scale_); return Point2D(x, y); } @@ -922,8 +945,12 @@ void MolDraw2D::calculateScale(int width, int height, double old_scale = scale_; x_range_ = x_max - x_min_; y_range_ = y_max - y_min_; - if (x_range_ < 1e-4) x_range_ = 1.; - if (y_range_ < 1e-4) y_range_ = 1.; + if (x_range_ < 1e-4) { + x_range_ = 1.; + } + if (y_range_ < 1e-4) { + y_range_ = 1.; + } scale_ = std::min(double(width) / x_range_, double(height) / y_range_); if (fabs(scale_ - old_scale) < 0.1) { break; @@ -1190,7 +1217,9 @@ void MolDraw2D::drawBond(const ROMol &mol, const Bond *bond, int at1_idx, // mol files from, for example, Marvin use a bond length of 1 for just about // everything. When this is the case, the default multipleBondOffset is just // too much, so scale it back. - if ((at1_cds - at2_cds).lengthSq() < 1.4) double_bond_offset *= 0.6; + if ((at1_cds - at2_cds).lengthSq() < 1.4) { + double_bond_offset *= 0.6; + } adjustBondEndForLabel(at1_idx, at2_cds, at1_cds); adjustBondEndForLabel(at2_idx, at1_cds, at2_cds); @@ -1329,9 +1358,13 @@ void MolDraw2D::drawBond(const ROMol &mol, const Bond *bond, int at1_idx, Point2D bv = at1_cds - at2_cds; Point2D p1 = at1_cds - bv * multipleBondTruncation + perp * dbo; Point2D p2 = at2_cds + bv * multipleBondTruncation + perp * dbo; - if (bt == Bond::AROMATIC) setDash(dashes); + if (bt == Bond::AROMATIC) { + setDash(dashes); + } drawLine(p1, p2, col1, col2); - if (bt == Bond::AROMATIC) setDash(noDash); + if (bt == Bond::AROMATIC) { + setDash(noDash); + } } } } @@ -1350,7 +1383,9 @@ void MolDraw2D::drawWedgedBond(const Point2D &cds1, const Point2D &cds2, // (part of github #985) // the constants are empirical to make sure that the wedge is visible, but // not absurdly large. - if (scale_ > 40) disp *= .6; + if (scale_ > 40) { + disp *= .6; + } Point2D end1 = cds2 + disp; Point2D end2 = cds2 - disp; @@ -1359,7 +1394,9 @@ void MolDraw2D::drawWedgedBond(const Point2D &cds1, const Point2D &cds2, unsigned int nDashes = 10; // empirical cutoff to make sure we don't have too many dashes in the // wedge: - if ((cds1 - cds2).lengthSq() < 1.0) nDashes /= 2; + if ((cds1 - cds2).lengthSq() < 1.0) { + nDashes /= 2; + } int orig_lw = lineWidth(); int tgt_lw = 1; // use the minimum line width diff --git a/Code/GraphMol/MolDraw2D/MolDraw2DCairo.cpp b/Code/GraphMol/MolDraw2D/MolDraw2DCairo.cpp index bd7f3516a..5dead73da 100644 --- a/Code/GraphMol/MolDraw2D/MolDraw2DCairo.cpp +++ b/Code/GraphMol/MolDraw2D/MolDraw2DCairo.cpp @@ -44,7 +44,7 @@ void MolDraw2DCairo::drawLine(const Point2D &cds1, const Point2D &cds2) { const DashPattern &dashes = dash(); if (dashes.size()) { - double *dd = new double[dashes.size()]; + auto *dd = new double[dashes.size()]; std::copy(dashes.begin(), dashes.end(), dd); cairo_set_dash(dp_cr, dd, dashes.size(), 0); delete[] dd; @@ -65,8 +65,9 @@ void MolDraw2DCairo::drawWavyLine(const Point2D &cds1, const Point2D &cds2, PRECONDITION(nSegments > 1, "too few segments"); RDUNUSED_PARAM(col2); - if (nSegments % 2) + if (nSegments % 2) { ++nSegments; // we're going to assume an even number of segments + } Point2D perp = calcPerpendicular(cds1, cds2); Point2D delta = (cds2 - cds1); @@ -124,14 +125,17 @@ void MolDraw2DCairo::drawPolygon(const std::vector &cds) { for (unsigned int i = 0; i < cds.size(); ++i) { Point2D lc = getDrawCoords(cds[i]); - if (!i) + if (!i) { cairo_move_to(dp_cr, lc.x, lc.y); - else + } else { cairo_line_to(dp_cr, lc.x, lc.y); + } } cairo_close_path(dp_cr); - if (fillPolys()) cairo_fill_preserve(dp_cr); + if (fillPolys()) { + cairo_fill_preserve(dp_cr); + } cairo_stroke(dp_cr); cairo_set_line_cap(dp_cr, olinecap); cairo_set_line_join(dp_cr, olinejoin); @@ -204,7 +208,7 @@ void MolDraw2DCairo::getStringSize(const std::string &label, namespace { cairo_status_t grab_str(void *closure, const unsigned char *data, unsigned int len) { - std::string *str_ptr = (std::string *)closure; + auto *str_ptr = (std::string *)closure; (*str_ptr) += std::string((const char *)data, len); return CAIRO_STATUS_SUCCESS; } diff --git a/Code/GraphMol/MolDraw2D/MolDraw2DDetails.cpp b/Code/GraphMol/MolDraw2D/MolDraw2DDetails.cpp index b93535762..eee38e61e 100644 --- a/Code/GraphMol/MolDraw2D/MolDraw2DDetails.cpp +++ b/Code/GraphMol/MolDraw2D/MolDraw2DDetails.cpp @@ -24,8 +24,12 @@ void arcPoints(const Point2D &cds1, const Point2D &cds2, // Note: this implementation is simple and not particularly efficient. float xScale = (cds2.x - cds1.x) / 2.0; float yScale = (cds2.y - cds1.y) / 2.0; - if (xScale < 0) xScale *= -1; - if (yScale < 0) yScale *= -1; + if (xScale < 0) { + xScale *= -1; + } + if (yScale < 0) { + yScale *= -1; + } float x = std::min(cds1.x, cds2.x) + xScale; float y = std::min(cds1.y, cds2.y) + yScale; diff --git a/Code/GraphMol/MolDraw2D/MolDraw2DSVG.cpp b/Code/GraphMol/MolDraw2D/MolDraw2DSVG.cpp index 7c3c935b0..1ad8f20dd 100644 --- a/Code/GraphMol/MolDraw2D/MolDraw2DSVG.cpp +++ b/Code/GraphMol/MolDraw2D/MolDraw2DSVG.cpp @@ -28,21 +28,24 @@ std::string DrawColourToSVG(const DrawColour &col) { unsigned int v; unsigned int i = 1; v = int(255 * col.r); - if (v > 255) + if (v > 255) { throw ValueErrorException( "elements of the color should be between 0 and 1"); + } res[i++] = convert[v / 16]; res[i++] = convert[v % 16]; v = int(255 * col.g); - if (v > 255) + if (v > 255) { throw ValueErrorException( "elements of the color should be between 0 and 1"); + } res[i++] = convert[v / 16]; res[i++] = convert[v % 16]; v = int(255 * col.b); - if (v > 255) + if (v > 255) { throw ValueErrorException( "elements of the color should be between 0 and 1"); + } res[i++] = convert[v / 16]; res[i++] = convert[v % 16]; return res; @@ -81,8 +84,9 @@ void MolDraw2DSVG::drawWavyLine(const Point2D &cds1, const Point2D &cds2, PRECONDITION(nSegments > 1, "too few segments"); RDUNUSED_PARAM(col2); - if (nSegments % 2) + if (nSegments % 2) { ++nSegments; // we're going to assume an even number of segments + } setColour(col1); Point2D perp = calcPerpendicular(cds1, cds2); @@ -125,7 +129,9 @@ void MolDraw2DSVG::drawBond( const std::map *highlight_bond_map) { PRECONDITION(bond, "bad bond"); std::string o_class = d_activeClass; - if (d_activeClass != "") d_activeClass += " "; + if (d_activeClass != "") { + d_activeClass += " "; + } d_activeClass += boost::str(boost::format("bond-%d") % bond->getIdx()); MolDraw2D::drawBond(mol, bond, at1_idx, at2_idx, highlight_atoms, highlight_atom_map, highlight_bonds, highlight_bond_map); @@ -199,11 +205,12 @@ void MolDraw2DSVG::drawPolygon(const std::vector &cds) { } d_os << " Z"; d_os << "' style='"; - if (fillPolys()) + if (fillPolys()) { d_os << "fill:" << col << ";fill-rule:evenodd;fill-opacity=" << colour().a << ";"; - else + } else { d_os << "fill:none;"; + } d_os << "stroke:" << col << ";stroke-width:" << width << "px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:" @@ -234,10 +241,11 @@ void MolDraw2DSVG::drawEllipse(const Point2D &cds1, const Point2D &cds2) { d_os << " class='" << d_activeClass << "'"; } d_os << " style='"; - if (fillPolys()) + if (fillPolys()) { d_os << "fill:" << col << ";fill-rule:evenodd;"; - else + } else { d_os << "fill:none;"; + } d_os << "stroke:" << col << ";stroke-width:" << width << "px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" @@ -421,10 +429,11 @@ void MolDraw2DSVG::addMoleculeMetadata(const ROMol &mol, int confId) const { RDGeom::Point3D pos = conf.getAtomPos(atom->getIdx()); Point2D dpos(pos.x, pos.y); - if (atom->hasProp(tag)) + if (atom->hasProp(tag)) { dpos = atom->getProp(tag); - else + } else { dpos = getDrawCoords(dpos); + } d_os << " drawing-x=\"" << dpos.x << "\"" << " drawing-y=\"" << dpos.y << "\""; d_os << " x=\"" << pos.x << "\"" @@ -450,7 +459,9 @@ void MolDraw2DSVG::addMoleculeMetadata(const std::vector &mols, const std::vector confIds) const { for (unsigned int i = 0; i < mols.size(); ++i) { int confId = -1; - if (confIds.size() == mols.size()) confId = confIds[i]; + if (confIds.size() == mols.size()) { + confId = confIds[i]; + } addMoleculeMetadata(*(mols[i]), confId); } }; diff --git a/Code/GraphMol/MolDraw2D/MolDraw2DUtils.cpp b/Code/GraphMol/MolDraw2D/MolDraw2DUtils.cpp index a6ffd6a9b..b4a0084ba 100644 --- a/Code/GraphMol/MolDraw2D/MolDraw2DUtils.cpp +++ b/Code/GraphMol/MolDraw2D/MolDraw2DUtils.cpp @@ -58,7 +58,9 @@ void prepareMolForDrawing(RWMol &mol, bool kekulize, bool addChiralHs, } if (chiralAts.size()) { bool addCoords = false; - if (!forceCoords && mol.getNumConformers()) addCoords = true; + if (!forceCoords && mol.getNumConformers()) { + addCoords = true; + } MolOps::addHs(mol, false, addCoords, &chiralAts); } } @@ -96,7 +98,9 @@ void updateDrawerParamsFromJSON(MolDraw2D &drawer, const char *json) { void get_colour_option(boost::property_tree::ptree *pt, const char *pnm, DrawColour &colour) { PRECONDITION(pnm && strlen(pnm), "bad property name"); - if (pt->find(pnm) == pt->not_found()) return; + if (pt->find(pnm) == pt->not_found()) { + return; + } boost::property_tree::ptree::const_iterator itm = pt->get_child(pnm).begin(); colour.r = itm->second.get_value(); @@ -108,7 +112,9 @@ void get_colour_option(boost::property_tree::ptree *pt, const char *pnm, } void updateDrawerParamsFromJSON(MolDraw2D &drawer, const std::string &json) { - if (json == "") return; + if (json == "") { + return; + } std::istringstream ss; ss.str(json); MolDrawOptions &opts = drawer.drawOptions(); @@ -170,7 +176,9 @@ void contourAndDrawGrid(MolDraw2D &drawer, const double *grid, } } } - if (maxV <= minV) return; + if (maxV <= minV) { + return; + } const auto olw = drawer.lineWidth(); const auto odash = drawer.dash(); @@ -183,10 +191,11 @@ void contourAndDrawGrid(MolDraw2D &drawer, const double *grid, auto delta = (maxV - minV); if (params.colourMap.size() > 2) { // need to find how fractionally far we are from zero, not the min - if (-minV > maxV) + if (-minV > maxV) { delta = -minV; - else + } else { delta = maxV; + } } for (size_t i = 0; i < nX - 1; ++i) { for (size_t j = 0; j < nY - 1; ++j) { @@ -195,7 +204,9 @@ void contourAndDrawGrid(MolDraw2D &drawer, const double *grid, if (params.colourMap.size() > 2) { // need to find how fractionally far we are from zero, not the min fracV = gridV / delta; - if (fracV < 0) fracV *= -1; + if (fracV < 0) { + fracV *= -1; + } } DrawColour fillColour; auto c1 = (gridV < 0 || params.colourMap.size() == 2) diff --git a/Code/GraphMol/MolDraw2D/Wrap/rdMolDraw2D.cpp b/Code/GraphMol/MolDraw2D/Wrap/rdMolDraw2D.cpp index 23796d906..b3c8cb10f 100644 --- a/Code/GraphMol/MolDraw2D/Wrap/rdMolDraw2D.cpp +++ b/Code/GraphMol/MolDraw2D/Wrap/rdMolDraw2D.cpp @@ -385,7 +385,7 @@ void contourAndDrawGridHelper(RDKit::MolDraw2D &drawer, python::object &data, if (!PyArray_Check(data.ptr())) { throw_value_error("data argument must be a numpy array"); } - PyArrayObject *dataArr = reinterpret_cast( + auto *dataArr = reinterpret_cast( PyArray_ContiguousFromObject(data.ptr(), NPY_DOUBLE, 2, 2)); if (!dataArr) { throw_value_error("could not convert data argument"); diff --git a/Code/GraphMol/MolDraw2D/catch_tests.cpp b/Code/GraphMol/MolDraw2D/catch_tests.cpp index d2b76af6b..7a3a878b8 100644 --- a/Code/GraphMol/MolDraw2D/catch_tests.cpp +++ b/Code/GraphMol/MolDraw2D/catch_tests.cpp @@ -67,7 +67,7 @@ TEST_CASE("contour data", "[drawing, conrec]") { MolDraw2DUtils::prepareMolForDrawing(*m1); const size_t gridSz = 100; - double *grid = new double[gridSz * gridSz]; + auto *grid = new double[gridSz * gridSz]; std::vector xps(gridSz); std::vector yps(gridSz); @@ -87,14 +87,18 @@ TEST_CASE("contour data", "[drawing, conrec]") { xps[ix] = px; for (size_t iy = 0; iy < gridSz; ++iy) { auto py = y1 + iy * dy; - if (ix == 0) yps[iy] = py; + if (ix == 0) { + yps[iy] = py; + } RDGeom::Point2D loc(px, py); double val = 0.0; for (size_t ia = 0; ia < conf.getNumAtoms(); ++ia) { auto dv = loc - RDGeom::Point2D(conf.getAtomPos(ia).x, conf.getAtomPos(ia).y); auto r = dv.length(); - if (r > 0.1) val += 1 / r; + if (r > 0.1) { + val += 1 / r; + } } maxV = std::max(val, maxV); grid[ix * gridSz + iy] = val; diff --git a/Code/GraphMol/MolDraw2D/test1.cpp b/Code/GraphMol/MolDraw2D/test1.cpp index 74b3a5604..d085702e1 100644 --- a/Code/GraphMol/MolDraw2D/test1.cpp +++ b/Code/GraphMol/MolDraw2D/test1.cpp @@ -561,7 +561,9 @@ void runblock(const std::vector &mols, unsigned int idx) { for (unsigned int j = 0; j < 200; j++) { for (unsigned int i = 0; i < mols.size(); ++i) { - if (i % count != idx) continue; + if (i % count != idx) { + continue; + } ROMol *mol = mols[i]; MolDraw2DSVG drawer(300, 300); drawer.drawMolecule(*mol); @@ -587,7 +589,9 @@ void testMultiThreaded() { } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } mols.push_back(mol); } @@ -1341,11 +1345,14 @@ void testDeuteriumTritium() { std::string line; std::getline(ins, line); ok = (ins.good() && !ins.eof()); - if (!ok) continue; + if (!ok) { + continue; + } if ((line.find("baseline-shift:super") != std::string::npos) && (line.find(">2<") != std::string::npos) && - (line.find(">H<") != std::string::npos)) + (line.find(">H<") != std::string::npos)) { ++count; + } } TEST_ASSERT(count == 4); delete m; @@ -1368,11 +1375,14 @@ void testDeuteriumTritium() { std::string line; std::getline(ins, line); ok = (ins.good() && !ins.eof()); - if (!ok) continue; + if (!ok) { + continue; + } if ((line.find("baseline-shift:super") != std::string::npos) && (line.find(">3<") != std::string::npos) && - (line.find(">H<") != std::string::npos)) + (line.find(">H<") != std::string::npos)) { ++count; + } } TEST_ASSERT(count == 4); delete m; @@ -1395,11 +1405,14 @@ void testDeuteriumTritium() { std::string line; std::getline(ins, line); ok = (ins.good() && !ins.eof()); - if (!ok) continue; + if (!ok) { + continue; + } if ((line.find("baseline-shift:super") == std::string::npos) && (line.find(">2<") == std::string::npos) && - (line.find(">D<") != std::string::npos)) + (line.find(">D<") != std::string::npos)) { ++count; + } } TEST_ASSERT(count == 4); delete m; @@ -1422,11 +1435,14 @@ void testDeuteriumTritium() { std::string line; std::getline(ins, line); ok = (ins.good() && !ins.eof()); - if (!ok) continue; + if (!ok) { + continue; + } if ((line.find("baseline-shift:super") == std::string::npos) && (line.find(">3<") == std::string::npos) && - (line.find(">T<") != std::string::npos)) + (line.find(">T<") != std::string::npos)) { ++count; + } } TEST_ASSERT(count == 4); delete m; @@ -2171,7 +2187,7 @@ void test16MoleculeMetadata() { #if 1 { // multiple molecules MolDraw2DSVG drawer(400, 400, 200, 200); - ROMol *rom = rdcast(m1.get()); + auto *rom = rdcast(m1.get()); std::vector ms = {new ROMol(*rom), new ROMol(*rom), new ROMol(*rom), new ROMol(*rom)}; drawer.drawMolecules(ms); @@ -2187,7 +2203,9 @@ void test16MoleculeMetadata() { std::ofstream outs("test16_2.svg"); outs << text; outs.flush(); - for (auto ptr : ms) delete ptr; + for (auto ptr : ms) { + delete ptr; + } } #endif } diff --git a/Code/GraphMol/MolHash/MolHash.cpp b/Code/GraphMol/MolHash/MolHash.cpp index 49d7befb6..666334714 100644 --- a/Code/GraphMol/MolHash/MolHash.cpp +++ b/Code/GraphMol/MolHash/MolHash.cpp @@ -75,23 +75,28 @@ void fillAtomBondCodes( } const Atom *atom = mol.getAtomWithIdx(i); (*atomCodes)[i] = 0; - if (0 != (CF_ELEMENT & flags)) (*atomCodes)[i] |= atom->getAtomicNum(); - if (0 != (CF_CHARGE & flags)) + if (0 != (CF_ELEMENT & flags)) { + (*atomCodes)[i] |= atom->getAtomicNum(); + } + if (0 != (CF_CHARGE & flags)) { (*atomCodes)[i] |= (atom->getFormalCharge() + 8) << 8; // allowed range [-8, +8] - if (0 != (CF_VALENCE & flags)) + } + if (0 != (CF_VALENCE & flags)) { (*atomCodes)[i] |= (atom->getExplicitValence()) << 13; // getTotalValence() + } if (0 != (CF_ATOM_CHIRALITY & flags)) { char v = 0; if (atom->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW || atom->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW) { if (atom->hasProp("_CIPCode")) { std::string code = atom->getProp("_CIPCode"); - if (code == "R") + if (code == "R") { v = 1; - else if (code == "S") + } else if (code == "S") { v = 2; + } } else if (atom->hasProp("_ringStereoAtoms")) { const INT_VECT &ringStereoAtoms = atom->getProp("_ringStereoAtoms"); @@ -113,23 +118,27 @@ void fillAtomBondCodes( } (*atomCodes)[i] |= v << 18; // 2 bits } - if (0 != (CF_ATOM_AROMATIC & flags)) + if (0 != (CF_ATOM_AROMATIC & flags)) { (*atomCodes)[i] |= (atom->getIsAromatic() ? 1 : 0) << 20; // 1 bit + } // if(0!=( & flags)) // (*atomCodes)[i] |= (atom-()) << 21; // 3 bits reserved - if (0 != (CF_ISOTOPE & flags)) + if (0 != (CF_ISOTOPE & flags)) { (*atomCodes)[i] |= (atom->getIsotope()) << 24; + } } } if (bondCodes) { std::map bondsInRing; const RingInfo::VECT_INT_VECT &rings = mol.getRingInfo()->bondRings(); - for (const auto &ring : rings) - for (int b : ring) - if (bondsInRing.end() == bondsInRing.find(b)) + for (const auto &ring : rings) { + for (int b : ring) { + if (bondsInRing.end() == bondsInRing.find(b)) { bondsInRing[(unsigned)b] = true; - + } + } + } unsigned n = mol.getNumBonds(); bondCodes->resize(n); for (unsigned i = 0; i < n; i++) { @@ -161,15 +170,17 @@ void fillAtomBondCodes( } (*bondCodes)[i] |= order; } - if (0 != (CF_BOND_AROMATIZATION & flags)) + if (0 != (CF_BOND_AROMATIZATION & flags)) { (*bondCodes)[i] |= ((bond->getIsAromatic() ? 1 : 0)) << 8; + } if (0 != (CF_BOND_CHIRALITY & flags)) { (*bondCodes)[i] |= bond->getStereo() << 9; } - if (0 != (CF_BOND_IN_RING & flags)) + if (0 != (CF_BOND_IN_RING & flags)) { (*bondCodes)[i] |= (bondsInRing.end() != bondsInRing.find(bond->getIdx()) ? 1 : 0) << 11; // 1 bit + } } } } @@ -183,7 +194,9 @@ HashCodeType generateMoleculeHashCode( const std::vector *bondCodes) { MolFragment m; prepareMolFragment(m, mol, atomsToUse, bondsToUse); - if (0 == m.getNumAtoms() || 0 == m.getNumBonds()) return 0; + if (0 == m.getNumAtoms() || 0 == m.getNumBonds()) { + return 0; + } std::vector atomLabels; std::vector bondLabels; prepareLabels(atomLabels, bondLabels, mol, m, atomCodes, bondCodes); @@ -201,7 +214,9 @@ void generateMoleculeHashSet(const ROMol &mol, HashSet &res, res.NumAtoms = m.getNumAtoms(); res.NumBonds = m.getNumBonds(); - if (0 == m.getNumAtoms() || 0 == m.getNumBonds()) return; + if (0 == m.getNumAtoms() || 0 == m.getNumBonds()) { + return; + } std::string formula = RDKit::Descriptors::calcMolFormula(mol); res.FormulaCRC32 = computeCRC32(formula.c_str(), formula.length()); @@ -277,13 +292,18 @@ static HashCodeType computeMorganCodeHash( std::vector currCodes(nv); std::vector prevCodes(nv); size_t nIterations = mol.getNumBonds(); - if (nIterations > 5) nIterations = 5; + if (nIterations > 5) { + nIterations = 5; + } - for (unsigned molAtomIdx = 0; molAtomIdx < mol.getNumAtoms(); molAtomIdx++) + for (unsigned molAtomIdx = 0; molAtomIdx < mol.getNumAtoms(); molAtomIdx++) { currCodes[molAtomIdx] = atomLabels[mol.AtomsIdx[molAtomIdx]]; + } for (size_t iter = 0; iter < nIterations; iter++) { - for (size_t i = 0; i < nv; i++) prevCodes[i] = currCodes[i]; + for (size_t i = 0; i < nv; i++) { + prevCodes[i] = currCodes[i]; + } for (size_t molBondIdx = 0; molBondIdx < ne; molBondIdx++) { const Bond *bond = mol.Bonds[molBondIdx]; @@ -309,26 +329,35 @@ static HashCodeType computeMorganCodeHash( static void prepareMolFragment(MolFragment &m, const ROMol &mol, const std::vector *atomsToUse, const std::vector *bondsToUse) { - if (nullptr != atomsToUse && atomsToUse->empty()) atomsToUse = nullptr; - if (nullptr != bondsToUse && bondsToUse->empty()) bondsToUse = nullptr; + if (nullptr != atomsToUse && atomsToUse->empty()) { + atomsToUse = nullptr; + } + if (nullptr != bondsToUse && bondsToUse->empty()) { + bondsToUse = nullptr; + } if (nullptr == atomsToUse && nullptr == bondsToUse) // whole molecule { unsigned n = mol.getNumAtoms(); m.AtomsIdx.resize(n); - for (unsigned i = 0; i < n; i++) m.AtomsIdx[i] = i; + for (unsigned i = 0; i < n; i++) { + m.AtomsIdx[i] = i; + } n = mol.getNumBonds(); m.BondsIdx.resize(n); - for (unsigned i = 0; i < n; i++) m.BondsIdx[i] = i; + for (unsigned i = 0; i < n; i++) { + m.BondsIdx[i] = i; + } } else if (nullptr != atomsToUse) // selected atoms only and all/selected // bonds between them { std::map addedBonds; unsigned n = atomsToUse->size(); m.AtomsIdx.resize(n); - for (unsigned i = 0; i < n; i++) // add all selected atoms at first + for (unsigned i = 0; i < n; i++) { // add all selected atoms at first m.AtomsIdx[i] = (*atomsToUse)[i]; + } for (unsigned i = 0; i < n; i++) // add bonds between all selected atoms { @@ -337,12 +366,14 @@ static void prepareMolFragment(MolFragment &m, const ROMol &mol, mol.getAtomBonds(mol.getAtomWithIdx(m.AtomsIdx[i])); beg != end; beg++) { const Bond *bond = &*((mol)[*beg]); - if (addedBonds.end() != addedBonds.find(bond->getIdx())) + if (addedBonds.end() != addedBonds.find(bond->getIdx())) { continue; // the bond has been already added + } if (nullptr != bondsToUse && bondsToUse->end() == - find(bondsToUse->begin(), bondsToUse->end(), bond->getIdx())) + find(bondsToUse->begin(), bondsToUse->end(), bond->getIdx())) { continue; // skip unselected bond + } unsigned endAtoms[2]; endAtoms[0] = bond->getBeginAtomIdx(); @@ -352,10 +383,11 @@ static void prepareMolFragment(MolFragment &m, const ROMol &mol, { if (nullptr != atomsToUse && atomsToUse->end() == - find(atomsToUse->begin(), atomsToUse->end(), endAtoms[ai])) + find(atomsToUse->begin(), atomsToUse->end(), endAtoms[ai])) { bond = nullptr; // check if both ending atoms of the bond are - // selected by - // atoms filter + } + // selected by + // atoms filter } if (nullptr != bond) { addedBonds[bond->getIdx()] = m.BondsIdx.size(); @@ -375,13 +407,12 @@ static void prepareMolFragment(MolFragment &m, const ROMol &mol, unsigned endAtoms[2]; endAtoms[0] = bond->getBeginAtomIdx(); endAtoms[1] = bond->getEndAtomIdx(); - for (unsigned ai = 0; ai < 2; ai++) // both ending bonds of the atom + for (unsigned int endAtom : endAtoms) // both ending bonds of the atom { - if (addedAtoms.end() == addedAtoms.find(endAtoms[ai])) { + if (addedAtoms.end() == addedAtoms.find(endAtom)) { auto val = addedAtoms.size(); - addedAtoms[endAtoms[ai]] = val; - m.AtomsIdx.push_back( - endAtoms[ai]); // the atom has NOT been already added + addedAtoms[endAtom] = val; + m.AtomsIdx.push_back(endAtom); // the atom has NOT been already added } } } diff --git a/Code/GraphMol/MolHash/hashfunctions.cpp b/Code/GraphMol/MolHash/hashfunctions.cpp index 4a56fd891..73690ce15 100644 --- a/Code/GraphMol/MolHash/hashfunctions.cpp +++ b/Code/GraphMol/MolHash/hashfunctions.cpp @@ -83,15 +83,18 @@ RDKit::Bond *NMRDKitMolNewBond(RDKit::RWMol *mol, RDKit::Atom *src, type = RDKit::Bond::QUADRUPLE; break; } - } else + } else { type = RDKit::Bond::AROMATIC; + } result = new RDKit::Bond(type); result->setOwningMol(mol); result->setBeginAtom(src); result->setEndAtom(dst); mol->addBond(result, true); - if (arom) result->setIsAromatic(true); + if (arom) { + result->setIsAromatic(true); + } return result; } @@ -155,10 +158,11 @@ static std::string NMMolecularFormula(RWMol *mol, const unsigned int *parts, unsigned int idx = aptr->getIdx(); if (part == 0 || parts[idx] == part) { unsigned int elem = aptr->getAtomicNum(); - if (elem < 256) + if (elem < 256) { hist[elem]++; - else + } else { hist[0]++; + } hist[1] += aptr->getTotalNumHs(false); charge += aptr->getFormalCharge(); } @@ -197,20 +201,25 @@ static std::string NMMolecularFormula(RWMol *mol, const unsigned int *parts, static std::string NMMolecularFormula(RWMol *mol, bool sep = false) { PRECONDITION(mol, "bad molecule"); - if (!sep) return NMMolecularFormula(mol, 0, 0); + if (!sep) { + return NMMolecularFormula(mol, nullptr, 0); + } unsigned int acount = mol->getNumAtoms(); - if (acount == 0) return ""; + if (acount == 0) { + return ""; + } - unsigned int size = (unsigned int)(acount * sizeof(int)); - unsigned int *parts = (unsigned int *)malloc(size); + auto size = (unsigned int)(acount * sizeof(int)); + auto *parts = (unsigned int *)malloc(size); unsigned int pcount = NMDetermineComponents(mol, parts, acount); std::string result; if (pcount > 1) { std::vector vmf; - for (unsigned int i = 1; i <= pcount; i++) + for (unsigned int i = 1; i <= pcount; i++) { vmf.push_back(NMMolecularFormula(mol, parts, i)); + } // sort result = vmf[0]; @@ -218,8 +227,9 @@ static std::string NMMolecularFormula(RWMol *mol, bool sep = false) { result += "."; result += vmf[i]; } - } else // pcount == 1 + } else { // pcount == 1 result = NMMolecularFormula(mol, parts, 1); + } free(parts); return result; } @@ -248,12 +258,13 @@ static void NormalizeHCount(Atom *aptr) { case 7: // Nitogen case 15: // Phosphorus hcount = aptr->getDegree(); - if (hcount < 3) + if (hcount < 3) { hcount = 3 - hcount; - else if (hcount == 4) + } else if (hcount == 4) { hcount = 1; - else + } else { hcount = 0; + } break; case 6: // Carbon hcount = aptr->getDegree(); @@ -354,8 +365,9 @@ static std::string TautomerHash(RWMol *mol, bool proto) { result = MolToSmiles(*mol); if (!proto) { sprintf(buffer, "_%d_%d", hcount, charge); - } else + } else { sprintf(buffer, "_%d", hcount - charge); + } result += buffer; return result; } @@ -368,9 +380,13 @@ static bool TraverseForRing(Atom *atom, unsigned char *visit) { atom->getOwningMol().getAtomNeighbors(atom))) { auto nptr = atom->getOwningMol()[nbri]; if (visit[nptr->getIdx()] == 0) { - if (RDKit::queryIsAtomInRing(nptr)) return true; + if (RDKit::queryIsAtomInRing(nptr)) { + return true; + } - if (TraverseForRing(nptr, visit)) return true; + if (TraverseForRing(nptr, visit)) { + return true; + } } } return false; @@ -382,7 +398,7 @@ static bool DepthFirstSearchForRing(Atom *root, Atom *nbor, PRECONDITION(nbor, "bad atom pointer"); unsigned int natoms = maxatomidx; - unsigned char *visit = (unsigned char *)alloca(natoms); + auto *visit = (unsigned char *)alloca(natoms); memset(visit, 0, natoms); visit[root->getIdx()] = true; @@ -391,13 +407,17 @@ static bool DepthFirstSearchForRing(Atom *root, Atom *nbor, bool IsInScaffold(Atom *atom, unsigned int maxatomidx) { PRECONDITION(atom, "bad atom pointer"); - if (RDKit::queryIsAtomInRing(atom)) return true; + if (RDKit::queryIsAtomInRing(atom)) { + return true; + } unsigned int count = 0; for (auto nbri : boost::make_iterator_range( atom->getOwningMol().getAtomNeighbors(atom))) { auto nptr = atom->getOwningMol()[nbri]; - if (DepthFirstSearchForRing(atom, nptr, maxatomidx)) ++count; + if (DepthFirstSearchForRing(atom, nptr, maxatomidx)) { + ++count; + } } return count > 1; } @@ -408,7 +428,9 @@ static bool HasNbrInScaffold(Atom *aptr, unsigned char *is_in_scaffold) { for (auto nbri : boost::make_iterator_range( aptr->getOwningMol().getAtomNeighbors(aptr))) { auto nptr = aptr->getOwningMol()[nbri]; - if (is_in_scaffold[nptr->getIdx()]) return true; + if (is_in_scaffold[nptr->getIdx()]) { + return true; + } } return false; } @@ -418,7 +440,7 @@ static std::string ExtendedMurckoScaffold(RWMol *mol) { RDKit::MolOps::fastFindRings(*mol); unsigned int maxatomidx = mol->getNumAtoms(); - unsigned char *is_in_scaffold = (unsigned char *)alloca(maxatomidx); + auto *is_in_scaffold = (unsigned char *)alloca(maxatomidx); for (auto aptr : mol->atoms()) { is_in_scaffold[aptr->getIdx()] = IsInScaffold(aptr, maxatomidx); } @@ -426,7 +448,9 @@ static std::string ExtendedMurckoScaffold(RWMol *mol) { std::vector for_deletion; for (auto aptr : mol->atoms()) { unsigned int aidx = aptr->getIdx(); - if (is_in_scaffold[aidx]) continue; + if (is_in_scaffold[aidx]) { + continue; + } if (HasNbrInScaffold(aptr, is_in_scaffold)) { aptr->setAtomicNum(0); aptr->setFormalCharge(0); @@ -437,8 +461,9 @@ static std::string ExtendedMurckoScaffold(RWMol *mol) { } } - for (unsigned int i = 0; i < for_deletion.size(); ++i) - mol->removeAtom(for_deletion[i]); + for (auto &i : for_deletion) { + mol->removeAtom(i); + } MolOps::assignRadicals(*mol); std::string result; @@ -467,8 +492,8 @@ static std::string MurckoScaffoldHash(RWMol *mol) { for_deletion.push_back(aptr); } } - for (unsigned int i = 0; i < for_deletion.size(); ++i) { - mol->removeAtom(for_deletion[i]); + for (auto &i : for_deletion) { + mol->removeAtom(i); } } while (!for_deletion.empty()); MolOps::assignRadicals(*mol); @@ -501,7 +526,9 @@ static std::string SmallWorldHash(RWMol *mol, bool brl) { if (brl) { unsigned int lcount = 0; for (auto aptr : mol->atoms()) { - if (aptr->getDegree() == 2) lcount++; + if (aptr->getDegree() == 2) { + lcount++; + } } sprintf(buffer, "B%uR%uL%u", bcount, rcount, lcount); } else { @@ -535,7 +562,9 @@ static bool HasDoubleBond(Atom *atom) { for (const auto &nbri : boost::make_iterator_range(atom->getOwningMol().getAtomBonds(atom))) { auto bptr = (atom->getOwningMol())[nbri]; - if (NMRDKitBondGetOrder(bptr) == 2) return true; + if (NMRDKitBondGetOrder(bptr) == 2) { + return true; + } } return false; } @@ -549,24 +578,38 @@ static bool HasDoubleBond(Atom *atom) { static int RegioisomerBond(Bond *bnd) { PRECONDITION(bnd, "bad bond"); - if (NMRDKitBondGetOrder(bnd) != 1) return -1; - if (RDKit::queryIsBondInRing(bnd)) return -1; + if (NMRDKitBondGetOrder(bnd) != 1) { + return -1; + } + if (RDKit::queryIsBondInRing(bnd)) { + return -1; + } Atom *beg = bnd->getBeginAtom(); Atom *end = bnd->getEndAtom(); unsigned int beg_elem = beg->getAtomicNum(); unsigned int end_elem = end->getAtomicNum(); - if (beg_elem == 0 || end_elem == 0) return -1; + if (beg_elem == 0 || end_elem == 0) { + return -1; + } if (RDKit::queryIsAtomInRing(beg)) { - if (RDKit::queryIsAtomInRing(end)) return 0; + if (RDKit::queryIsAtomInRing(end)) { + return 0; + } return 2; } - if (RDKit::queryIsAtomInRing(end)) return 1; + if (RDKit::queryIsAtomInRing(end)) { + return 1; + } - if (beg_elem != 6 && end_elem == 6 && !HasDoubleBond(end)) return 1; - if (beg_elem == 6 && end_elem != 6 && !HasDoubleBond(beg)) return 2; + if (beg_elem != 6 && end_elem == 6 && !HasDoubleBond(end)) { + return 1; + } + if (beg_elem == 6 && end_elem != 6 && !HasDoubleBond(beg)) { + return 2; + } return -1; } @@ -576,8 +619,9 @@ static void ClearEZStereo(Atom *atm) { for (const auto &nbri : boost::make_iterator_range(atm->getOwningMol().getAtomBonds(atm))) { auto bptr = (atm->getOwningMol())[nbri]; - if (bptr->getStereo() > RDKit::Bond::STEREOANY) + if (bptr->getStereo() > RDKit::Bond::STEREOANY) { bptr->setStereo(RDKit::Bond::STEREOANY); + } } } @@ -636,7 +680,7 @@ static std::string ArthorSubOrderHash(RWMol *mol) { unsigned int pcount = 1; unsigned int size = 4 * mol->getNumAtoms() + 4; - unsigned int *parts = (unsigned int *)malloc(size); + auto *parts = (unsigned int *)malloc(size); if (parts) { memset(parts, 0, size); pcount = NMDetermineComponents(mol, parts, acount); @@ -656,23 +700,31 @@ static std::string ArthorSubOrderHash(RWMol *mol) { switch (elem) { case 6: // Carbon ccount++; - if (charge == 0 && aptr->getTotalValence() != 4) rcount++; + if (charge == 0 && aptr->getTotalValence() != 4) { + rcount++; + } break; case 7: // Nitrogen case 15: // Phosphorus ocount++; if (charge == 0) { unsigned int valence = aptr->getTotalValence(); - if (valence != 3 && valence != 5) rcount++; + if (valence != 3 && valence != 5) { + rcount++; + } } break; case 8: // Oxygen ocount++; - if (charge && aptr->getTotalValence() != 2) rcount++; + if (charge && aptr->getTotalValence() != 2) { + rcount++; + } break; case 9: // Fluorine ocount++; - if (charge && aptr->getTotalValence() != 1) rcount++; + if (charge && aptr->getTotalValence() != 1) { + rcount++; + } break; case 17: // Chlorine case 35: // Bromine @@ -680,32 +732,57 @@ static std::string ArthorSubOrderHash(RWMol *mol) { ocount++; if (charge == 0) { unsigned int valence = aptr->getTotalValence(); - if (valence != 1 && valence != 3 && valence != 5 && valence != 7) + if (valence != 1 && valence != 3 && valence != 5 && valence != 7) { rcount++; + } } break; case 16: // Sulfur ocount++; if (charge == 0) { unsigned int valence = aptr->getTotalValence(); - if (valence != 2 && valence != 4 && valence != 6) rcount++; + if (valence != 2 && valence != 4 && valence != 6) { + rcount++; + } } break; } zcount += elem; - if (aptr->getIsotope() != 0) icount++; - if (charge != 0) qcount++; + if (aptr->getIsotope() != 0) { + icount++; + } + if (charge != 0) { + qcount++; + } } - if (acount > 0xffff) acount = 0xffff; - if (bcount > 0xffff) bcount = 0xffff; - if (pcount > 0xff) pcount = 0xff; - if (ccount > 0xffff) ccount = 0xffff; - if (ocount > 0xffff) ocount = 0xffff; - if (zcount > 0xffffff) zcount = 0xffffff; - if (rcount > 0xff) rcount = 0xff; - if (qcount > 0xff) qcount = 0xff; - if (icount > 0xff) icount = 0xff; + if (acount > 0xffff) { + acount = 0xffff; + } + if (bcount > 0xffff) { + bcount = 0xffff; + } + if (pcount > 0xff) { + pcount = 0xff; + } + if (ccount > 0xffff) { + ccount = 0xffff; + } + if (ocount > 0xffff) { + ocount = 0xffff; + } + if (zcount > 0xffffff) { + zcount = 0xffffff; + } + if (rcount > 0xff) { + rcount = 0xff; + } + if (qcount > 0xff) { + qcount = 0xff; + } + if (icount > 0xff) { + icount = 0xff; + } sprintf(buffer, "%04x%04x%02x%04x%04x%06x%02x%02x%02x", acount, bcount, pcount, ccount, ocount, zcount, rcount, qcount, icount); diff --git a/Code/GraphMol/MolHash/normalize.cpp b/Code/GraphMol/MolHash/normalize.cpp index 9c2d13071..db403bbbf 100644 --- a/Code/GraphMol/MolHash/normalize.cpp +++ b/Code/GraphMol/MolHash/normalize.cpp @@ -28,8 +28,9 @@ void Strip(RWMol *mol, unsigned int striptype) { } if (striptype & static_cast(StripType::BondStereo)) { for (auto bptr : mol->bonds()) { - if (bptr->getStereo() > RDKit::Bond::STEREOANY) + if (bptr->getStereo() > RDKit::Bond::STEREOANY) { bptr->setStereo(RDKit::Bond::STEREOANY); + } } } if (striptype & static_cast(StripType::Isotope)) { diff --git a/Code/GraphMol/MolHash/testMolHash.cpp b/Code/GraphMol/MolHash/testMolHash.cpp index 0509cb1df..7e0bd87b3 100644 --- a/Code/GraphMol/MolHash/testMolHash.cpp +++ b/Code/GraphMol/MolHash/testMolHash.cpp @@ -74,17 +74,24 @@ void test1() { unsigned n; n = mol->getNumAtoms(); atomsToUse.resize(n); - for (unsigned i = 0; i < n; i++) atomsToUse[i] = i; + for (unsigned i = 0; i < n; i++) { + atomsToUse[i] = i; + } n = mol->getNumBonds(); bondsToUse.resize(n); - for (unsigned i = 0; i < n; i++) bondsToUse[i] = i; + for (unsigned i = 0; i < n; i++) { + bondsToUse[i] = i; + } n = mol->getNumAtoms(); - for (unsigned i = 0; i < n; i++) + for (unsigned i = 0; i < n; i++) { atomCodes[i] = 1; // + mol->getAtomWithIdx(i)->getAtomicNum(); //res0 != res1,2,3 + } n = mol->getNumBonds(); - for (unsigned i = 0; i < n; i++) bondCodes[i] = 1; + for (unsigned i = 0; i < n; i++) { + bondCodes[i] = 1; + } fillAtomBondCodes(*mol, CF_NO_LABELS, &atomCodes, &bondCodes); @@ -127,8 +134,9 @@ void test2() { std::vector atomCodes(mol->getNumAtoms()); std::vector bondCodes(mol->getNumBonds()); - fillAtomBondCodes(*mol, CF_ELEMENT | CF_CHARGE /*|CF_VALENCE*/ - | CF_ATOM_AROMATIC, + fillAtomBondCodes(*mol, + CF_ELEMENT | CF_CHARGE /*|CF_VALENCE*/ + | CF_ATOM_AROMATIC, &atomCodes, &bondCodes); // fillAtomBondCodes(*mol, CF_ATOM_ALL &(~(CF_BOND_CHIRALITY | @@ -140,9 +148,13 @@ void test2() { << std::endl; } bool passed = true; - for (size_t i = 0; i < HashNonChiral.size(); i++) - for (size_t j = 0; j < HashNonChiral.size(); j++) - if (i != j && HashNonChiral[i] != HashNonChiral[j]) passed = false; + for (size_t i = 0; i < HashNonChiral.size(); i++) { + for (size_t j = 0; j < HashNonChiral.size(); j++) { + if (i != j && HashNonChiral[i] != HashNonChiral[j]) { + passed = false; + } + } + } TEST_ASSERT(passed); BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } @@ -154,7 +166,9 @@ void test21() { std::cout << "Hash size = " << 8 * sizeof(HashCodeType) << " bits.\n"; const char* smi[] = { // equal non-chiral BOND hash - "C/C=C/C", "CC=CC", "C/C=C\\C", + "C/C=C/C", + "CC=CC", + "C/C=C\\C", }; std::vector HashNonChiral; @@ -173,9 +187,13 @@ void test21() { << std::endl; } bool passed = true; - for (size_t i = 0; i < HashNonChiral.size(); i++) - for (size_t j = 0; j < HashNonChiral.size(); j++) - if (i != j && HashNonChiral[i] != HashNonChiral[j]) passed = false; + for (size_t i = 0; i < HashNonChiral.size(); i++) { + for (size_t j = 0; j < HashNonChiral.size(); j++) { + if (i != j && HashNonChiral[i] != HashNonChiral[j]) { + passed = false; + } + } + } TEST_ASSERT(passed); BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } @@ -185,7 +203,8 @@ void test3() { BOOST_LOG(rdInfoLog) << "Testing MolHash test3 CHIRALITY DIFF" << std::endl; const char* smi[] = { // different chiral hash - "C[C@H](F)Cl", "C[C@@H](F)Cl", "CC(F)Cl", "[13CH3]C(F)Cl", + "C[C@H](F)Cl", "C[C@@H](F)Cl", "CC(F)Cl", + "[13CH3]C(F)Cl", "C[C@H]1CC[C@H](C)CC1", "C[C@H]1CC[C@@H](C)CC1", "CC1CCC(C)CC1", }; @@ -208,9 +227,13 @@ void test3() { } bool passed = true; - for (size_t i = 0; i < HashChiral.size(); i++) - for (size_t j = 0; j < HashChiral.size(); j++) - if (i != j && HashChiral[i] == HashChiral[j]) passed = false; + for (size_t i = 0; i < HashChiral.size(); i++) { + for (size_t j = 0; j < HashChiral.size(); j++) { + if (i != j && HashChiral[i] == HashChiral[j]) { + passed = false; + } + } + } TEST_ASSERT(passed); BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } @@ -220,7 +243,8 @@ void test3a() { BOOST_LOG(rdInfoLog) << "Testing MolHash test3a CHIRALITY EQUAL" << std::endl; { const char* smi[] = { - "C[C@H](F)Cl", "C[C@@H](Cl)F", + "C[C@H](F)Cl", + "C[C@@H](Cl)F", }; ROMOL_SPTR mol1 = ROMOL_SPTR(SmilesToMol(smi[0])); ROMOL_SPTR mol2 = ROMOL_SPTR(SmilesToMol(smi[1])); @@ -241,7 +265,8 @@ void test3a() { } { const char* smi[] = { - "C[C@@H](F)Cl", "C[C@H](Cl)F", + "C[C@@H](F)Cl", + "C[C@H](Cl)F", }; ROMOL_SPTR mol1 = ROMOL_SPTR(SmilesToMol(smi[0])); ROMOL_SPTR mol2 = ROMOL_SPTR(SmilesToMol(smi[1])); @@ -263,7 +288,8 @@ void test3a() { { const char* smi[] = { - "C/C=C/Cl", "Cl/C=C/C", + "C/C=C/Cl", + "Cl/C=C/C", }; ROMOL_SPTR mol1 = ROMOL_SPTR(SmilesToMol(smi[0])); ROMOL_SPTR mol2 = ROMOL_SPTR(SmilesToMol(smi[1])); @@ -284,7 +310,8 @@ void test3a() { } { const char* smi[] = { - "C/C=C/Cl", "C/C=C\\Cl", + "C/C=C/Cl", + "C/C=C\\Cl", }; ROMOL_SPTR mol1 = ROMOL_SPTR(SmilesToMol(smi[0])); ROMOL_SPTR mol2 = ROMOL_SPTR(SmilesToMol(smi[1])); @@ -312,9 +339,14 @@ void test4() { BOOST_LOG(rdInfoLog) << "Testing MolHash test4 STRING" << std::endl; const char* smi[] = { // different chiral hash and equal non-chiral hash - "C[C@H](F)Cl", "C[C@@H](F)Cl", "CC(F)Cl", "[13CH3]C(F)Cl", + "C[C@H](F)Cl", + "C[C@@H](F)Cl", + "CC(F)Cl", + "[13CH3]C(F)Cl", // different chiral hash - "C[C@H]1CC[C@H](C)CC1", "C[C@H]1CC[C@@H](C)CC1", "CC1CCC(C)CC1", + "C[C@H]1CC[C@H](C)CC1", + "C[C@H]1CC[C@@H](C)CC1", + "CC1CCC(C)CC1", }; for (auto& i : smi) { @@ -329,8 +361,8 @@ void test4() { void test5() { BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Testing MolHash test5 " << std::endl; - const char* smi[] = {// different chiral hash and equal non-chiral hash - // groups of 3 + const char* smi[] = {// different chiral hash and equal non-chiral + // hash groups of 3 "C[CH](F)Cl", "C[C@H](F)Cl", "C[C@@H](F)Cl", // "c1cc(C[CH](F)Cl)cnc1", "c1cc(C[C@H](F)Cl)cnc1", @@ -365,38 +397,40 @@ void test5() { void doUnitTest() { std::cout << "Hash size = " << 8 * sizeof(HashCodeType) << " bits.\n"; - BOOST_LOG(rdInfoLog) - << "*******************************************************\n"; + BOOST_LOG(rdInfoLog) << "****************************************" + "***************\n"; test1(); - BOOST_LOG(rdInfoLog) - << "*******************************************************\n"; + BOOST_LOG(rdInfoLog) << "****************************************" + "***************\n"; test2(); - BOOST_LOG(rdInfoLog) - << "*******************************************************\n"; + BOOST_LOG(rdInfoLog) << "****************************************" + "***************\n"; test21(); - BOOST_LOG(rdInfoLog) - << "*******************************************************\n"; + BOOST_LOG(rdInfoLog) << "****************************************" + "***************\n"; test3(); - BOOST_LOG(rdInfoLog) - << "*******************************************************\n"; + BOOST_LOG(rdInfoLog) << "****************************************" + "***************\n"; test3a(); - BOOST_LOG(rdInfoLog) - << "*******************************************************\n"; + BOOST_LOG(rdInfoLog) << "****************************************" + "***************\n"; test4(); - BOOST_LOG(rdInfoLog) - << "*******************************************************\n"; + BOOST_LOG(rdInfoLog) << "****************************************" + "***************\n"; test5(); } //============================================================================= -// investigation test case for computing of a probability of the hash code -// collisions +// investigation test case for computing of a probability of the +// hash code collisions //============================================================================= std::string getSmilesOnly(const char* smiles, std::string* id = nullptr) { const char* sp = strchr(smiles, ' '); unsigned n = (sp ? sp - smiles + 1 : strlen(smiles)); - if (id) *id = std::string(smiles + n); + if (id) { + *id = std::string(smiles + n); + } return std::string(smiles, n); } @@ -412,13 +446,17 @@ HashCodeType computeHash(const ROMol& mol, CodeFlags flags) { unsigned n = mol.getNumAtoms(); for (unsigned i = 0; i < n; i++) { const Atom* atom = mol.getAtomWithIdx(i); - if (1) atomsToUse.push_back(atom->getIdx()); + if (1) { + atomsToUse.push_back(atom->getIdx()); + } } n = mol.getNumBonds(); for (unsigned i = 0; i < n; i++) { const Bond* bond = mol.getBondWithIdx(i); - if (1) bondsToUse.push_back(bond->getIdx()); + if (1) { + bondsToUse.push_back(bond->getIdx()); + } } return generateMoleculeHashCode(mol, &atomsToUse, &bondsToUse, &atomCodes, @@ -452,24 +490,27 @@ void analyzeResults(std::list& res) { unsigned rn = 0, cn = 0; for (auto r0 = res.begin(); r0 != res.end(); r0++) { std::cerr << "Result: " << ++rn << "\r"; - if (0 == r0->Line) // collision has been already found + if (0 == r0->Line) { // collision has been already found continue; + } unsigned hashCollision = 0; std::vector cl; - // use binary search of collision in sorted list to improve performance + // use binary search of collision in sorted list to improve + // performance //........ auto r1 = r0; for (auto r = ++r1; r != res.end(); r++) { - if (0 == r->Line) // collision has been already found + if (0 == r->Line) { // collision has been already found continue; + } if (r->Hash == r0->Hash) // collision found { ++hashCollision; cl.push_back(r->Line); - // std::cout<Id<<"="<Line<<"\n"; // TEMP - // TEST - r->Line = - 0; // mark as already processed collision to exclude duplicates + // std::cout<Id<<"="<Line<<"\n"; // + // TEMP TEST + r->Line = 0; // mark as already processed collision to exclude + // duplicates } } if (0 != hashCollision) // collision found @@ -477,7 +518,9 @@ void analyzeResults(std::list& res) { cn += hashCollision; std::cout << "mol line " << r0->Line << ": " << hashCollision << " collisions with: "; - for (unsigned int i : cl) std::cout << i << " "; + for (unsigned int i : cl) { + std::cout << i << " "; + } std::cout << "lines.\n"; } } @@ -497,8 +540,9 @@ void testFileSMILES(const char* file, HashCodeType bitMask) { } char smiles[4096]; while (fgets(smiles, sizeof(smiles), f) && line <= 1000999) { - for (size_t i = strlen(smiles) - 1; i > 0 && smiles[i] < ' '; i--) + for (size_t i = strlen(smiles) - 1; i > 0 && smiles[i] < ' '; i--) { smiles[i] = '\0'; // remove LF + } std::string id; std::cerr << "\rLine: " << ++line << " "; if ('#' != smiles[0] && ' ' != smiles[0] && @@ -517,8 +561,9 @@ void testFileSMILES(const char* file, HashCodeType bitMask) { HashResult& r = res.back(); // r.ChiralInfo = 0;//mol-(); r.Hash = computeHash(*mol, CF_ALL) & bitMask; - } else + } else { std::cerr << " skipped: " << smiles << "/n"; + } } fclose(f); std::cout << "\nDONE. " << res.size() << " molecules processed.\n"; @@ -528,27 +573,32 @@ void testFileSMILES(const char* file, HashCodeType bitMask) { void checkCollisions(const char* file, std::uint32_t bits = 0) { HashCodeType bitMask = 0; - if (0 == bits || 8 * sizeof(HashCodeType) < bits) + if (0 == bits || 8 * sizeof(HashCodeType) < bits) { bits = 8 * sizeof(HashCodeType); - for (unsigned i = 0; i < bits; i++) bitMask |= 1ULL << i; + } + for (unsigned i = 0; i < bits; i++) { + bitMask |= 1ULL << i; + } std::cout << "Hash size = " << bits << " bits. Mask = " << bitMask << "\n"; - if (0 == strcmp(file + strlen(file) - 4, ".smi")) + if (0 == strcmp(file + strlen(file) - 4, ".smi")) { testFileSMILES(file, bitMask); - else + } else { std::cout << "UNKNOWN File Extension.\n"; + } } -} // RDKit +} // namespace RDKit int main(int argc, char* argv[]) { RDKit::doUnitTest(); - if (2 == argc) + if (2 == argc) { RDKit::checkCollisions(argv[1]); - else if (3 == argc && isdigit(*argv[2])) + } else if (3 == argc && isdigit(*argv[2])) { RDKit::checkCollisions(argv[1], atoi(argv[2])); - else if (1 != argc) + } else if (1 != argc) { std::cout << "UNKNOWN Argument.\n"; + } return 0; } diff --git a/Code/GraphMol/MolInterchange/Parser.cpp b/Code/GraphMol/MolInterchange/Parser.cpp index d30930f58..c00863635 100644 --- a/Code/GraphMol/MolInterchange/Parser.cpp +++ b/Code/GraphMol/MolInterchange/Parser.cpp @@ -45,13 +45,16 @@ struct DefaultValueCache { int getInt(const char *key) const { PRECONDITION(key, "no key"); const auto &lookup = intMap.find(key); - if (lookup != intMap.end()) return lookup->second; + if (lookup != intMap.end()) { + return lookup->second; + } const auto &miter = rjDefaults.FindMember(key); if (miter != rjDefaults.MemberEnd()) { - if (!miter->value.IsInt()) + if (!miter->value.IsInt()) { throw FileParseException(std::string("Bad format: value of ") + std::string(key) + std::string(" is not an int")); + } int res = miter->value.GetInt(); intMap[key] = res; return res; @@ -61,13 +64,16 @@ struct DefaultValueCache { bool getBool(const char *key) const { PRECONDITION(key, "no key"); const auto &lookup = boolMap.find(key); - if (lookup != boolMap.end()) return lookup->second; + if (lookup != boolMap.end()) { + return lookup->second; + } const auto &miter = rjDefaults.FindMember(key); if (miter != rjDefaults.MemberEnd()) { - if (!miter->value.IsBool()) + if (!miter->value.IsBool()) { throw FileParseException(std::string("Bad format: value of ") + std::string(key) + std::string(" is not a bool")); + } bool res = miter->value.GetBool(); boolMap[key] = res; return res; @@ -77,13 +83,16 @@ struct DefaultValueCache { std::string getString(const char *key) const { PRECONDITION(key, "no key"); const auto &lookup = stringMap.find(key); - if (lookup != stringMap.end()) return lookup->second; + if (lookup != stringMap.end()) { + return lookup->second; + } const auto &miter = rjDefaults.FindMember(key); if (miter != rjDefaults.MemberEnd()) { - if (!miter->value.IsString()) + if (!miter->value.IsString()) { throw FileParseException(std::string("Bad format: value of ") + std::string(key) + std::string(" is not a string")); + } std::string res = miter->value.GetString(); stringMap[key] = res; return res; @@ -98,10 +107,11 @@ int getIntDefaultValue(const char *key, const rj::Value &from, auto endp = from.MemberEnd(); auto miter = from.FindMember(key); if (miter != endp) { - if (!miter->value.IsInt()) + if (!miter->value.IsInt()) { throw FileParseException(std::string("Bad format: value of ") + std::string(key) + std::string(" is not an int")); + } return miter->value.GetInt(); } return defaults.getInt(key); @@ -112,10 +122,11 @@ bool getBoolDefaultValue(const char *key, const rj::Value &from, auto endp = from.MemberEnd(); auto miter = from.FindMember(key); if (miter != endp) { - if (!miter->value.IsBool()) + if (!miter->value.IsBool()) { throw FileParseException(std::string("Bad format: value of ") + std::string(key) + std::string(" is not a bool")); + } return miter->value.GetBool(); } return defaults.getBool(key); @@ -126,10 +137,11 @@ std::string getStringDefaultValue(const char *key, const rj::Value &from, auto endp = from.MemberEnd(); auto miter = from.FindMember(key); if (miter != endp) { - if (!miter->value.IsString()) + if (!miter->value.IsString()) { throw FileParseException(std::string("Bad format: value of ") + std::string(key) + std::string(" is not a string")); + } return miter->value.GetString(); } return defaults.getString(key); @@ -161,10 +173,13 @@ void readBond(RWMol *mol, const rj::Value &bondVal, unsigned int bid = mol->addBond(aids[0].GetInt(), aids[1].GetInt()) - 1; Bond *bnd = mol->getBondWithIdx(bid); unsigned int bo = getIntDefaultValue("bo", bondVal, bondDefaults); - if (bolookup.find(bo) == bolookup.end()) + if (bolookup.find(bo) == bolookup.end()) { throw FileParseException("Bad Format: bad bond order for bond"); + } bnd->setBondType(bolookup.find(bo)->second); - if (bondVal.HasMember("stereoAtoms")) needStereoLoop = true; + if (bondVal.HasMember("stereoAtoms")) { + needStereoLoop = true; + } } void readBondStereo(Bond *bnd, const rj::Value &bondVal, @@ -176,8 +191,9 @@ void readBondStereo(Bond *bnd, const rj::Value &bondVal, const auto aids = miter->value.GetArray(); bnd->setStereoAtoms(aids[0].GetInt(), aids[1].GetInt()); std::string stereo = getStringDefaultValue("stereo", bondVal, bondDefaults); - if (stereolookup.find(stereo) == stereolookup.end()) + if (stereolookup.find(stereo) == stereolookup.end()) { throw FileParseException("Bad Format: bond stereo value for bond"); + } bnd->setStereo(stereolookup.find(stereo)->second); } else { @@ -191,29 +207,34 @@ void readBondStereo(Bond *bnd, const rj::Value &bondVal, void readConformer(Conformer *conf, const rj::Value &confVal) { PRECONDITION(conf, "no conformer"); - if (!confVal.HasMember("dim")) + if (!confVal.HasMember("dim")) { throw FileParseException("Bad Format: no conformer dimension"); + } size_t dim = confVal["dim"].GetInt(); - if (dim == 2) + if (dim == 2) { conf->set3D(false); - else if (dim == 3) + } else if (dim == 3) { conf->set3D(true); - else + } else { throw FileParseException("Bad Format: conformer dimension != 2 or 3"); - if (!confVal.HasMember("coords")) + } + if (!confVal.HasMember("coords")) { throw FileParseException("Bad Format: no conformer coords"); + } size_t idx = 0; for (const auto &ptVal : confVal["coords"].GetArray()) { const auto &arr = ptVal.GetArray(); - if (arr.Size() != dim) + if (arr.Size() != dim) { throw FileParseException("coordinate contains wrong number of values"); + } RDGeom::Point3D pt(arr[0].GetFloat(), arr[1].GetFloat(), (dim == 3 ? arr[2].GetFloat() : 0.0)); conf->setAtomPos(idx++, pt); } - if (idx != conf->getNumAtoms()) + if (idx != conf->getNumAtoms()) { throw FileParseException( "Bad Format: conformer doesn't contain coordinates for all atoms"); + } } void readPartialCharges(RWMol *mol, const rj::Value &repVal, @@ -222,8 +243,9 @@ void readPartialCharges(RWMol *mol, const rj::Value &repVal, PRECONDITION(mol, "no molecule"); PRECONDITION(repVal["name"].GetString() == std::string("partialCharges"), "bad charges"); - if (!repVal.HasMember("formatVersion")) + if (!repVal.HasMember("formatVersion")) { throw FileParseException("Bad Format: missing version"); + } if (repVal["formatVersion"].GetInt() > currentChargeRepresentationVersion) { BOOST_LOG(rdWarningLog) << "partialCharges version " << repVal["formatVersion"].GetInt() @@ -233,14 +255,16 @@ void readPartialCharges(RWMol *mol, const rj::Value &repVal, { const auto &miter = repVal.FindMember("values"); if (miter != repVal.MemberEnd()) { - if (miter->value.GetArray().Size() != mol->getNumAtoms()) + if (miter->value.GetArray().Size() != mol->getNumAtoms()) { throw FileParseException( "Bad Format: size of values array != num atoms"); + } for (unsigned int idx = 0; idx != mol->getNumAtoms(); ++idx) { const auto &aval = miter->value.GetArray(); const auto &val = aval[idx]; - if (!val.IsDouble()) + if (!val.IsDouble()) { throw FileParseException("Bad Format: partial charge not double"); + } mol->getAtomWithIdx(idx)->setProp(common_properties::_GasteigerCharge, val.GetDouble()); } @@ -252,8 +276,9 @@ void readRDKitRepresentation(RWMol *mol, const rj::Value &repVal, PRECONDITION(mol, "no molecule"); PRECONDITION(repVal["name"].GetString() == std::string("rdkitRepresentation"), "bad representation"); - if (!repVal.HasMember("formatVersion")) + if (!repVal.HasMember("formatVersion")) { throw FileParseException("Bad Format: missing format_version"); + } if (repVal["formatVersion"].GetInt() > 1) { BOOST_LOG(rdWarningLog) << "RDKit representation format version " << repVal["formatVersion"].GetInt() @@ -264,8 +289,9 @@ void readRDKitRepresentation(RWMol *mol, const rj::Value &repVal, const auto &miter = repVal.FindMember("aromaticAtoms"); if (miter != repVal.MemberEnd()) { for (const auto &val : miter->value.GetArray()) { - if (!val.IsInt()) + if (!val.IsInt()) { throw FileParseException("Bad Format: aromaticAtom not int"); + } mol->getAtomWithIdx(val.GetInt())->setIsAromatic(true); } } @@ -274,8 +300,9 @@ void readRDKitRepresentation(RWMol *mol, const rj::Value &repVal, const auto &miter = repVal.FindMember("aromaticBonds"); if (miter != repVal.MemberEnd()) { for (const auto &val : miter->value.GetArray()) { - if (!val.IsInt()) + if (!val.IsInt()) { throw FileParseException("Bad Format: aromaticBond not int"); + } mol->getBondWithIdx(val.GetInt())->setIsAromatic(true); if (params.setAromaticBonds) { mol->getBondWithIdx(val.GetInt())->setBondType(Bond::AROMATIC); @@ -288,8 +315,9 @@ void readRDKitRepresentation(RWMol *mol, const rj::Value &repVal, if (miter != repVal.MemberEnd()) { size_t i = 0; for (const auto &val : miter->value.GetArray()) { - if (!val.IsInt()) + if (!val.IsInt()) { throw FileParseException("Bad Format: ciprank not int"); + } mol->getAtomWithIdx(i++)->setProp( common_properties::_CIPRank, static_cast(val.GetInt())); @@ -300,8 +328,9 @@ void readRDKitRepresentation(RWMol *mol, const rj::Value &repVal, const auto &miter = repVal.FindMember("cipCodes"); if (miter != repVal.MemberEnd()) { for (const auto &val : miter->value.GetArray()) { - if (!val.IsArray()) + if (!val.IsArray()) { throw FileParseException("Bad Format: CIPCode not string"); + } mol->getAtomWithIdx(val[0].GetInt()) ->setProp(common_properties::_CIPCode, val[1].GetString()); } @@ -315,8 +344,9 @@ void readRDKitRepresentation(RWMol *mol, const rj::Value &repVal, auto ri = mol->getRingInfo(); ri->initialize(); for (const auto &val : miter->value.GetArray()) { - if (!val.IsArray()) + if (!val.IsArray()) { throw FileParseException("Bad Format: atomRing not array"); + } INT_VECT atomRing; INT_VECT bondRing; size_t sz = val.Size(); @@ -349,10 +379,12 @@ void processMol(RWMol *mol, const rj::Value &molval, if (molval.HasMember("name")) { mol->setProp(common_properties::_Name, molval["name"].GetString()); } - if (!molval.HasMember("atoms")) + if (!molval.HasMember("atoms")) { throw FileParseException("Bad Format: missing atoms in JSON"); - if (!molval.HasMember("bonds")) + } + if (!molval.HasMember("bonds")) { throw FileParseException("Bad Format: missing bonds in JSON"); + } for (const auto &atomVal : molval["atoms"].GetArray()) { readAtom(mol, atomVal, atomDefaults); @@ -371,7 +403,7 @@ void processMol(RWMol *mol, const rj::Value &molval, } if (params.parseConformers && molval.HasMember("conformers")) { for (const auto &confVal : molval["conformers"].GetArray()) { - Conformer *conf = new Conformer(mol->getNumAtoms()); + auto *conf = new Conformer(mol->getNumAtoms()); readConformer(conf, confVal); mol->addConformer(conf, true); } @@ -379,20 +411,22 @@ void processMol(RWMol *mol, const rj::Value &molval, if (params.parseProperties && molval.HasMember("properties")) { for (const auto &propVal : molval["properties"].GetObject()) { - if (propVal.value.IsInt()) + if (propVal.value.IsInt()) { mol->setProp(propVal.name.GetString(), propVal.value.GetInt()); - else if (propVal.value.IsDouble()) + } else if (propVal.value.IsDouble()) { mol->setProp(propVal.name.GetString(), propVal.value.GetDouble()); - else if (propVal.value.IsString()) + } else if (propVal.value.IsString()) { mol->setProp(propVal.name.GetString(), propVal.value.GetString()); + } } } if (molval.HasMember("extensions")) { for (const auto &propVal : molval["extensions"].GetArray()) { - if (!propVal.HasMember("name")) + if (!propVal.HasMember("name")) { throw FileParseException( "Bad Format: representation has no name member"); + } if (propVal["name"].GetString() == std::string("rdkitRepresentation")) { readRDKitRepresentation(mol, propVal, params); } @@ -410,36 +444,43 @@ std::vector> DocToMols( std::vector> res; // some error checking - if (!doc.IsObject()) + if (!doc.IsObject()) { throw FileParseException("Bad Format: JSON should be an object"); - if (!doc.HasMember("commonchem")) + } + if (!doc.HasMember("commonchem")) { throw FileParseException("Bad Format: missing header in JSON"); - if (!doc["commonchem"].HasMember("version")) + } + if (!doc["commonchem"].HasMember("version")) { throw FileParseException("Bad Format: missing version in JSON"); - if (doc["commonchem"]["version"].GetInt() != currentMolJSONVersion) + } + if (doc["commonchem"]["version"].GetInt() != currentMolJSONVersion) { throw FileParseException("Bad Format: bad version in JSON"); + } rj::Value atomDefaults_; if (rj::GetValueByPointer(doc, "/defaults/atom")) { atomDefaults_ = *rj::GetValueByPointer(doc, "/defaults/atom"); - if (!atomDefaults_.IsObject()) + if (!atomDefaults_.IsObject()) { throw FileParseException("Bad Format: atomDefaults is not an object"); + } } const DefaultValueCache atomDefaults(atomDefaults_); rj::Value bondDefaults_; if (rj::GetValueByPointer(doc, "/defaults/bond")) { bondDefaults_ = *rj::GetValueByPointer(doc, "/defaults/bond"); - if (!bondDefaults_.IsObject()) + if (!bondDefaults_.IsObject()) { throw FileParseException("Bad Format: bondDefaults is not an object"); + } } const DefaultValueCache bondDefaults(bondDefaults_); if (doc.HasMember("molecules")) { - if (!doc["molecules"].IsArray()) + if (!doc["molecules"].IsArray()) { throw FileParseException("Bad Format: molecules is not an array"); + } for (const auto &molval : doc["molecules"].GetArray()) { - RWMol *mol = new RWMol(); + auto *mol = new RWMol(); processMol(mol, molval, atomDefaults, bondDefaults, params); mol->updatePropertyCache(params.strictValenceCheck); mol->setProp(common_properties::_StereochemDone, 1); diff --git a/Code/GraphMol/MolOps.cpp b/Code/GraphMol/MolOps.cpp index 7dd497dc1..2b65852f3 100644 --- a/Code/GraphMol/MolOps.cpp +++ b/Code/GraphMol/MolOps.cpp @@ -59,7 +59,9 @@ void nitrogenCleanup(RWMol &mol, Atom *atom) { // munged: // O=[n+]1occcc1 // this was sf.net issue 1811276 - if (atom->getFormalCharge()) return; + if (atom->getFormalCharge()) { + return; + } // we need to play this little aromaticity game because the // explicit valence code modifies its results for aromatic @@ -112,7 +114,9 @@ void phosphorusCleanup(RWMol &mol, Atom *atom) { PRECONDITION(atom, "bad atom"); // we only want to do neutrals - if (atom->getFormalCharge()) return; + if (atom->getFormalCharge()) { + return; + } // NOTE that we are calling calcExplicitValence() here, we do // this because we cannot be sure that it has already been @@ -464,7 +468,7 @@ std::vector getMolFrags(const ROMol &mol, bool sanitizeFrags, // copy atoms INT_INT_VECT_MAP comMap; for (unsigned int idx = 0; idx < mol.getNumAtoms(); ++idx) { - RWMol *tmp = static_cast(res[(*mapping)[idx]].get()); + auto *tmp = static_cast(res[(*mapping)[idx]].get()); const Atom *oAtm = mol.getAtomWithIdx(idx); ids[idx] = tmp->addAtom(oAtm->copy(), false, true); copiedAtoms[idx] = 1; @@ -501,7 +505,7 @@ std::vector getMolFrags(const ROMol &mol, bool sanitizeFrags, } ringStereoAtomsCopied.push_back(ridx); } - RWMol *tmp = static_cast(res[(*mapping)[idx]].get()); + auto *tmp = static_cast(res[(*mapping)[idx]].get()); tmp->getAtomWithIdx(ids[idx])->setProp( common_properties::_ringStereoAtoms, ringStereoAtomsCopied); } @@ -517,7 +521,7 @@ std::vector getMolFrags(const ROMol &mol, bool sanitizeFrags, continue; } Bond *nBond = bond->copy(); - RWMol *tmp = + auto *tmp = static_cast(res[(*mapping)[nBond->getBeginAtomIdx()]].get()); nBond->setOwningMol(static_cast(tmp)); nBond->setBeginAtomIdx(ids[nBond->getBeginAtomIdx()]); @@ -534,7 +538,7 @@ std::vector getMolFrags(const ROMol &mol, bool sanitizeFrags, if (mol.getRingInfo()->isInitialized()) { for (const auto &i : mol.getRingInfo()->atomRings()) { INT_VECT aids; - RWMol *tmp = static_cast(res[(*mapping)[i[0]]].get()); + auto *tmp = static_cast(res[(*mapping)[i[0]]].get()); if (!tmp->getRingInfo()->isInitialized()) { tmp->getRingInfo()->initialize(); } @@ -545,12 +549,16 @@ std::vector getMolFrags(const ROMol &mol, bool sanitizeFrags, INT_VECT_CI lastRai = aids.begin(); for (INT_VECT_CI rai = aids.begin() + 1; rai != aids.end(); ++rai) { const Bond *bnd = tmp->getBondBetweenAtoms(*rai, *lastRai); - if (!bnd) throw ValueErrorException("expected bond not found"); + if (!bnd) { + throw ValueErrorException("expected bond not found"); + } bids.push_back(bnd->getIdx()); lastRai = rai; } const Bond *bnd = tmp->getBondBetweenAtoms(*lastRai, *(aids.begin())); - if (!bnd) throw ValueErrorException("expected bond not found"); + if (!bnd) { + throw ValueErrorException("expected bond not found"); + } bids.push_back(bnd->getIdx()); tmp->getRingInfo()->addRing(aids, bids); } @@ -568,7 +576,9 @@ std::vector getMolFrags(const ROMol &mol, bool sanitizeFrags, newM->addConformer(conf); } for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) { - if (ids[i] < 0) continue; + if (ids[i] < 0) { + continue; + } res[(*mapping)[i]] ->getConformer((*cit)->getId()) .setAtomPos(ids[i], (*cit)->getAtomPos(i)); @@ -638,16 +648,17 @@ std::map> getMolFragsWithQuery( if (whiteList) { bool found = std::find(whiteList->begin(), whiteList->end(), where) != whiteList->end(); - if (!found && !negateList) + if (!found && !negateList) { continue; - else if (found && negateList) + } else if (found && negateList) { continue; + } } assignments[i] = where; if (res.find(where) == res.end()) { res[where] = boost::shared_ptr(new ROMol()); } - RWMol *frag = static_cast(res[where].get()); + auto *frag = static_cast(res[where].get()); ids[i] = frag->addAtom(mol.getAtomWithIdx(i)->copy(), false, true); // loop over neighbors and add bonds in the fragment to all atoms // that are already in the same fragment @@ -674,7 +685,9 @@ std::map> getMolFragsWithQuery( newM->addConformer(conf); } for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) { - if (ids[i] < 0) continue; + if (ids[i] < 0) { + continue; + } res[assignments[i]] ->getConformer((*cit)->getId()) .setAtomPos(ids[i], (*cit)->getAtomPos(i)); diff --git a/Code/GraphMol/MolPickler.cpp b/Code/GraphMol/MolPickler.cpp index 7c08b99a1..a616aea0f 100644 --- a/Code/GraphMol/MolPickler.cpp +++ b/Code/GraphMol/MolPickler.cpp @@ -37,7 +37,7 @@ const int32_t MolPickler::versionPatch = 0; const int32_t MolPickler::endianId = 0xDEADBEEF; void streamWrite(std::ostream &ss, MolPickler::Tags tag) { - unsigned char tmp = static_cast(tag); + auto tmp = static_cast(tag); streamWrite(ss, tmp); } template @@ -128,7 +128,9 @@ template void pickleQuery(std::ostream &ss, const Query *query) { PRECONDITION(query, "no query"); streamWrite(ss, query->getDescription()); - if (query->getNegation()) streamWrite(ss, MolPickler::QUERY_ISNEGATED); + if (query->getNegation()) { + streamWrite(ss, MolPickler::QUERY_ISNEGATED); + } int32_t queryVal; // if (typeid(*query)==typeid(ATOM_BOOL_QUERY)){ // streamWrite(ss,QUERY_BOOL); @@ -598,37 +600,48 @@ Query *unpickleQuery(std::istream &ss, void pickleAtomPDBResidueInfo(std::ostream &ss, const AtomPDBResidueInfo *info) { PRECONDITION(info, "no info"); - if (info->getSerialNumber()) + if (info->getSerialNumber()) { streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_SERIALNUMBER, info->getSerialNumber()); - if (info->getAltLoc() != "") + } + if (info->getAltLoc() != "") { streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_ALTLOC, info->getAltLoc()); - if (info->getResidueName() != "") + } + if (info->getResidueName() != "") { streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_RESIDUENAME, info->getResidueName()); - if (info->getResidueNumber()) + } + if (info->getResidueNumber()) { streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_RESIDUENUMBER, info->getResidueNumber()); - if (info->getChainId() != "") + } + if (info->getChainId() != "") { streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_CHAINID, info->getChainId()); - if (info->getInsertionCode() != "") + } + if (info->getInsertionCode() != "") { streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_INSERTIONCODE, info->getInsertionCode()); - if (info->getOccupancy()) + } + if (info->getOccupancy()) { streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_OCCUPANCY, info->getOccupancy()); - if (info->getTempFactor()) + } + if (info->getTempFactor()) { streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_TEMPFACTOR, info->getTempFactor()); - if (info->getIsHeteroAtom()) + } + if (info->getIsHeteroAtom()) { streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_ISHETEROATOM, static_cast(info->getIsHeteroAtom())); - if (info->getSecondaryStructure()) + } + if (info->getSecondaryStructure()) { streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_SECONDARYSTRUCTURE, info->getSecondaryStructure()); - if (info->getSegmentNumber()) + } + if (info->getSegmentNumber()) { streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_SEGMENTNUMBER, info->getSegmentNumber()); + } } void unpickleAtomPDBResidueInfo(std::istream &ss, AtomPDBResidueInfo *info, @@ -724,9 +737,10 @@ AtomMonomerInfo *unpickleAtomMonomerInfo(std::istream &ss, int version) { case AtomMonomerInfo::UNKNOWN: case AtomMonomerInfo::OTHER: streamRead(ss, tag, version); - if (tag != MolPickler::END_ATOM_MONOMER) + if (tag != MolPickler::END_ATOM_MONOMER) { throw MolPicklerException( "did not find expected end of atom monomer info"); + } res = new AtomMonomerInfo(RDKit::AtomMonomerInfo::AtomMonomerType(typ), nm); break; @@ -990,7 +1004,9 @@ void MolPickler::_depickle(std::istream &ss, ROMol *mol, int version, if (version >= 3000) { char flag; streamRead(ss, flag, version); - if (flag & 0x1 << 7) includeCoords = true; + if (flag & 0x1 << 7) { + includeCoords = true; + } } // ------------------- // @@ -1148,7 +1164,9 @@ void MolPickler::_depickle(std::istream &ss, ROMol *mol, int version, namespace { bool getAtomMapNumber(const Atom *atom, int &mapNum) { PRECONDITION(atom, "bad atom"); - if (!atom->hasProp(common_properties::molAtomMapNumber)) return false; + if (!atom->hasProp(common_properties::molAtomMapNumber)) { + return false; + } bool res = true; int tmpInt; try { @@ -1162,7 +1180,9 @@ bool getAtomMapNumber(const Atom *atom, int &mapNum) { res = false; } } - if (res) mapNum = tmpInt; + if (res) { + mapNum = tmpInt; + } return res; } } // namespace @@ -1303,12 +1323,24 @@ void MolPickler::_pickleAtom(std::ostream &ss, const Atom *atom) { streamWrite(ss, tmpUchar); flags = 0; - if (atom->getIsAromatic()) flags |= 0x1 << 6; - if (atom->getNoImplicit()) flags |= 0x1 << 5; - if (atom->hasQuery()) flags |= 0x1 << 4; - if (getAtomMapNumber(atom, tmpInt)) flags |= 0x1 << 3; - if (atom->hasProp(common_properties::dummyLabel)) flags |= 0x1 << 2; - if (atom->getMonomerInfo()) flags |= 0x1 << 1; + if (atom->getIsAromatic()) { + flags |= 0x1 << 6; + } + if (atom->getNoImplicit()) { + flags |= 0x1 << 5; + } + if (atom->hasQuery()) { + flags |= 0x1 << 4; + } + if (getAtomMapNumber(atom, tmpInt)) { + flags |= 0x1 << 3; + } + if (atom->hasProp(common_properties::dummyLabel)) { + flags |= 0x1 << 2; + } + if (atom->getMonomerInfo()) { + flags |= 0x1 << 1; + } streamWrite(ss, flags); @@ -1348,7 +1380,7 @@ void MolPickler::_pickleConformer(std::ostream &ss, const Conformer *conf) { PRECONDITION(conf, "empty conformer"); char tmpChr = static_cast(conf->is3D()); streamWrite(ss, tmpChr); - int32_t tmpInt = static_cast(conf->getId()); + auto tmpInt = static_cast(conf->getId()); streamWrite(ss, tmpInt); T tmpT = static_cast(conf->getNumAtoms()); streamWrite(ss, tmpT); @@ -1375,10 +1407,10 @@ Conformer *MolPickler::_conformerFromPickle(std::istream &ss, int version) { } int tmpInt; streamRead(ss, tmpInt, version); - unsigned int cid = static_cast(tmpInt); + auto cid = static_cast(tmpInt); T tmpT; streamRead(ss, tmpT, version); - unsigned int numAtoms = static_cast(tmpT); + auto numAtoms = static_cast(tmpT); auto *conf = new Conformer(numAtoms); conf->setId(cid); conf->set3D(is3D); @@ -1582,12 +1614,24 @@ void MolPickler::_pickleBond(std::ostream &ss, const Bond *bond, streamWrite(ss, tmpT); flags = 0; - if (bond->getIsAromatic()) flags |= 0x1 << 6; - if (bond->getIsConjugated()) flags |= 0x1 << 5; - if (bond->hasQuery()) flags |= 0x1 << 4; - if (bond->getBondType() != Bond::SINGLE) flags |= 0x1 << 3; - if (bond->getBondDir() != Bond::NONE) flags |= 0x1 << 2; - if (bond->getStereo() != Bond::STEREONONE) flags |= 0x1 << 1; + if (bond->getIsAromatic()) { + flags |= 0x1 << 6; + } + if (bond->getIsConjugated()) { + flags |= 0x1 << 5; + } + if (bond->hasQuery()) { + flags |= 0x1 << 4; + } + if (bond->getBondType() != Bond::SINGLE) { + flags |= 0x1 << 3; + } + if (bond->getBondDir() != Bond::NONE) { + flags |= 0x1 << 2; + } + if (bond->getStereo() != Bond::STEREONONE) { + flags |= 0x1 << 1; + } streamWrite(ss, flags); if (bond->getBondType() != Bond::SINGLE) { @@ -1657,7 +1701,7 @@ Bond *MolPickler::_addBondFromPickle(std::istream &ss, ROMol *mol, int version, if (version > 3000) { streamRead(ss, tmpChar, version); - Bond::BondStereo stereo = static_cast(tmpChar); + auto stereo = static_cast(tmpChar); bond->setStereo(stereo); if (stereo != Bond::STEREONONE) { streamRead(ss, tmpChar, version); @@ -1684,7 +1728,7 @@ Bond *MolPickler::_addBondFromPickle(std::istream &ss, ROMol *mol, int version, if (flags & (0x1 << 1)) { streamRead(ss, tmpChar, version); - Bond::BondStereo stereo = static_cast(tmpChar); + auto stereo = static_cast(tmpChar); streamRead(ss, tmpChar, version); for (char i = 0; i < tmpChar; ++i) { streamRead(ss, tmpT, version); @@ -1765,7 +1809,9 @@ void MolPickler::_addRingInfoFromPickle(std::istream &ss, ROMol *mol, int version, bool directMap) { PRECONDITION(mol, "empty molecule"); RingInfo *ringInfo = mol->getRingInfo(); - if (!ringInfo->isInitialized()) ringInfo->initialize(); + if (!ringInfo->isInitialized()) { + ringInfo->initialize(); + } T numRings; streamRead(ss, numRings, version); @@ -1940,11 +1986,11 @@ SubstanceGroup MolPickler::_getSubstanceGroupFromPickle(std::istream &ss, SubstanceGroup::Bracket bracket; for (auto j = 0; j < 3; ++j) { streamRead(ss, tmpFloat, version); - double x = static_cast(tmpFloat); + auto x = static_cast(tmpFloat); streamRead(ss, tmpFloat, version); - double y = static_cast(tmpFloat); + auto y = static_cast(tmpFloat); streamRead(ss, tmpFloat, version); - double z = static_cast(tmpFloat); + auto z = static_cast(tmpFloat); bracket[j] = RDGeom::Point3D(x, y, z); } sgroup.addBracket(bracket); @@ -2005,7 +2051,7 @@ template void MolPickler::_depickleStereo(std::istream &ss, ROMol *mol, int version) { T tmpT; streamRead(ss, tmpT, version); - const unsigned numGroups = static_cast(tmpT); + const auto numGroups = static_cast(tmpT); if (numGroups > 0u) { std::vector groups; @@ -2015,7 +2061,7 @@ void MolPickler::_depickleStereo(std::istream &ss, ROMol *mol, int version) { const auto groupType = static_cast(tmpT); streamRead(ss, tmpT, version); - const unsigned numAtoms = static_cast(tmpT); + const auto numAtoms = static_cast(tmpT); std::vector atoms; atoms.reserve(numAtoms); @@ -2033,7 +2079,9 @@ void MolPickler::_depickleStereo(std::istream &ss, ROMol *mol, int version) { void MolPickler::_pickleProperties(std::ostream &ss, const RDProps &props, unsigned int pickleFlags) { - if (!pickleFlags) return; + if (!pickleFlags) { + return; + } streamWriteProps(ss, props, pickleFlags & PicklerOps::PrivateProps, pickleFlags & PicklerOps::ComputedProps, diff --git a/Code/GraphMol/MolStandardize/Charge.cpp b/Code/GraphMol/MolStandardize/Charge.cpp index c8b0370b3..767b45fe9 100644 --- a/Code/GraphMol/MolStandardize/Charge.cpp +++ b/Code/GraphMol/MolStandardize/Charge.cpp @@ -80,7 +80,7 @@ ROMol *Reionizer::reionize(const ROMol &mol) { const std::vector> abpairs = abparams->getPairs(); - ROMol *omol = new ROMol(mol); + auto *omol = new ROMol(mol); int start_charge = MolOps::getFormalCharge(*omol); for (const auto &cc : this->d_ccs) { @@ -280,7 +280,7 @@ Uncharger::~Uncharger(){}; ROMol *Uncharger::uncharge(const ROMol &mol) { BOOST_LOG(rdInfoLog) << "Running Uncharger\n"; - ROMol *omol = new ROMol(mol); + auto *omol = new ROMol(mol); std::vector p_matches; std::vector q_matches; @@ -327,12 +327,16 @@ ROMol *Uncharger::uncharge(const ROMol &mol) { if (n_matched > 0 && neg_surplus > 0) { boost::dynamic_bitset<> nonAcids(omol->getNumAtoms()); nonAcids.set(); - for (const auto pr : a_atoms) nonAcids.reset(pr.second); + for (const auto pr : a_atoms) { + nonAcids.reset(pr.second); + } unsigned int midx = 0; // zwitterion with more negative charges than quaternary positive centres while (neg_surplus > 0 && midx < n_atoms.size()) { unsigned int idx = n_atoms[midx++].second; - if (!nonAcids[idx]) continue; + if (!nonAcids[idx]) { + continue; + } Atom *atom = omol->getAtomWithIdx(idx); if (!isEarlyAtom(atom->getAtomicNum())) { @@ -366,7 +370,9 @@ ROMol *Uncharger::uncharge(const ROMol &mol) { // Until quaternary positive == negative total or no more negative atoms Atom *atom = omol->getAtomWithIdx(a_atoms[midx++].second); // skip ahead if we already neutralized this - if (atom->getFormalCharge() >= 0) continue; + if (atom->getFormalCharge() >= 0) { + continue; + } atom->setNumExplicitHs(atom->getTotalNumHs() + 1); atom->setNoImplicit(true); atom->setFormalCharge(atom->getFormalCharge() + 1); @@ -430,7 +436,9 @@ ROMol *Uncharger::uncharge(const ROMol &mol) { // the special case for C here was github #2792 if (atom->getAtomicNum() != 6 && !isEarlyAtom(atom->getAtomicNum())) { auto nExplicit = atom->getNumExplicitHs(); - if (nExplicit >= 1) atom->setNumExplicitHs(nExplicit - 1); + if (nExplicit >= 1) { + atom->setNumExplicitHs(nExplicit - 1); + } if (nExplicit == 1) { // we just removed the last one: break; @@ -443,7 +451,9 @@ ROMol *Uncharger::uncharge(const ROMol &mol) { // since we changed the number of explicit Hs, we need to update the // other valence parameters atom->updatePropertyCache(false); - if (!netCharge) break; + if (!netCharge) { + break; + } } } return omol; diff --git a/Code/GraphMol/MolStandardize/Fragment.cpp b/Code/GraphMol/MolStandardize/Fragment.cpp index 5b9543a1a..ca8718e35 100644 --- a/Code/GraphMol/MolStandardize/Fragment.cpp +++ b/Code/GraphMol/MolStandardize/Fragment.cpp @@ -10,6 +10,7 @@ #include "Fragment.h" #include #include +#include typedef boost::tokenizer> tokenizer; #include #include @@ -83,7 +84,9 @@ ROMol *FragmentRemover::remove(const ROMol &mol) { for (auto &fgci : fgrps) { size_t oCount = frags.size(); - if (!oCount) break; + if (!oCount) { + break; + } auto tfrags = frags; // remove any fragments that this frags.erase(std::remove_if( @@ -128,7 +131,9 @@ ROMol *FragmentRemover::remove(const ROMol &mol) { // remove the atoms that need to go auto *removed = new RWMol(mol); for (int i = mol.getNumAtoms() - 1; i >= 0; --i) { - if (atomsToRemove[i]) removed->removeAtom(i); + if (atomsToRemove[i]) { + removed->removeAtom(i); + } } return static_cast(removed); } @@ -162,7 +167,9 @@ ROMol *LargestFragmentChooser::choose(const ROMol &mol) { if (this->PREFER_ORGANIC) { // Skip this fragment if not organic and we already have an organic // fragment as the largest so far - if (l.Fragment != nullptr && l.Organic && !organic) continue; + if (l.Fragment != nullptr && l.Organic && !organic) { + continue; + } // Reset largest if it wasn't organic and this fragment is organic // if largest and organic and not largest['organic']: if (l.Fragment != nullptr && organic && !l.Organic) { @@ -174,19 +181,23 @@ ROMol *LargestFragmentChooser::choose(const ROMol &mol) { numatoms += 1 + at->getTotalNumHs(); } // Skip this fragment if fewer atoms than the largest - if (l.Fragment != nullptr && (numatoms < l.NumAtoms)) continue; + if (l.Fragment != nullptr && (numatoms < l.NumAtoms)) { + continue; + } // Skip this fragment if equal number of atoms but weight is lower double weight = Descriptors::calcExactMW(*frag); if (l.Fragment != nullptr && (numatoms == l.NumAtoms) && - (weight < l.Weight)) + (weight < l.Weight)) { continue; + } // Skip this fragment if equal number of atoms and equal weight but smiles // comes last alphabetically if (l.Fragment != nullptr && (numatoms == l.NumAtoms) && - (weight == l.Weight) && (smiles > l.Smiles)) + (weight == l.Weight) && (smiles > l.Smiles)) { continue; + } BOOST_LOG(rdInfoLog) << "New largest fragment: " << smiles << " (" << numatoms << ")\n"; @@ -204,11 +215,12 @@ ROMol *LargestFragmentChooser::choose(const ROMol &mol) { LargestFragmentChooser::Largest::Largest() : Smiles(""), Fragment(nullptr), NumAtoms(0), Weight(0), Organic(false) {} -LargestFragmentChooser::Largest::Largest( - std::string &smiles, const boost::shared_ptr &fragment, - unsigned int &numatoms, double &weight, bool &organic) +LargestFragmentChooser::Largest::Largest(std::string &smiles, + boost::shared_ptr fragment, + unsigned int &numatoms, double &weight, + bool &organic) : Smiles(smiles), - Fragment(fragment), + Fragment(std::move(fragment)), NumAtoms(numatoms), Weight(weight), Organic(organic) {} diff --git a/Code/GraphMol/MolStandardize/Fragment.h b/Code/GraphMol/MolStandardize/Fragment.h index f56a85dc1..b385a60c5 100644 --- a/Code/GraphMol/MolStandardize/Fragment.h +++ b/Code/GraphMol/MolStandardize/Fragment.h @@ -66,7 +66,7 @@ class RDKIT_MOLSTANDARDIZE_EXPORT LargestFragmentChooser { ROMol *choose(const ROMol &mol); struct Largest { Largest(); - Largest(std::string &smiles, const boost::shared_ptr &fragment, + Largest(std::string &smiles, boost::shared_ptr fragment, unsigned int &numatoms, double &weight, bool &organic); std::string Smiles; boost::shared_ptr Fragment; diff --git a/Code/GraphMol/MolStandardize/Normalize.cpp b/Code/GraphMol/MolStandardize/Normalize.cpp index 57e4b50a9..9c04fef30 100644 --- a/Code/GraphMol/MolStandardize/Normalize.cpp +++ b/Code/GraphMol/MolStandardize/Normalize.cpp @@ -87,7 +87,7 @@ ROMol *Normalizer::normalize(const ROMol &mol) { ROMOL_SPTR nfrag(this->normalizeFragment(*frag, transforms)); nfrags.push_back(nfrag); } - ROMol *outmol = new ROMol(*(nfrags.back())); + auto *outmol = new ROMol(*(nfrags.back())); nfrags.pop_back(); for (const auto &nfrag : nfrags) { ROMol *tmol = combineMols(*outmol, *nfrag); @@ -145,7 +145,9 @@ boost::shared_ptr Normalizer::applyTransform( MOL_SPTR_VECT mols; mols.push_back(mol); - if (!transform.isInitialized()) transform.initReactantMatchers(); + if (!transform.isInitialized()) { + transform.initReactantMatchers(); + } // REVIEW: what's the source of the 20 in the next line? for (unsigned int i = 0; i < 20; ++i) { std::vector pdts; @@ -157,7 +159,7 @@ boost::shared_ptr Normalizer::applyTransform( // std::endl; unsigned int failed; try { - RWMol *tmol = static_cast(pdt[0].get()); + auto *tmol = static_cast(pdt[0].get()); // we'll allow atoms with a valence that's too high to make it // through, but we should fail if we just created something that // can't, for example, be kekulized. @@ -185,10 +187,11 @@ boost::shared_ptr Normalizer::applyTransform( } } } - if (mols.size()) + if (mols.size()) { return mols[0]; - else + } else { return nullptr; + } } } // namespace MolStandardize diff --git a/Code/GraphMol/MolStandardize/Tautomer.cpp b/Code/GraphMol/MolStandardize/Tautomer.cpp index 7049c7153..b66c8ea35 100644 --- a/Code/GraphMol/MolStandardize/Tautomer.cpp +++ b/Code/GraphMol/MolStandardize/Tautomer.cpp @@ -20,6 +20,7 @@ #include #include #include +#include using namespace RDKit; @@ -102,9 +103,8 @@ struct SubstructTerm { std::string smarts; int score; std::shared_ptr matcher; - SubstructTerm(const std::string &aname, const std::string &asmarts, - int ascore) - : name(aname), smarts(asmarts), score(ascore) { + SubstructTerm(std::string aname, std::string asmarts, int ascore) + : name(std::move(aname)), smarts(std::move(asmarts)), score(ascore) { matcher = smarts_mol_flyweight(smarts).get().dp_mol; }; }; diff --git a/Code/GraphMol/MolTransforms/MolTransforms.cpp b/Code/GraphMol/MolTransforms/MolTransforms.cpp index 618795db3..f11ee000b 100644 --- a/Code/GraphMol/MolTransforms/MolTransforms.cpp +++ b/Code/GraphMol/MolTransforms/MolTransforms.cpp @@ -166,7 +166,9 @@ bool computePrincipalAxesAndMoments(const RDKit::Conformer &conf, RDGeom::Point3D origin(0, 0, 0); double wSum = 0.0; for (unsigned int i = 0; i < conf.getNumAtoms(); ++i) { - if (ignoreHs && mol.getAtomWithIdx(i)->getAtomicNum() == 1) continue; + if (ignoreHs && mol.getAtomWithIdx(i)->getAtomicNum() == 1) { + continue; + } double w = 1.0; if (weights) { w = (*weights)[i]; @@ -219,7 +221,9 @@ bool computePrincipalAxesAndMomentsFromGyrationMatrix( RDGeom::Point3D origin(0, 0, 0); double wSum = 0.0; for (unsigned int i = 0; i < conf.getNumAtoms(); ++i) { - if (ignoreHs && mol.getAtomWithIdx(i)->getAtomicNum() == 1) continue; + if (ignoreHs && mol.getAtomWithIdx(i)->getAtomicNum() == 1) { + continue; + } double w = 1.0; if (weights) { w = (*weights)[i]; @@ -416,13 +420,17 @@ void setBondLength(Conformer &conf, unsigned int iAtomId, unsigned int jAtomId, URANGE_CHECK(jAtomId, pos.size()); ROMol &mol = conf.getOwningMol(); Bond *bond = mol.getBondBetweenAtoms(iAtomId, jAtomId); - if (!bond) throw ValueErrorException("atoms i and j must be bonded"); - if (queryIsBondInRing(bond)) + if (!bond) { + throw ValueErrorException("atoms i and j must be bonded"); + } + if (queryIsBondInRing(bond)) { throw ValueErrorException("bond (i,j) must not belong to a ring"); + } RDGeom::Point3D v = pos[iAtomId] - pos[jAtomId]; double origValue = v.length(); - if (origValue <= 1.e-8) + if (origValue <= 1.e-8) { throw ValueErrorException("atoms i and j have identical 3D coordinates"); + } // get all atoms bonded to j std::list alist; @@ -441,12 +449,14 @@ double getAngleRad(const Conformer &conf, unsigned int iAtomId, URANGE_CHECK(kAtomId, pos.size()); RDGeom::Point3D rJI = pos[iAtomId] - pos[jAtomId]; double rJISqLength = rJI.lengthSq(); - if (rJISqLength <= 1.e-16) + if (rJISqLength <= 1.e-16) { throw ValueErrorException("atoms i and j have identical 3D coordinates"); + } RDGeom::Point3D rJK = pos[kAtomId] - pos[jAtomId]; double rJKSqLength = rJK.lengthSq(); - if (rJKSqLength <= 1.e-16) + if (rJKSqLength <= 1.e-16) { throw ValueErrorException("atoms j and k have identical 3D coordinates"); + } return rJI.angleTo(rJK); } @@ -458,21 +468,28 @@ void setAngleRad(Conformer &conf, unsigned int iAtomId, unsigned int jAtomId, URANGE_CHECK(kAtomId, pos.size()); ROMol &mol = conf.getOwningMol(); Bond *bondJI = mol.getBondBetweenAtoms(jAtomId, iAtomId); - if (!bondJI) throw ValueErrorException("atoms i and j must be bonded"); + if (!bondJI) { + throw ValueErrorException("atoms i and j must be bonded"); + } Bond *bondJK = mol.getBondBetweenAtoms(jAtomId, kAtomId); - if (!bondJK) throw ValueErrorException("atoms j and k must be bonded"); - if (queryIsBondInRing(bondJI) && queryIsBondInRing(bondJK)) + if (!bondJK) { + throw ValueErrorException("atoms j and k must be bonded"); + } + if (queryIsBondInRing(bondJI) && queryIsBondInRing(bondJK)) { throw ValueErrorException( "bonds (i,j) and (j,k) must not both belong to a ring"); + } RDGeom::Point3D rJI = pos[iAtomId] - pos[jAtomId]; double rJISqLength = rJI.lengthSq(); - if (rJISqLength <= 1.e-16) + if (rJISqLength <= 1.e-16) { throw ValueErrorException("atoms i and j have identical 3D coordinates"); + } RDGeom::Point3D rJK = pos[kAtomId] - pos[jAtomId]; double rJKSqLength = rJK.lengthSq(); - if (rJKSqLength <= 1.e-16) + if (rJKSqLength <= 1.e-16) { throw ValueErrorException("atoms j and k have identical 3D coordinates"); + } // we only need to rotate by delta with respect to the current angle value value -= rJI.angleTo(rJK); @@ -506,16 +523,19 @@ double getDihedralRad(const Conformer &conf, unsigned int iAtomId, URANGE_CHECK(lAtomId, pos.size()); RDGeom::Point3D rIJ = pos[jAtomId] - pos[iAtomId]; double rIJSqLength = rIJ.lengthSq(); - if (rIJSqLength <= 1.e-16) + if (rIJSqLength <= 1.e-16) { throw ValueErrorException("atoms i and j have identical 3D coordinates"); + } RDGeom::Point3D rJK = pos[kAtomId] - pos[jAtomId]; double rJKSqLength = rJK.lengthSq(); - if (rJKSqLength <= 1.e-16) + if (rJKSqLength <= 1.e-16) { throw ValueErrorException("atoms j and k have identical 3D coordinates"); + } RDGeom::Point3D rKL = pos[lAtomId] - pos[kAtomId]; double rKLSqLength = rKL.lengthSq(); - if (rKLSqLength <= 1.e-16) + if (rKLSqLength <= 1.e-16) { throw ValueErrorException("atoms k and l have identical 3D coordinates"); + } RDGeom::Point3D nIJK = rIJ.crossProduct(rJK); double nIJKSqLength = nIJK.lengthSq(); @@ -536,22 +556,28 @@ void setDihedralRad(Conformer &conf, unsigned int iAtomId, unsigned int jAtomId, URANGE_CHECK(lAtomId, pos.size()); ROMol &mol = conf.getOwningMol(); Bond *bondJK = mol.getBondBetweenAtoms(jAtomId, kAtomId); - if (!bondJK) throw ValueErrorException("atoms j and k must be bonded"); + if (!bondJK) { + throw ValueErrorException("atoms j and k must be bonded"); + } - if (queryIsBondInRing(bondJK)) + if (queryIsBondInRing(bondJK)) { throw ValueErrorException("bond (j,k) must not belong to a ring"); + } RDGeom::Point3D rIJ = pos[jAtomId] - pos[iAtomId]; double rIJSqLength = rIJ.lengthSq(); - if (rIJSqLength <= 1.e-16) + if (rIJSqLength <= 1.e-16) { throw ValueErrorException("atoms i and j have identical 3D coordinates"); + } RDGeom::Point3D rJK = pos[kAtomId] - pos[jAtomId]; double rJKSqLength = rJK.lengthSq(); - if (rJKSqLength <= 1.e-16) + if (rJKSqLength <= 1.e-16) { throw ValueErrorException("atoms j and k have identical 3D coordinates"); + } RDGeom::Point3D rKL = pos[lAtomId] - pos[kAtomId]; double rKLSqLength = rKL.lengthSq(); - if (rKLSqLength <= 1.e-16) + if (rKLSqLength <= 1.e-16) { throw ValueErrorException("atoms k and l have identical 3D coordinates"); + } RDGeom::Point3D nIJK = rIJ.crossProduct(rJK); double nIJKSqLength = nIJK.lengthSq(); diff --git a/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp b/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp index 6b4dfd01d..860157624 100644 --- a/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp +++ b/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp @@ -31,8 +31,8 @@ PyObject *computeCanonTrans(const Conformer &conf, npy_intp dims[2]; dims[0] = 4; dims[1] = 4; - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); - double *resData = reinterpret_cast(PyArray_DATA(res)); + auto *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); + auto *resData = reinterpret_cast(PyArray_DATA(res)); const double *tdata = trans->getData(); memcpy(static_cast(resData), static_cast(tdata), 4 * 4 * sizeof(double)); @@ -48,16 +48,18 @@ PyObject *computePrincAxesMomentsHelper(bool func(const Conformer &, bool ignoreHs, const python::object &weights) { Eigen::Matrix3d axes; Eigen::Vector3d moments; - std::vector *weightsVecPtr = NULL; + std::vector *weightsVecPtr = nullptr; std::vector weightsVec; size_t i; if (weights != python::object()) { size_t numElements = python::extract(weights.attr("__len__")()); - if (numElements != conf.getNumAtoms()) + if (numElements != conf.getNumAtoms()) { throw ValueErrorException("The Python container must have length equal to conf.GetNumAtoms()"); + } weightsVec.resize(numElements); - for (i = 0; i < numElements; ++i) + for (i = 0; i < numElements; ++i) { weightsVec[i] = python::extract(weights[i]); + } weightsVecPtr = &weightsVec; } PyObject *res = PyTuple_New(2); @@ -66,17 +68,19 @@ PyObject *computePrincAxesMomentsHelper(bool func(const Conformer &, npy_intp dims[2]; dims[0] = 3; dims[1] = 3; - PyArrayObject *axesNpy = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); - double *axesNpyData = reinterpret_cast(PyArray_DATA(axesNpy)); + auto *axesNpy = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); + auto *axesNpyData = reinterpret_cast(PyArray_DATA(axesNpy)); i = 0; for (size_t y = 0; y < 3; ++y) { - for (size_t x = 0; x < 3; ++x) + for (size_t x = 0; x < 3; ++x) { axesNpyData[i++] = axes(y, x); + } } - PyArrayObject *momentsNpy = (PyArrayObject *)PyArray_SimpleNew(1, dims, NPY_DOUBLE); - double *momentsNpyData = reinterpret_cast(PyArray_DATA(momentsNpy)); - for (size_t y = 0; y < 3; ++y) + auto *momentsNpy = (PyArrayObject *)PyArray_SimpleNew(1, dims, NPY_DOUBLE); + auto *momentsNpyData = reinterpret_cast(PyArray_DATA(momentsNpy)); + for (size_t y = 0; y < 3; ++y) { momentsNpyData[y] = moments(y); + } res = PyTuple_New(2); PyTuple_SetItem(res, 0, (PyObject *)axesNpy); PyTuple_SetItem(res, 1, (PyObject *)momentsNpy); @@ -106,10 +110,10 @@ void transConformer(Conformer &conf, python::object trans) { if (!PyArray_Check(transObj)) { throw_value_error("Expecting a numeric array for transformation"); } - PyArrayObject *transMat = reinterpret_cast(transObj); + auto *transMat = reinterpret_cast(transObj); unsigned int nrows = PyArray_DIM(transMat, 0); unsigned int dSize = nrows * nrows; - double *inData = reinterpret_cast(PyArray_DATA(transMat)); + auto *inData = reinterpret_cast(PyArray_DATA(transMat)); RDGeom::Transform3D transform; double *tData = transform.getData(); memcpy(static_cast(tData), static_cast(inData), diff --git a/Code/GraphMol/PartialCharges/GasteigerParams.cpp b/Code/GraphMol/PartialCharges/GasteigerParams.cpp index 4505001ee..298e1f1ec 100644 --- a/Code/GraphMol/PartialCharges/GasteigerParams.cpp +++ b/Code/GraphMol/PartialCharges/GasteigerParams.cpp @@ -75,7 +75,9 @@ typedef boost::flyweight< GasteigerParams::GasteigerParams(std::string paramData) { boost::char_separator eolSep("\n"); boost::char_separator spaceSep(" \t"); - if (paramData == "") paramData = defaultParamData + additionalParamData; + if (paramData == "") { + paramData = defaultParamData + additionalParamData; + } tokenizer lines(paramData, eolSep); d_paramMap.clear(); std::istringstream istr; diff --git a/Code/GraphMol/PeriodicTable.cpp b/Code/GraphMol/PeriodicTable.cpp index 7981b0abd..194f7f72e 100644 --- a/Code/GraphMol/PeriodicTable.cpp +++ b/Code/GraphMol/PeriodicTable.cpp @@ -67,21 +67,29 @@ PeriodicTable::PeriodicTable() { istr >> anum; atomicData &adata = byanum[anum]; ++token; - if (token == tokens.end()) continue; + if (token == tokens.end()) { + continue; + } ++token; - if (token == tokens.end()) continue; + if (token == tokens.end()) { + continue; + } unsigned int isotope; istr.clear(); istr.str(*token); istr >> isotope; ++token; - if (token == tokens.end()) continue; + if (token == tokens.end()) { + continue; + } double mass; istr.clear(); istr.str(*token); istr >> mass; ++token; - if (token == tokens.end()) continue; + if (token == tokens.end()) { + continue; + } double abundance; istr.clear(); istr.str(*token); @@ -101,7 +109,9 @@ PeriodicTable *PeriodicTable::getTable() { static std::once_flag pt_init_once; std::call_once(pt_init_once, initInstance); #else - if (!ds_instance) initInstance(); + if (!ds_instance) { + initInstance(); + } #endif return ds_instance.get(); } diff --git a/Code/GraphMol/QueryAtom.cpp b/Code/GraphMol/QueryAtom.cpp index 9d41efa7b..9782c0263 100644 --- a/Code/GraphMol/QueryAtom.cpp +++ b/Code/GraphMol/QueryAtom.cpp @@ -121,7 +121,9 @@ bool queriesMatch(QueryAtom::QUERYATOM_QUERY const *q1, res = true; } } - if (res) break; + if (res) { + break; + } } } else if (d1 == "AtomAnd") { res = true; diff --git a/Code/GraphMol/QueryBond.cpp b/Code/GraphMol/QueryBond.cpp index fce0b017b..765056532 100644 --- a/Code/GraphMol/QueryBond.cpp +++ b/Code/GraphMol/QueryBond.cpp @@ -14,10 +14,11 @@ namespace RDKit { QueryBond::QueryBond(BondType bT) : Bond(bT) { - if (bT != Bond::UNSPECIFIED) + if (bT != Bond::UNSPECIFIED) { dp_query = makeBondOrderEqualsQuery(bT); - else + } else { dp_query = makeBondNullQuery(); + } }; QueryBond::~QueryBond() { @@ -146,7 +147,9 @@ bool queriesMatch(QueryBond::QUERYBOND_QUERY const *q1, res = true; } } - if (res) break; + if (res) { + break; + } } } else if (d1 == "BondAnd") { res = true; diff --git a/Code/GraphMol/QueryOps.cpp b/Code/GraphMol/QueryOps.cpp index 94f0fc06b..310665963 100644 --- a/Code/GraphMol/QueryOps.cpp +++ b/Code/GraphMol/QueryOps.cpp @@ -196,20 +196,20 @@ unsigned int queryAtomAllBondProduct(Atom const *at) { } ATOM_EQUALS_QUERY *makeAtomImplicitValenceQuery(int what) { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(what, queryAtomImplicitValence); res->setDescription("AtomImplicitValence"); return res; } ATOM_EQUALS_QUERY *makeAtomExplicitValenceQuery(int what) { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(what, queryAtomExplicitValence); res->setDescription("AtomExplicitValence"); return res; } ATOM_EQUALS_QUERY *makeAtomTotalValenceQuery(int what) { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(what, queryAtomTotalValence); res->setDescription("AtomTotalValence"); return res; @@ -225,125 +225,120 @@ ATOM_EQUALS_QUERY *makeAtomTypeQuery(int num, int aromatic) { queryAtomType, "AtomType"); } ATOM_EQUALS_QUERY *makeAtomExplicitDegreeQuery(int what) { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(what, queryAtomExplicitDegree); res->setDescription("AtomExplicitDegree"); return res; } ATOM_EQUALS_QUERY *makeAtomTotalDegreeQuery(int what) { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(what, queryAtomTotalDegree); res->setDescription("AtomTotalDegree"); return res; } ATOM_EQUALS_QUERY *makeAtomHeavyAtomDegreeQuery(int what) { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(what, queryAtomHeavyAtomDegree); res->setDescription("AtomHeavyAtomDegree"); return res; } ATOM_EQUALS_QUERY *makeAtomHCountQuery(int what) { - ATOM_EQUALS_QUERY *res = - makeAtomSimpleQuery(what, queryAtomHCount); + auto *res = makeAtomSimpleQuery(what, queryAtomHCount); res->setDescription("AtomHCount"); return res; } ATOM_EQUALS_QUERY *makeAtomImplicitHCountQuery(int what) { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(what, queryAtomImplicitHCount); res->setDescription("AtomImplicitHCount"); return res; } ATOM_EQUALS_QUERY *makeAtomHasImplicitHQuery() { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(true, queryAtomHasImplicitH); res->setDescription("AtomHasImplicitH"); return res; } ATOM_EQUALS_QUERY *makeAtomAromaticQuery() { - ATOM_EQUALS_QUERY *res = - makeAtomSimpleQuery(true, queryAtomAromatic); + auto *res = makeAtomSimpleQuery(true, queryAtomAromatic); res->setDescription("AtomIsAromatic"); return res; } ATOM_EQUALS_QUERY *makeAtomAliphaticQuery() { - ATOM_EQUALS_QUERY *res = - makeAtomSimpleQuery(true, queryAtomAliphatic); + auto *res = makeAtomSimpleQuery(true, queryAtomAliphatic); res->setDescription("AtomIsAliphatic"); return res; } ATOM_EQUALS_QUERY *makeAtomUnsaturatedQuery() { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(true, queryAtomUnsaturated); res->setDescription("AtomUnsaturated"); return res; } ATOM_EQUALS_QUERY *makeAtomMassQuery(int what) { - ATOM_EQUALS_QUERY *res = makeAtomSimpleQuery( + auto *res = makeAtomSimpleQuery( massIntegerConversionFactor * what, queryAtomMass); res->setDescription("AtomMass"); return res; } ATOM_EQUALS_QUERY *makeAtomIsotopeQuery(int what) { - ATOM_EQUALS_QUERY *res = - makeAtomSimpleQuery(what, queryAtomIsotope); + auto *res = makeAtomSimpleQuery(what, queryAtomIsotope); res->setDescription("AtomIsotope"); return res; } ATOM_EQUALS_QUERY *makeAtomFormalChargeQuery(int what) { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(what, queryAtomFormalCharge); res->setDescription("AtomFormalCharge"); return res; } ATOM_EQUALS_QUERY *makeAtomNegativeFormalChargeQuery(int what) { - ATOM_EQUALS_QUERY *res = makeAtomSimpleQuery( + auto *res = makeAtomSimpleQuery( what, queryAtomNegativeFormalCharge); res->setDescription("AtomNegativeFormalCharge"); return res; } ATOM_EQUALS_QUERY *makeAtomHybridizationQuery(int what) { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(what, queryAtomHybridization); res->setDescription("AtomHybridization"); return res; } ATOM_EQUALS_QUERY *makeAtomNumRadicalElectronsQuery(int what) { - ATOM_EQUALS_QUERY *res = makeAtomSimpleQuery( + auto *res = makeAtomSimpleQuery( what, queryAtomNumRadicalElectrons); res->setDescription("AtomNumRadicalElectrons"); return res; } ATOM_EQUALS_QUERY *makeAtomHasChiralTagQuery() { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(true, queryAtomHasChiralTag); res->setDescription("AtomHasChiralTag"); return res; } ATOM_EQUALS_QUERY *makeAtomMissingChiralTagQuery() { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(true, queryAtomMissingChiralTag); res->setDescription("AtomMissingChiralTag"); return res; } ATOM_EQUALS_QUERY *makeAtomInRingQuery() { - ATOM_EQUALS_QUERY *res = - makeAtomSimpleQuery(true, queryIsAtomInRing); + auto *res = makeAtomSimpleQuery(true, queryIsAtomInRing); res->setDescription("AtomInRing"); return res; } @@ -371,7 +366,7 @@ ATOM_EQUALS_QUERY *makeAAtomQuery() { return res; } ATOM_EQUALS_QUERY *makeAHAtomQuery() { - ATOM_EQUALS_QUERY *res = rdcast(makeAtomNullQuery()); + auto *res = rdcast(makeAtomNullQuery()); return res; } @@ -468,34 +463,34 @@ ATOM_EQUALS_QUERY *makeAtomInNRingsQuery(int what) { } ATOM_EQUALS_QUERY *makeAtomHasRingBondQuery() { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(true, queryAtomHasRingBond); res->setDescription("AtomHasRingBond"); return res; } ATOM_EQUALS_QUERY *makeAtomNumHeteroatomNbrsQuery(int what) { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(what, queryAtomNumHeteroatomNbrs); res->setDescription("AtomNumHeteroatomNeighbors"); return res; } ATOM_EQUALS_QUERY *makeAtomHasHeteroatomNbrsQuery() { - ATOM_EQUALS_QUERY *res = + auto *res = makeAtomSimpleQuery(true, queryAtomHasHeteroatomNbrs); res->setDescription("AtomHasHeteroatomNeighbors"); return res; } ATOM_EQUALS_QUERY *makeAtomNumAliphaticHeteroatomNbrsQuery(int what) { - ATOM_EQUALS_QUERY *res = makeAtomSimpleQuery( + auto *res = makeAtomSimpleQuery( what, queryAtomNumAliphaticHeteroatomNbrs); res->setDescription("AtomNumAliphaticHeteroatomNeighbors"); return res; } ATOM_EQUALS_QUERY *makeAtomHasAliphaticHeteroatomNbrsQuery() { - ATOM_EQUALS_QUERY *res = makeAtomSimpleQuery( + auto *res = makeAtomSimpleQuery( true, queryAtomHasAliphaticHeteroatomNbrs); res->setDescription("AtomHasAliphaticHeteroatomNeighbors"); return res; @@ -566,25 +561,35 @@ ATOM_NULL_QUERY *makeAtomNullQuery() { } bool isComplexQuery(const Bond *b) { - if (!b->hasQuery()) return false; + if (!b->hasQuery()) { + return false; + } // negated things are always complex: - if (b->getQuery()->getNegation()) return true; + if (b->getQuery()->getNegation()) { + return true; + } std::string descr = b->getQuery()->getDescription(); - if (descr == "BondOrder" || descr == "SingleOrAromaticBond") return false; - if (descr == "BondAnd" || descr == "BondXor") return true; + if (descr == "BondOrder" || descr == "SingleOrAromaticBond") { + return false; + } + if (descr == "BondAnd" || descr == "BondXor") { + return true; + } if (descr == "BondOr") { // detect the types of queries that appear for unspecified bonds in SMARTS: if (b->getQuery()->endChildren() - b->getQuery()->beginChildren() == 2) { for (auto child = b->getQuery()->beginChildren(); child != b->getQuery()->endChildren(); ++child) { if ((*child)->getDescription() != "BondOrder" || - (*child)->getNegation()) + (*child)->getNegation()) { return true; + } if (static_cast(child->get())->getVal() != Bond::SINGLE && static_cast(child->get())->getVal() != - Bond::AROMATIC) + Bond::AROMATIC) { return true; + } } return false; } @@ -594,41 +599,59 @@ bool isComplexQuery(const Bond *b) { } bool _complexQueryHelper(Atom::QUERYATOM_QUERY const *query, bool &hasAtNum) { - if (!query) return false; - if (query->getNegation()) return true; + if (!query) { + return false; + } + if (query->getNegation()) { + return true; + } std::string descr = query->getDescription(); // std::cerr<<" |"<beginChildren(); while (childIt != query->endChildren()) { - if (_complexQueryHelper(childIt->get(), hasAtNum)) return true; + if (_complexQueryHelper(childIt->get(), hasAtNum)) { + return true; + } ++childIt; } } return false; } bool isComplexQuery(const Atom *a) { - if (!a->hasQuery()) return false; + if (!a->hasQuery()) { + return false; + } // std::cerr<<"\n"<getIdx(); // negated things are always complex: - if (a->getQuery()->getNegation()) return true; + if (a->getQuery()->getNegation()) { + return true; + } std::string descr = a->getQuery()->getDescription(); // std::cerr<<" "<getQuery(), hasAtNum)) return true; - if (hasAtNum) - return false; - else + if (_complexQueryHelper(a->getQuery(), hasAtNum)) { return true; + } + if (hasAtNum) { + return false; + } else { + return true; + } } return true; @@ -643,14 +666,20 @@ bool isAtomAromatic(const Atom *a) { res = a->getIsAromatic(); } else if (descr == "AtomIsAromatic") { res = true; - if (a->getQuery()->getNegation()) res = !res; + if (a->getQuery()->getNegation()) { + res = !res; + } } else if (descr == "AtomIsAliphatic") { res = false; - if (a->getQuery()->getNegation()) res = !res; + if (a->getQuery()->getNegation()) { + res = !res; + } } else if (descr == "AtomType") { res = getAtomTypeIsAromatic( static_cast(a->getQuery())->getVal()); - if (a->getQuery()->getNegation()) res = !res; + if (a->getQuery()->getNegation()) { + res = !res; + } } else if (descr == "AtomAnd") { auto childIt = a->getQuery()->beginChildren(); if ((*childIt)->getDescription() == "AtomAtomicNum") { diff --git a/Code/GraphMol/RGroupDecomposition/RGroupDecomp.cpp b/Code/GraphMol/RGroupDecomposition/RGroupDecomp.cpp index 899d36fd8..6a5cb33f6 100644 --- a/Code/GraphMol/RGroupDecomposition/RGroupDecomp.cpp +++ b/Code/GraphMol/RGroupDecomposition/RGroupDecomp.cpp @@ -130,14 +130,16 @@ bool setLabel(Atom *atom, int label, std::set &labels, int &maxLabel, if (label) { if (labels.find(label) != labels.end()) { if (relabel) { - if (type == Labelling::INTERNAL_LABELS) + if (type == Labelling::INTERNAL_LABELS) { std::cerr << "WARNING: relabelling existing label" << std::endl; + } label = maxLabel + 1; - } else + } else { // XXX FIX me - get label id throw ValueErrorException( std::string("Duplicate label in input, current type is:") + labellingToString(type)); + } } atom->setProp(RLABEL, label); @@ -151,7 +153,9 @@ bool setLabel(Atom *atom, int label, std::set &labels, int &maxLabel, bool hasDummy(const RWMol &core) { for (RWMol::ConstAtomIterator atIt = core.beginAtoms(); atIt != core.endAtoms(); ++atIt) { - if ((*atIt)->getAtomicNum() == 0) return true; + if ((*atIt)->getAtomicNum() == 0) { + return true; + } } return false; } @@ -159,26 +163,37 @@ bool hasDummy(const RWMol &core) { unsigned int RGroupDecompositionParameters::autoGetLabels(const RWMol &core) { unsigned int autoLabels = 0; - if (!onlyMatchAtRGroups) autoLabels = AtomIndexLabels; + if (!onlyMatchAtRGroups) { + autoLabels = AtomIndexLabels; + } bool hasMDLRGroup = false; bool hasAtomMapNum = false; bool hasIsotopes = false; bool hasDummies = false; for (auto atm : core.atoms()) { - if (atm->getIsotope()) hasIsotopes = true; - if (atm->getAtomMapNum()) hasAtomMapNum = true; - if (atm->hasProp(common_properties::_MolFileRLabel)) hasMDLRGroup = true; - if (atm->getAtomicNum() == 0) hasDummies = true; + if (atm->getIsotope()) { + hasIsotopes = true; + } + if (atm->getAtomMapNum()) { + hasAtomMapNum = true; + } + if (atm->hasProp(common_properties::_MolFileRLabel)) { + hasMDLRGroup = true; + } + if (atm->getAtomicNum() == 0) { + hasDummies = true; + } } - if (hasMDLRGroup) + if (hasMDLRGroup) { return autoLabels | MDLRGroupLabels; - else if (hasAtomMapNum) + } else if (hasAtomMapNum) { return autoLabels | AtomMapLabels; - else if (hasIsotopes) + } else if (hasIsotopes) { return autoLabels | IsotopeLabels; - else if (hasDummies) + } else if (hasDummies) { return autoLabels | DummyAtomLabels; + } return autoLabels; } @@ -252,8 +267,9 @@ bool RGroupDecompositionParameters::prepareCore(RWMol &core, if (atom->hasProp(RLABEL)) { if (setLabel(atom, atom->getProp(RLABEL), foundLabels, maxLabel, - relabel, Labelling::INTERNAL_LABELS)) + relabel, Labelling::INTERNAL_LABELS)) { found = true; + } } if (!found && (autoLabels & MDLRGroupLabels)) { @@ -261,29 +277,33 @@ bool RGroupDecompositionParameters::prepareCore(RWMol &core, if (atom->getPropIfPresent( common_properties::_MolFileRLabel, rgroup)) { if (setLabel(atom, rdcast(rgroup), foundLabels, maxLabel, relabel, - Labelling::RGROUP_LABELS)) + Labelling::RGROUP_LABELS)) { found = true; + } } } if (!found && (autoLabels & IsotopeLabels) && atom->getIsotope() > 0) { if (setLabel(atom, rdcast(atom->getIsotope()), foundLabels, maxLabel, - relabel, Labelling::ISOTOPE_LABELS)) + relabel, Labelling::ISOTOPE_LABELS)) { found = true; + } } if (!found && (autoLabels & AtomMapLabels) && atom->getAtomMapNum() > 0) { if (setLabel(atom, rdcast(atom->getAtomMapNum()), foundLabels, - maxLabel, relabel, Labelling::ATOMMAP_LABELS)) + maxLabel, relabel, Labelling::ATOMMAP_LABELS)) { found = true; + } } if (!found && (autoLabels & DummyAtomLabels) && atom->getAtomicNum() == 0) { const bool forceRelabellingWithDummies = true; int defaultDummyStartLabel = 1; if (setLabel(atom, defaultDummyStartLabel, foundLabels, maxLabel, - forceRelabellingWithDummies, Labelling::DUMMY_LABELS)) + forceRelabellingWithDummies, Labelling::DUMMY_LABELS)) { found = true; + } } // Unless there is an MCS match from above, we need to give different @@ -292,8 +312,9 @@ bool RGroupDecompositionParameters::prepareCore(RWMol &core, // potential rgroups and haven't been assigned yet) if (!found && (autoLabels & AtomIndexLabels)) { if (setLabel(atom, indexOffset - atom->getIdx(), foundLabels, maxLabel, - relabel, Labelling::INDEX_LABELS)) + relabel, Labelling::INDEX_LABELS)) { nextOffset++; + } found = true; } @@ -344,7 +365,9 @@ struct RGroupData { const std::vector &rlabel_attachments) { // some fragments can be add multiple times if they are cyclic for (auto &mol : mols) { - if (newMol.get() == mol.get()) return; + if (newMol.get() == mol.get()) { + return; + } } labelled = false; @@ -375,8 +398,9 @@ struct RGroupData { atIt != combinedMol->endAtoms(); ++atIt) { Atom *atom = *atIt; int rlabel; - if (atom->getPropIfPresent(RLABEL, rlabel)) + if (atom->getPropIfPresent(RLABEL, rlabel)) { rlabelsUsedCount[rlabel] += 1; + } } return rlabelsUsedCount; } @@ -385,7 +409,9 @@ struct RGroupData { for (const auto &mol : mols) { for (ROMol::AtomIterator atIt = mol->beginAtoms(); atIt != mol->endAtoms(); ++atIt) { - if ((*atIt)->getAtomicNum() > 1) return false; + if ((*atIt)->getAtomicNum() > 1) { + return false; + } } } return true; @@ -396,7 +422,9 @@ struct RGroupData { const { // compute the canonical smiles for the attachments std::string s; for (const auto &it : smilesSet) { - if (s.length()) s += "."; + if (s.length()) { + s += "."; + } s += it; } return s; @@ -418,8 +446,9 @@ struct RGroupMatch { }; void ADD_MATCH(R_DECOMP &match, int rlabel) { - if (match.find(rlabel) == match.end()) + if (match.find(rlabel) == match.end()) { match[rlabel] = boost::make_shared(); + } } struct CartesianProduct { @@ -432,8 +461,9 @@ struct CartesianProduct { sizes(inputSizes), permutationCount(0) { maxPermutations = 1; - for (unsigned long size : sizes) + for (unsigned long size : sizes) { maxPermutations *= size; // may overflow.... + } } bool next() { @@ -446,7 +476,9 @@ struct CartesianProduct { } bool increment(size_t rowToIncrement) { - if (permutationCount > maxPermutations) return false; + if (permutationCount > maxPermutations) { + return false; + } permutation[rowToIncrement] += 1; size_t max_index_of_row = sizes[rowToIncrement] - 1; @@ -546,7 +578,9 @@ double score(const std::vector &permutation, for (size_t i = 0; i < equivalentRGroupCount.size(); ++i) { auto lscore = equivalentRGroupCount[i] / ((i + 1) * (double)matches.size()); - if (lscore > 0) tempScore *= lscore * lscore; + if (lscore > 0) { + tempScore *= lscore * lscore; + } #ifdef DEBUG std::cerr << " lscore^2 " << i << ": " << lscore * lscore << std::endl; #endif @@ -560,7 +594,9 @@ double score(const std::vector &permutation, linkerMatchSet.begin(); it != linkerMatchSet.end(); ++it) { if (it->second > 1) { - if (it->second > maxLinkerMatches) maxLinkerMatches = it->second; + if (it->second > maxLinkerMatches) { + maxLinkerMatches = it->second; + } } } #ifdef DEBUG @@ -740,8 +776,9 @@ struct RGroupDecompData { int next() { int i=1; - while( labels_used.find(i) != labels_used.end() ) - ++i; + while (labels_used.find(i) != labels_used.end()) { + ++i; + } labels_used.insert(i); return i; } @@ -772,7 +809,9 @@ struct RGroupDecompData { // Deal with user supplied labels for (auto rlabels : atoms) { int userLabel = rlabels.first; - if (userLabel < 0) continue; // not a user specified label + if (userLabel < 0) { + continue; // not a user specified label + } Atom *atom = rlabels.second; mappings[userLabel] = userLabel; used_labels.add(userLabel); @@ -816,12 +855,14 @@ struct RGroupDecompData { // Deal with multiple bonds to the same label for (auto &extraAtomRLabel : extraAtomRLabels) { auto atm = atoms.find(extraAtomRLabel.first); - if (atm == atoms.end()) continue; // label not used in the rgroup + if (atm == atoms.end()) { + continue; // label not used in the rgroup + } Atom *atom = atm->second; - for (size_t i = 0; i < extraAtomRLabel.second.size(); ++i) { - int rlabel = used_labels.next(); - extraAtomRLabel.second[i] = rlabel; + for (int &i : extraAtomRLabel.second) { + int rlabel = used_labels.next(); + i = rlabel; // Is this necessary? CHECK_INVARIANT( atom->getAtomicNum() > 1, @@ -910,12 +951,16 @@ struct RGroupDecompData { std::map> extraAtomRLabels; for (auto &it : best) { - for (auto rit = it.rgroups.begin(); rit != it.rgroups.end(); ++rit) { - if (rit->first >= 0) userLabels.insert(rit->first); - if (rit->first < 0) indexLabels.insert(rit->first); + for (auto &rgroup : it.rgroups) { + if (rgroup.first >= 0) { + userLabels.insert(rgroup.first); + } + if (rgroup.first < 0) { + indexLabels.insert(rgroup.first); + } std::map rlabelsUsedInRGroup = - rit->second->getNumBondsToRlabels(); + rgroup.second->getNumBondsToRlabels(); for (auto &numBondsUsed : rlabelsUsedInRGroup) { // Make space for the extra labels if (numBondsUsed.second > 1) { // multiple rgroup bonds to same atom @@ -941,8 +986,8 @@ struct RGroupDecompData { } for (auto &it : best) { - for (auto rit = it.rgroups.begin(); rit != it.rgroups.end(); ++rit) { - relabelRGroup(*rit->second, finalRlabelMapping); + for (auto &rgroup : it.rgroups) { + relabelRGroup(*rgroup.second, finalRlabelMapping); } } } @@ -969,7 +1014,9 @@ struct RGroupDecompData { } bool process(bool pruneMatches, bool finalize = false) { - if (matches.size() == 0) return false; + if (matches.size() == 0) { + return false; + } // Exhaustive search, get the MxN matrix size_t M = matches.size(); // Number of molecules @@ -999,7 +1046,9 @@ struct RGroupDecompData { // [m1_permutation_idx, m2_permutation_idx, m3_permutation_idx] while (iterator.next()) { - if (count > N) throw ValueErrorException("Next did not finish"); + if (count > N) { + throw ValueErrorException("Next did not finish"); + } #ifdef DEBUG std::cerr << "**************************************************" << std::endl; @@ -1120,7 +1169,9 @@ int RGroupDecomposition::add(const ROMol &inmol) { } } } - if (!passes_filter) break; + if (!passes_filter) { + break; + } } if (passes_filter) { @@ -1137,7 +1188,9 @@ int RGroupDecomposition::add(const ROMol &inmol) { if (data->matches.size() == 0) { // Greedy strategy just grabs the first match and // takes the best matches from the rest - if (data->params.matchingStrategy == Greedy) tmatches.resize(1); + if (data->params.matchingStrategy == Greedy) { + tmatches.resize(1); + } } } core = &coreIt->second; @@ -1146,7 +1199,9 @@ int RGroupDecomposition::add(const ROMol &inmol) { } } - if (core == nullptr) return -1; + if (core == nullptr) { + return -1; + } // strategies // ========== @@ -1233,7 +1288,9 @@ int RGroupDecomposition::add(const ROMol &inmol) { for (int aIdx = newCore.getNumAtoms() - 1; aIdx >= 0; --aIdx) { Atom *atom = newCore.getAtomWithIdx(aIdx); - if (!atom->hasProp("keep")) newCore.removeAtom(atom); + if (!atom->hasProp("keep")) { + newCore.removeAtom(atom); + } } if (newCore.getNumAtoms()) { std::string newCoreSmi = MolToSmiles(newCore, true); @@ -1279,8 +1336,9 @@ int RGroupDecomposition::add(const ROMol &inmol) { if (size) { if (data->params.matchingStrategy & Greedy || (data->params.matchingStrategy & GreedyChunks && size > 1 && - size % data->params.chunkSize == 0)) + size % data->params.chunkSize == 0)) { data->process(true); + } } return data->matches.size() - 1; } @@ -1363,7 +1421,9 @@ RGroupColumns RGroupDecomposition::getRGroupsAsColumns() const { Rs_seen.set(rgrp_pos_map[realLabel->second]); std::string r = std::string("R") + std::to_string(realLabel->second); RGroupColumn &col = groups[r]; - if (molidx && col.size() < (size_t)(molidx - 1)) col.resize(molidx - 1); + if (molidx && col.size() < (size_t)(molidx - 1)) { + col.resize(molidx - 1); + } col.push_back(rgroup->second->combinedMol); } // add empty entries to columns where this molecule didn't appear @@ -1383,7 +1443,9 @@ std::vector Decomp(RGroupDecomposition &decomp, std::vector unmatched; for (size_t i = 0; i < mols.size(); ++i) { int v = decomp.add(*mols[i].get()); - if (v == -1) unmatched.push_back(i); + if (v == -1) { + unmatched.push_back(i); + } } decomp.process(); return unmatched; @@ -1396,7 +1458,9 @@ unsigned int RGroupDecompose(const std::vector &cores, const RGroupDecompositionParameters &options) { RGroupDecomposition decomp(cores, options); std::vector unmatched = Decomp(decomp, mols); - if (unmatchedIndices) *unmatchedIndices = unmatched; + if (unmatchedIndices) { + *unmatchedIndices = unmatched; + } rows = decomp.getRGroupsAsRows(); return mols.size() - unmatched.size(); } @@ -1408,7 +1472,9 @@ unsigned int RGroupDecompose(const std::vector &cores, const RGroupDecompositionParameters &options) { RGroupDecomposition decomp(cores, options); std::vector unmatched = Decomp(decomp, mols); - if (unmatchedIndices) *unmatchedIndices = unmatched; + if (unmatchedIndices) { + *unmatchedIndices = unmatched; + } columns = decomp.getRGroupsAsColumns(); return mols.size() - unmatched.size(); } diff --git a/Code/GraphMol/RGroupDecomposition/Wrap/rdRGroupComposition.cpp b/Code/GraphMol/RGroupDecomposition/Wrap/rdRGroupComposition.cpp index ebdbe38ab..8450dd690 100644 --- a/Code/GraphMol/RGroupDecomposition/Wrap/rdRGroupComposition.cpp +++ b/Code/GraphMol/RGroupDecomposition/Wrap/rdRGroupComposition.cpp @@ -66,7 +66,9 @@ class RGroupDecompositionHelper { MOL_SPTR_VECT coreMols; python::stl_input_iterator iter(cores), end; while (iter != end) { - if (!*iter) throw_value_error("reaction called with None reactants"); + if (!*iter) { + throw_value_error("reaction called with None reactants"); + } coreMols.push_back(*iter); ++iter; } @@ -135,7 +137,9 @@ python::object RGroupDecomp(python::object cores, python::object mols, python::stl_input_iterator iter(mols), end; unsigned int idx = 0; while (iter != end) { - if (!*iter) throw_value_error("reaction called with None reactants"); + if (!*iter) { + throw_value_error("reaction called with None reactants"); + } if (decomp.Add(*(*iter)) == -1) { unmatched.append(idx); } @@ -158,7 +162,7 @@ struct rgroupdecomp_wrapper { boost::python::type_id(); const boost::python::converter::registration *reg = boost::python::converter::registry::query(info); - if (reg == NULL || (*reg).m_to_python == NULL) { + if (reg == nullptr || (*reg).m_to_python == nullptr) { python::class_("MOL_SPTR_VECT") .def(python::vector_indexing_suite()); } diff --git a/Code/GraphMol/RGroupDecomposition/testRGroupDecomp.cpp b/Code/GraphMol/RGroupDecomposition/testRGroupDecomp.cpp index 5c5ec14c5..6a89035fa 100644 --- a/Code/GraphMol/RGroupDecomposition/testRGroupDecomp.cpp +++ b/Code/GraphMol/RGroupDecomposition/testRGroupDecomp.cpp @@ -49,7 +49,9 @@ void CHECK_RGROUP(RGroupRows::const_iterator &it, std::string expected, int i = 0; for (auto rgroups = it->begin(); rgroups != it->end(); ++rgroups, ++i) { - if (i) str << " "; + if (i) { + str << " "; + } // rlabel:smiles str << rgroups->first << ":" << MolToSmiles(*rgroups->second.get(), true); } @@ -60,7 +62,9 @@ void CHECK_RGROUP(RGroupRows::const_iterator &it, std::string expected, std::cerr << "Got: '" << result << "'" << std::endl; } - if (doassert) TEST_ASSERT(result == expected); + if (doassert) { + TEST_ASSERT(result == expected); + } } void DUMP_RGROUP(RGroupRows::const_iterator &it, std::string &result) { @@ -505,8 +509,8 @@ void testMatchOnlyAtRgroupHs() { params.onlyMatchAtRGroups = true; RGroupDecomposition decomp(*core, params); const char *smilesData[2] = {"OCC", "COCC"}; - for (int i = 0; i < 2; ++i) { - ROMol *mol = SmilesToMol(smilesData[i]); + for (auto &i : smilesData) { + ROMol *mol = SmilesToMol(i); decomp.add(*mol); delete mol; } @@ -560,8 +564,8 @@ M END 2 3 1 0 0 0 0 M END )CTAB"}; - for (int i = 0; i < 2; ++i) { - ROMol *mol = MolBlockToMol(chains[i]); + for (const auto &chain : chains) { + ROMol *mol = MolBlockToMol(chain); decomp.add(*mol); delete mol; } diff --git a/Code/GraphMol/ROMol.cpp b/Code/GraphMol/ROMol.cpp index 40b7416be..455974d92 100644 --- a/Code/GraphMol/ROMol.cpp +++ b/Code/GraphMol/ROMol.cpp @@ -61,7 +61,9 @@ ROMol::ROMol(const std::string &pickle) : RDProps() { } void ROMol::initFromOther(const ROMol &other, bool quickCopy, int confId) { - if (this == &other) return; + if (this == &other) { + return; + } numBonds = 0; // std::cerr<<" init from other: "<getAtomicNum() > 1) ++res; + if ((*ai)->getAtomicNum() > 1) { + ++res; + } } return res; }; @@ -286,7 +292,9 @@ Bond *ROMol::getBondWithIdx(unsigned int idx) { URANGE_CHECK(idx, getNumBonds()); BOND_ITER_PAIR bIter = getEdges(); - for (unsigned int i = 0; i < idx; i++) ++bIter.first; + for (unsigned int i = 0; i < idx; i++) { + ++bIter.first; + } Bond *res = d_graph[*(bIter.first)]; POSTCONDITION(res != nullptr, "Invalid bond requested"); @@ -298,7 +306,9 @@ const Bond *ROMol::getBondWithIdx(unsigned int idx) const { URANGE_CHECK(idx, getNumBonds()); BOND_ITER_PAIR bIter = getEdges(); - for (unsigned int i = 0; i < idx; i++) ++bIter.first; + for (unsigned int i = 0; i < idx; i++) { + ++bIter.first; + } const Bond *res = d_graph[*(bIter.first)]; POSTCONDITION(res != nullptr, "Invalid bond requested"); @@ -355,10 +365,11 @@ unsigned int ROMol::addAtom(Atom *atom_pin, bool updateLabel, bool takeOwnership) { PRECONDITION(atom_pin, "null atom passed in"); Atom *atom_p; - if (!takeOwnership) + if (!takeOwnership) { atom_p = atom_pin->copy(); - else + } else { atom_p = atom_pin; + } atom_p->setOwningMol(this); MolGraph::vertex_descriptor which = boost::add_vertex(d_graph); @@ -386,10 +397,11 @@ unsigned int ROMol::addBond(Bond *bond_pin, bool takeOwnership) { "bond already exists"); Bond *bond_p; - if (!takeOwnership) + if (!takeOwnership) { bond_p = bond_pin->copy(); - else + } else { bond_p = bond_pin; + } bond_p->setOwningMol(this); bool ok; @@ -509,7 +521,9 @@ ROMol::ConstBondIterator ROMol::endBonds() const { void ROMol::clearComputedProps(bool includeRings) const { // the SSSR information: - if (includeRings) this->dp_ringInfo->reset(); + if (includeRings) { + this->dp_ringInfo->reset(); + } RDProps::clearComputedProps(); @@ -554,7 +568,7 @@ const Conformer &ROMol::getConformer(int id) const { if (id < 0) { return *(d_confs.front()); } - unsigned int cid = (unsigned int)id; + auto cid = (unsigned int)id; for (auto ci = this->beginConformers(); ci != this->endConformers(); ++ci) { if ((*ci)->getId() == cid) { return *(*ci); @@ -575,7 +589,7 @@ Conformer &ROMol::getConformer(int id) { if (id < 0) { return *(d_confs.front()); } - unsigned int cid = (unsigned int)id; + auto cid = (unsigned int)id; for (auto ci = this->beginConformers(); ci != this->endConformers(); ++ci) { if ((*ci)->getId() == cid) { return *(*ci); diff --git a/Code/GraphMol/RWMol.cpp b/Code/GraphMol/RWMol.cpp index 7e7458fa8..078c9e2b2 100644 --- a/Code/GraphMol/RWMol.cpp +++ b/Code/GraphMol/RWMol.cpp @@ -88,8 +88,9 @@ void RWMol::insertMol(const ROMol &other) { auto *nconf = new Conformer(getNumAtoms()); nconf->set3D((*cfi)->is3D()); nconf->setId((*cfi)->getId()); - for (unsigned int i = 0; i < newAtomIds.size(); ++i) + for (unsigned int i = 0; i < newAtomIds.size(); ++i) { nconf->setAtomPos(newAtomIds[i], (*cfi)->getAtomPos(i)); + } addConformer(nconf, false); } } else if (getNumConformers()) { @@ -99,15 +100,17 @@ void RWMol::insertMol(const ROMol &other) { for (cfi = beginConformers(), ocfi = other.beginConformers(); cfi != endConformers(); ++cfi, ++ocfi) { (*cfi)->resize(getNumAtoms()); - for (unsigned int i = 0; i < newAtomIds.size(); ++i) + for (unsigned int i = 0; i < newAtomIds.size(); ++i) { (*cfi)->setAtomPos(newAtomIds[i], (*ocfi)->getAtomPos(i)); + } } } else { for (auto cfi = this->beginConformers(); cfi != this->endConformers(); ++cfi) { (*cfi)->resize(getNumAtoms()); - for (unsigned int newAtomId : newAtomIds) + for (unsigned int newAtomId : newAtomIds) { (*cfi)->setAtomPos(newAtomId, RDGeom::Point3D(0.0, 0.0, 0.0)); + } } } } @@ -160,7 +163,9 @@ void RWMol::replaceBond(unsigned int idx, Bond *bond_pin, bool preserveProps) { PRECONDITION(bond_pin, "bad bond passed to replaceBond"); URANGE_CHECK(idx, getNumBonds()); BOND_ITER_PAIR bIter = getEdges(); - for (unsigned int i = 0; i < idx; i++) ++bIter.first; + for (unsigned int i = 0; i < idx; i++) { + ++bIter.first; + } Bond *obond = d_graph[*(bIter.first)]; Bond *bond_p = bond_pin->copy(); bond_p->setOwningMol(this); @@ -181,10 +186,11 @@ void RWMol::replaceBond(unsigned int idx, Bond *bond_pin, bool preserveProps) { }; Atom *RWMol::getActiveAtom() { - if (hasAtomBookmark(ci_RIGHTMOST_ATOM)) + if (hasAtomBookmark(ci_RIGHTMOST_ATOM)) { return getAtomWithBookmark(ci_RIGHTMOST_ATOM); - else + } else { return getLastAtom(); + } }; void RWMol::setActiveAtom(Atom *at) { @@ -257,9 +263,13 @@ void RWMol::removeAtom(Atom *atom) { while (beg != end) { Bond *bond = d_graph[*beg++]; unsigned int tmpIdx = bond->getBeginAtomIdx(); - if (tmpIdx > idx) bond->setBeginAtomIdx(tmpIdx - 1); + if (tmpIdx > idx) { + bond->setBeginAtomIdx(tmpIdx - 1); + } tmpIdx = bond->getEndAtomIdx(); - if (tmpIdx > idx) bond->setEndAtomIdx(tmpIdx - 1); + if (tmpIdx > idx) { + bond->setEndAtomIdx(tmpIdx - 1); + } bond->setIdx(nBonds++); for (auto bsi = bond->getStereoAtoms().begin(); bsi != bond->getStereoAtoms().end(); ++bsi) { @@ -346,7 +356,9 @@ void RWMol::removeBond(unsigned int aid1, unsigned int aid2) { URANGE_CHECK(aid1, getNumAtoms()); URANGE_CHECK(aid2, getNumAtoms()); Bond *bnd = getBondBetweenAtoms(aid1, aid2); - if (!bnd) return; + if (!bnd) { + return; + } unsigned int idx = bnd->getIdx(); // remove any bookmarks which point to this bond: @@ -369,25 +381,35 @@ void RWMol::removeBond(unsigned int aid1, unsigned int aid2) { ADJ_ITER a1, a2; boost::tie(a1, a2) = boost::adjacent_vertices(aid1, d_graph); while (a1 != a2) { - unsigned int oIdx = rdcast(*a1); + auto oIdx = rdcast(*a1); ++a1; - if (oIdx == aid2) continue; + if (oIdx == aid2) { + continue; + } Bond *obnd = getBondBetweenAtoms(aid1, oIdx); - if (!obnd) continue; + if (!obnd) { + continue; + } if (std::find(obnd->getStereoAtoms().begin(), obnd->getStereoAtoms().end(), - aid2) != obnd->getStereoAtoms().end()) + aid2) != obnd->getStereoAtoms().end()) { obnd->getStereoAtoms().clear(); + } } boost::tie(a1, a2) = boost::adjacent_vertices(aid2, d_graph); while (a1 != a2) { - unsigned int oIdx = rdcast(*a1); + auto oIdx = rdcast(*a1); ++a1; - if (oIdx == aid1) continue; + if (oIdx == aid1) { + continue; + } Bond *obnd = getBondBetweenAtoms(aid2, oIdx); - if (!obnd) continue; + if (!obnd) { + continue; + } if (std::find(obnd->getStereoAtoms().begin(), obnd->getStereoAtoms().end(), - aid1) != obnd->getStereoAtoms().end()) + aid1) != obnd->getStereoAtoms().end()) { obnd->getStereoAtoms().clear(); + } } // reset our ring info structure, because it is pretty likely diff --git a/Code/GraphMol/ReducedGraphs/ReducedGraphs.cpp b/Code/GraphMol/ReducedGraphs/ReducedGraphs.cpp index 0ab2e24e9..d3c66d4a8 100644 --- a/Code/GraphMol/ReducedGraphs/ReducedGraphs.cpp +++ b/Code/GraphMol/ReducedGraphs/ReducedGraphs.cpp @@ -131,7 +131,9 @@ RDNumeric::DoubleVector *generateErGFingerprintForReducedGraph( PRECONDITION(maxPath > minPath, "maxPath<=minPath"); // FIX: this isn't doing the special handling for flip/flop bits unsigned int nTypes = nFeatures; - if (atomTypes) nTypes = atomTypes->size(); + if (atomTypes) { + nTypes = atomTypes->size(); + } nTypes += 1; // need the extra one for aromatic features unsigned int nBins = maxPath - minPath; @@ -153,7 +155,9 @@ RDNumeric::DoubleVector *generateErGFingerprintForReducedGraph( // now loop and set the bits between features for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) { - if (tvs[i].empty()) continue; + if (tvs[i].empty()) { + continue; + } #ifdef VERBOSE_FINGERPRINTING std::cerr << " atom: " << i << " "; std::copy(tvs[i].begin(), tvs[i].end(), @@ -161,9 +165,13 @@ RDNumeric::DoubleVector *generateErGFingerprintForReducedGraph( std::cerr << std::endl; #endif for (unsigned int j = i + 1; j < mol.getNumAtoms(); ++j) { - if (tvs[j].empty()) continue; + if (tvs[j].empty()) { + continue; + } int dist = int(dm[i * mol.getNumAtoms() + j]); - if (dist < rdcast(minPath) || dist > rdcast(maxPath)) continue; + if (dist < rdcast(minPath) || dist > rdcast(maxPath)) { + continue; + } BOOST_FOREACH (int ti, tvs[i]) { BOOST_FOREACH (int tj, tvs[j]) { int ijMin = std::min(ti, tj); @@ -177,10 +185,12 @@ RDNumeric::DoubleVector *generateErGFingerprintForReducedGraph( block += ijMax; unsigned int bin = block * nBins + (dist - minPath); (*res)[bin] += 1; - if (dist > rdcast(minPath) && fuzzIncrement > 0) + if (dist > rdcast(minPath) && fuzzIncrement > 0) { (*res)[bin - 1] += fuzzIncrement; - if (dist < rdcast(maxPath) && fuzzIncrement > 0) + } + if (dist < rdcast(maxPath) && fuzzIncrement > 0) { (*res)[bin + 1] += fuzzIncrement; + } } } } @@ -206,7 +216,9 @@ ROMol *generateMolExtendedReducedGraph( std::list tv; tv.clear(); for (unsigned int i = 0; i < atomTypes->size(); ++i) { - if ((*atomTypes)[i][(*atIt)->getIdx()]) tv.push_back(i); + if ((*atomTypes)[i][(*atIt)->getIdx()]) { + tv.push_back(i); + } } (*atIt)->setProp("_ErGAtomTypes", tv); } @@ -225,10 +237,11 @@ ROMol *generateMolExtendedReducedGraph( } } std::list tv; - if (nAromatic >= 2 || nSP2 >= rdcast(ring.size() / 2)) + if (nAromatic >= 2 || nSP2 >= rdcast(ring.size() / 2)) { tv.push_back(aromaticFlag); - else + } else { tv.push_back(aliphaticFlag); + } res->getAtomWithIdx(nIdx)->setProp("_ErGAtomTypes", tv); } } @@ -247,7 +260,9 @@ ROMol *generateMolExtendedReducedGraph( // FIX: still need to do the "highly fused rings" simplification for things // like adamantane - if (latomTypes) delete latomTypes; + if (latomTypes) { + delete latomTypes; + } return res; } } // end of namespace ReducedGraphs diff --git a/Code/GraphMol/ReducedGraphs/Wrap/rdReducedGraphs.cpp b/Code/GraphMol/ReducedGraphs/Wrap/rdReducedGraphs.cpp index dd2de7d20..52498a9d7 100644 --- a/Code/GraphMol/ReducedGraphs/Wrap/rdReducedGraphs.cpp +++ b/Code/GraphMol/ReducedGraphs/Wrap/rdReducedGraphs.cpp @@ -47,7 +47,7 @@ PyObject *GenerateErGFingerprintForReducedGraphHelper(const RDKit::ROMol &mol, RDKit::ReducedGraphs::generateErGFingerprintForReducedGraph( mol, nullptr, fuzzIncrement, minPath, maxPath); npy_intp dim = dv->size(); - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(1, &dim, NPY_DOUBLE); + auto *res = (PyArrayObject *)PyArray_SimpleNew(1, &dim, NPY_DOUBLE); memcpy(static_cast(PyArray_DATA(res)), static_cast(dv->getData()), dv->size() * sizeof(double)); delete dv; @@ -63,7 +63,7 @@ PyObject *GetErGFingerprintHelper(const RDKit::ROMol &mol, RDNumeric::DoubleVector *dv = RDKit::ReducedGraphs::getErGFingerprint( mol, nullptr, fuzzIncrement, minPath, maxPath); npy_intp dim = dv->size(); - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(1, &dim, NPY_DOUBLE); + auto *res = (PyArrayObject *)PyArray_SimpleNew(1, &dim, NPY_DOUBLE); memcpy(static_cast(PyArray_DATA(res)), static_cast(dv->getData()), dv->size() * sizeof(double)); delete dv; diff --git a/Code/GraphMol/Resonance.cpp b/Code/GraphMol/Resonance.cpp index 2f0391b05..b6f1f77b6 100644 --- a/Code/GraphMol/Resonance.cpp +++ b/Code/GraphMol/Resonance.cpp @@ -320,7 +320,9 @@ bool AtomElectrons::isNbrCharged(unsigned int bo, unsigned int oeConstraint) { for (; !res && (nbrIdx != endNbrs); ++nbrIdx) { const Bond *bondNbr = mol[*nbrIdx]; unsigned int biNbr = bondNbr->getIdx(); - if (d_parent->parent()->getBondConjGrpIdx(biNbr) != conjGrpIdx()) continue; + if (d_parent->parent()->getBondConjGrpIdx(biNbr) != conjGrpIdx()) { + continue; + } BondElectrons *beNbr = d_parent->getBondElectronsWithIdx(biNbr); const Atom *atomNbr = bondNbr->getOtherAtom(d_atom); unsigned int aiNbr = atomNbr->getIdx(); @@ -338,7 +340,9 @@ bool AtomElectrons::isNbrCharged(unsigned int bo, unsigned int oeConstraint) { // bit is true if the atom needs be charged std::uint8_t AtomElectrons::canAddBondWithOrder(unsigned int bo) { std::uint8_t canAdd = !isDefinitive(); - if (canAdd) canAdd = (d_tv <= (5 - bo)); + if (canAdd) { + canAdd = (d_tv <= (5 - bo)); + } // if canAdd is true, loop over neighboring conjugated bonds // and check their definitive flag; if all neighbors are // definitive, we need an additional check on total valence @@ -347,9 +351,9 @@ std::uint8_t AtomElectrons::canAddBondWithOrder(unsigned int bo) { // carbon, not more than 1 on atoms left of N unsigned int rightOfC = ((oe() > 4) ? 1 : 0); unsigned int fcInc = 0; - if (rightOfC) + if (rightOfC) { fcInc = (!isNbrCharged(bo, 4) ? 1 : 0); - else { + } else { // atoms left of N can be charged only if: // - the neighbor is uncharged and either the conjugate // group does not bear a non-zero total formal charge @@ -366,7 +370,9 @@ std::uint8_t AtomElectrons::canAddBondWithOrder(unsigned int bo) { } unsigned int e = oe() + d_tv - 1 + bo; canAdd = ((e + fcInc + rightOfC) >= 8); - if (canAdd && (e < 8)) canAdd |= (1 << NEED_CHARGE_BIT); + if (canAdd && (e < 8)) { + canAdd |= (1 << NEED_CHARGE_BIT); + } } return canAdd; } @@ -381,10 +387,13 @@ void AtomElectrons::allConjBondsDefinitiveBut(unsigned int bi) { for (; allDefinitive && (nbrIdx != endNbrs); ++nbrIdx) { unsigned int nbi = mol[*nbrIdx]->getIdx(); if ((nbi != bi) && - (d_parent->parent()->getBondConjGrpIdx(nbi) == conjGrpIdx())) + (d_parent->parent()->getBondConjGrpIdx(nbi) == conjGrpIdx())) { allDefinitive = d_parent->getBondElectronsWithIdx(nbi)->isDefinitive(); + } + } + if (allDefinitive) { + setLastBond(); } - if (allDefinitive) setLastBond(); } // called after all bonds to the atom have been marked as definitive @@ -400,7 +409,9 @@ void AtomElectrons::finalizeAtom() { if (nb) { int fc = nb / 2; if (d_parent->allowedChgLeftOfN()) { - if (d_parent->allowedChgLeftOfN() < 0) fc = -fc; + if (d_parent->allowedChgLeftOfN() < 0) { + fc = -fc; + } d_parent->decrAllowedChgLeftOfN(fc); } } @@ -480,12 +491,15 @@ ConjElectrons::ConjElectrons(ResonanceMolSupplier *parent, unsigned int nb = mol.getNumBonds(); unsigned int na = mol.getNumAtoms(); for (unsigned int ai = 0; ai < na; ++ai) { - if (d_parent->getAtomConjGrpIdx(ai) != -1) + if (d_parent->getAtomConjGrpIdx(ai) != -1) { d_totalFormalCharge += mol.getAtomWithIdx(ai)->getFormalCharge(); + } } d_allowedChgLeftOfN = d_totalFormalCharge; for (unsigned int bi = 0; bi < nb; ++bi) { - if (d_parent->getBondConjGrpIdx(bi) != static_cast(groupIdx)) continue; + if (d_parent->getBondConjGrpIdx(bi) != static_cast(groupIdx)) { + continue; + } const Bond *bond = mol.getBondWithIdx(bi); // store the pointers to BondElectrons objects in a map d_conjBondMap[bi] = new BondElectrons(this, bond); @@ -493,8 +507,9 @@ ConjElectrons::ConjElectrons(ResonanceMolSupplier *parent, const Atom *atom[2] = {bond->getBeginAtom(), bond->getEndAtom()}; for (auto &i : atom) { unsigned int ai = i->getIdx(); - if (d_conjAtomMap.find(ai) == d_conjAtomMap.end()) + if (d_conjAtomMap.find(ai) == d_conjAtomMap.end()) { d_conjAtomMap[ai] = new AtomElectrons(this, i); + } } } // count total number of valence electrons in conjugated group @@ -513,20 +528,24 @@ ConjElectrons::ConjElectrons(const ConjElectrons &ce) d_ceMetrics(ce.d_ceMetrics), d_beginAIStack(ce.d_beginAIStack), d_parent(ce.d_parent) { - for (const auto &it : ce.d_conjAtomMap) + for (const auto &it : ce.d_conjAtomMap) { d_conjAtomMap[it.first] = new AtomElectrons(this, *(it.second)); - for (const auto &it : ce.d_conjBondMap) + } + for (const auto &it : ce.d_conjBondMap) { d_conjBondMap[it.first] = new BondElectrons(this, *(it.second)); + } } // object destructor ConjElectrons::~ConjElectrons() { for (ConjAtomMap::const_iterator it = d_conjAtomMap.begin(); - it != d_conjAtomMap.end(); ++it) + it != d_conjAtomMap.end(); ++it) { delete it->second; + } for (ConjBondMap::const_iterator it = d_conjBondMap.begin(); - it != d_conjBondMap.end(); ++it) + it != d_conjBondMap.end(); ++it) { delete it->second; + } } // store fingerprints for this ConjElectrons object in ceMap @@ -536,9 +555,12 @@ bool ConjElectrons::storeFP(CEMap &ceMap, unsigned int flags) { std::uint8_t byte; ConjFP fp; unsigned int fpSize = 0; - if (flags & FP_ATOMS) fpSize += rdcast(d_conjAtomMap.size()); - if (flags & FP_BONDS) + if (flags & FP_ATOMS) { + fpSize += rdcast(d_conjAtomMap.size()); + } + if (flags & FP_BONDS) { fpSize += rdcast((d_conjBondMap.size() - 1) / 4 + 1); + } fp.reserve(fpSize); if (flags & FP_ATOMS) { // for each atom, we push a byte to the FP vector whose @@ -566,7 +588,9 @@ bool ConjElectrons::storeFP(CEMap &ceMap, unsigned int flags) { byte |= (static_cast(it->second->order()) << (i * 2)); ++i; } - if (i) fp.push_back(byte); + if (i) { + fp.push_back(byte); + } } // convert the FP vector to a hash std::size_t hash = boost::hash_range(fp.begin(), fp.end()); @@ -603,11 +627,13 @@ void ConjElectrons::assignBondsFormalChargesToMol(ROMol &mol) { // respective atoms and bonds void ConjElectrons::initCeFromMol() { for (ConjAtomMap::const_iterator it = d_conjAtomMap.begin(); - it != d_conjAtomMap.end(); ++it) + it != d_conjAtomMap.end(); ++it) { it->second->initTvNbFcFromAtom(); + } for (ConjBondMap::const_iterator it = d_conjBondMap.begin(); - it != d_conjBondMap.end(); ++it) + it != d_conjBondMap.end(); ++it) { it->second->initOrderFromBond(); + } d_currElectrons = 0; } @@ -625,8 +651,9 @@ void ConjElectrons::assignNonBonded() { // assign formal charges to atoms void ConjElectrons::assignFormalCharge() { for (ConjAtomMap::const_iterator it = d_conjAtomMap.begin(); - it != d_conjAtomMap.end(); ++it) + it != d_conjAtomMap.end(); ++it) { it->second->assignFormalCharge(); + } } // return true if formal charges for this ConjElectrons @@ -643,21 +670,27 @@ bool ConjElectrons::checkCharges() { // formal charges should be between -2 and +1 areAcceptable = ((ae->fc() < 2) && (ae->fc() > -3)); if (areAcceptable) { - if (ae->fc() > 0) + if (ae->fc() > 0) { d_flags |= HAVE_CATION; - else if (ae->fc() < 0) + } else if (ae->fc() < 0) { d_flags |= HAVE_ANION; + } if (ae->oe() > 4) { - if (!ae->hasOctet()) haveIncompleteOctetRightOfC = true; + if (!ae->hasOctet()) { + haveIncompleteOctetRightOfC = true; + } if ((ae->fc() > 0) && (ae->oe() > 5)) { d_flags |= HAVE_CATION_RIGHT_OF_N; - if (!ae->hasOctet()) havePosRightOfNNoOctet = true; + if (!ae->hasOctet()) { + havePosRightOfNNoOctet = true; + } } } else { - if (ae->fc() < 0) + if (ae->fc() < 0) { haveNegLeftOfN = true; - else if (ae->fc() > 0) + } else if (ae->fc() > 0) { havePosLeftOfN = true; + } } // no carbanions should coexist with incomplete octets areAcceptable = !(haveIncompleteOctetRightOfC && haveNegLeftOfN); @@ -668,15 +701,17 @@ bool ConjElectrons::checkCharges() { // if the UNCONSTRAINED_CATIONS flag is not set, positively charged // atoms left and right of N with an incomplete octet are acceptable // only if the conjugated group has a positive total formal charge - if (havePosLeftOfN || havePosRightOfNNoOctet) + if (havePosLeftOfN || havePosRightOfNNoOctet) { areAcceptable = (d_totalFormalCharge > 0); + } } if (areAcceptable && haveNegLeftOfN && - !(d_parent->flags() & ResonanceMolSupplier::UNCONSTRAINED_ANIONS)) + !(d_parent->flags() & ResonanceMolSupplier::UNCONSTRAINED_ANIONS)) { // if the UNCONSTRAINED_ANIONS flag is not set, negatively charged // atoms left of N are acceptable only if the conjugated group has // a negative total formal charge areAcceptable = (d_totalFormalCharge < 0); + } for (ConjBondMap::const_iterator it = d_conjBondMap.begin(); areAcceptable && (it != d_conjBondMap.end()); ++it) { BondElectrons *be = it->second; @@ -691,10 +726,11 @@ bool ConjElectrons::checkCharges() { ((be->order() == 1) || ((be->order() > 1) && (ae[i]->fc() < 1))); } } - if (areAcceptable) + if (areAcceptable) { // charged neighboring atoms left of N are not acceptable areAcceptable = !((ae[0]->oe() < 5) && ae[0]->fc() && (ae[1]->oe() < 5) && ae[1]->fc()); + } } return areAcceptable; } @@ -705,8 +741,12 @@ bool ConjElectrons::assignFormalChargesAndStore(CEMap &ceMap, unsigned int fpFlags) { assignFormalCharge(); bool ok = checkCharges(); - if (ok) ok = storeFP(ceMap, fpFlags); - if (ok) computeMetrics(); + if (ok) { + ok = storeFP(ceMap, fpFlags); + } + if (ok) { + computeMetrics(); + } return ok; } @@ -754,7 +794,9 @@ void ConjElectrons::enumerateNonBonded(CEMap &ceMap) { ConjElectrons *ceCopy = ((numComb > 1) ? new ConjElectrons(*ce) : nullptr); // enumerate all permutations for (unsigned int c = 0; c < numComb; ++c) { - if (c) ce = new ConjElectrons(*ceCopy); + if (c) { + ce = new ConjElectrons(*ceCopy); + } unsigned int vc = v; for (unsigned int i : aiVec) { AtomElectrons *ae = ce->getAtomElectronsWithIdx(i); @@ -762,13 +804,17 @@ void ConjElectrons::enumerateNonBonded(CEMap &ceMap) { // if this atom was chosen to be octet-unsatisfied in // this permutation, give it one electron pair less than // its need (which most likely means no electrons at all) - if (vc & 1) e -= 2; + if (vc & 1) { + e -= 2; + } ce->decrCurrElectrons(e); ae->assignNonBonded(e); vc >>= 1; } // delete this candidate if it fails the formal charge check - if (!ce->assignFormalChargesAndStore(ceMap, fpFlags)) delete ce; + if (!ce->assignFormalChargesAndStore(ceMap, fpFlags)) { + delete ce; + } // get the next binary code ResonanceUtils::updateV(v); } @@ -779,12 +825,15 @@ void ConjElectrons::enumerateNonBonded(CEMap &ceMap) { // is univocal ce->assignNonBonded(); // delete this candidate if it fails the formal charge check - if (!ce->assignFormalChargesAndStore(ceMap, fpFlags)) delete ce; - } else + if (!ce->assignFormalChargesAndStore(ceMap, fpFlags)) { + delete ce; + } + } else { // if the electrons required to satisfy all octets are less // than those currently available, we must have failed the bond // assignment, so the candidate must be deleted delete ce; + } } void ConjElectrons::computeMetrics() { @@ -817,16 +866,21 @@ void ConjElectrons::computeMetrics() { void ConjElectrons::computeDistFormalCharges() { for (ConjAtomMap::const_iterator it1 = d_conjAtomMap.begin(); it1 != d_conjAtomMap.end(); ++it1) { - if (!it1->second->fc()) continue; + if (!it1->second->fc()) { + continue; + } for (auto it2 = it1; it2 != d_conjAtomMap.end(); ++it2) { - if ((it1 == it2) || !it2->second->fc()) continue; + if ((it1 == it2) || !it2->second->fc()) { + continue; + } unsigned int dist = rdcast( MolOps::getShortestPath(d_parent->mol(), it1->first, it2->first) .size()); - if ((it1->second->fc() * it2->second->fc()) > 0) + if ((it1->second->fc() * it2->second->fc()) > 0) { d_ceMetrics.d_fcSameSignDist += dist; - else + } else { d_ceMetrics.d_fcOppSignDist += dist; + } } } } @@ -835,7 +889,9 @@ void ConjElectrons::computeDistFormalCharges() { void ConjElectrons::computeSumFormalChargeIdxs() { for (ConjAtomMap::const_iterator it = d_conjAtomMap.begin(); it != d_conjAtomMap.end(); ++it) { - if (it->second->fc()) d_ceMetrics.d_sumFormalChargeIdxs += it->first; + if (it->second->fc()) { + d_ceMetrics.d_sumFormalChargeIdxs += it->first; + } } } @@ -843,7 +899,9 @@ void ConjElectrons::computeSumFormalChargeIdxs() { void ConjElectrons::computeSumMultipleBondIdxs() { for (ConjBondMap::const_iterator it = d_conjBondMap.begin(); it != d_conjBondMap.end(); ++it) { - if (it->second->order() > 1) d_ceMetrics.d_sumMultipleBondIdxs += it->first; + if (it->second->order() > 1) { + d_ceMetrics.d_sumMultipleBondIdxs += it->first; + } } } @@ -911,8 +969,9 @@ bool CEVect2::resonanceStructureCompare(const ConjElectrons *a, CEVect2::CEVect2(CEMap &ceMap) { d_ceVect.reserve(ceMap.size()); - for (CEMap::const_iterator it = ceMap.begin(); it != ceMap.end(); ++it) + for (CEMap::const_iterator it = ceMap.begin(); it != ceMap.end(); ++it) { d_ceVect.push_back(it->second); + } std::sort(d_ceVect.begin(), d_ceVect.end(), resonanceStructureCompare); bool first = true; CEMetrics metricsPrev; @@ -922,8 +981,9 @@ CEVect2::CEVect2(CEMap &ceMap) { first = false; metricsPrev = (*it)->metrics(); d_degVect.push_back(1); - } else + } else { ++d_degVect.back(); + } } } @@ -940,7 +1000,9 @@ ConjElectrons *CEVect2::getCE(unsigned int depth, unsigned int width) { throw std::runtime_error(ss.str()); } unsigned int i = 0; - for (unsigned int d = 0; d < depth; ++d) i += d_degVect[d]; + for (unsigned int d = 0; d < depth; ++d) { + i += d_degVect[d]; + } i += width; return d_ceVect[i]; } @@ -966,7 +1028,9 @@ unsigned int CEVect2::ceCountUntilDepth(unsigned int depth) { throw std::runtime_error(ss.str()); } unsigned int i = 0; - for (unsigned int d = 0; d <= depth; ++d) i += d_degVect[d]; + for (unsigned int d = 0; d <= depth; ++d) { + i += d_degVect[d]; + } return i; } @@ -999,8 +1063,9 @@ AtomElectrons *ConjElectrons::getAtomElectronsWithIdx(unsigned int ai) { unsigned int ConjElectrons::countTotalElectrons() { // count total number of valence electrons in conjugated group for (ConjBondMap::const_iterator it = d_conjBondMap.begin(); - it != d_conjBondMap.end(); ++it) + it != d_conjBondMap.end(); ++it) { d_totalElectrons += (2 * it->second->orderFromBond()); + } for (ConjAtomMap::const_iterator it = d_conjAtomMap.begin(); it != d_conjAtomMap.end(); ++it) { const Atom *a = it->second->atom(); @@ -1036,8 +1101,9 @@ void ResonanceMolSupplier::trimCeVect2() { for (unsigned int d = s[conjGrpIdx]; d < d_ceVect3[conjGrpIdx]->depth(); ++d) { for (unsigned int w = 0; w < d_ceVect3[conjGrpIdx]->ceCountAtDepth(d); - ++w) + ++w) { delete (d_ceVect3[conjGrpIdx]->getCE(d, w)); + } } d_ceVect3[conjGrpIdx]->resize(s[conjGrpIdx]); } @@ -1075,21 +1141,33 @@ bool ResonanceMolSupplier::cePermCompare(const CEPerm *a, const CEPerm *b) { aSum += a->v[i]; bSum += b->v[i]; } - if (aSum != bSum) return (aSum < bSum); + if (aSum != bSum) { + return (aSum < bSum); + } unsigned int aMax = 0; unsigned int bMax = 0; for (unsigned int i = 0; i < a->v.size(); i += 2) { - if (!i || (a->v[i] > aMax)) aMax = a->v[i]; - if (!i || (b->v[i] > bMax)) bMax = b->v[i]; + if (!i || (a->v[i] > aMax)) { + aMax = a->v[i]; + } + if (!i || (b->v[i] > bMax)) { + bMax = b->v[i]; + } + } + if (aMax != bMax) { + return (aMax < bMax); } - if (aMax != bMax) return (aMax < bMax); for (unsigned int i = 0; i < a->v.size(); i += 2) { - if (a->v[i] != b->v[i]) return (a->v[i] < b->v[i]); + if (a->v[i] != b->v[i]) { + return (a->v[i] < b->v[i]); + } } // if the other criteria didn't discriminate, // sort based on degenerate resonance structures for (unsigned int i = 1; i < a->v.size(); i += 2) { - if (a->v[i] != b->v[i]) return (a->v[i] < b->v[i]); + if (a->v[i] != b->v[i]) { + return (a->v[i] < b->v[i]); + } } // we'll never get here, this it is just to silence a warning return false; @@ -1134,14 +1212,19 @@ ResonanceMolSupplier::ResonanceMolSupplier(ROMol &mol, unsigned int flags, ResonanceMolSupplier::~ResonanceMolSupplier() { for (CEVect3::const_iterator ceVect3It = d_ceVect3.begin(); ceVect3It != d_ceVect3.end(); ++ceVect3It) { - if (!(*ceVect3It)) continue; + if (!(*ceVect3It)) { + continue; + } for (unsigned int d = 0; d < (*ceVect3It)->depth(); ++d) { - for (unsigned int w = 0; w < (*ceVect3It)->ceCountAtDepth(d); ++w) + for (unsigned int w = 0; w < (*ceVect3It)->ceCountAtDepth(d); ++w) { delete ((*ceVect3It)->getCE(d, w)); + } } delete (*ceVect3It); } - if (d_mol) delete d_mol; + if (d_mol) { + delete d_mol; + } } void ResonanceMolSupplier::setNumThreads(int numThreads) { @@ -1149,11 +1232,14 @@ void ResonanceMolSupplier::setNumThreads(int numThreads) { } void ResonanceMolSupplier::enumerate() { - if (d_isEnumerated) return; + if (d_isEnumerated) { + return; + } resizeCeVect(); - if (d_numThreads == 1) mainLoop(0, 1); + if (d_numThreads == 1) { + mainLoop(0, 1); #ifdef RDK_THREADSAFE_SSS - else { + } else { std::vector> tg; auto functor = [this](unsigned int ti, unsigned int d_numThreads) -> void { mainLoop(ti, d_numThreads); @@ -1175,7 +1261,9 @@ void ResonanceMolSupplier::enumerate() { void ResonanceMolSupplier::mainLoop(unsigned int ti, unsigned int nt) { for (unsigned int conjGrpIdx = 0; conjGrpIdx < d_nConjGrp; ++conjGrpIdx) { - if ((conjGrpIdx % nt) != ti) continue; + if ((conjGrpIdx % nt) != ti) { + continue; + } CEMap ceMap; buildCEMap(ceMap, conjGrpIdx); storeCEMap(ceMap, conjGrpIdx); @@ -1189,7 +1277,9 @@ void ResonanceMolSupplier::mainLoop(unsigned int ti, unsigned int nt) { // index -1 void ResonanceMolSupplier::assignConjGrpIdx() { unsigned int nb = d_mol->getNumBonds(); - if (!nb) return; + if (!nb) { + return; + } std::stack bondIndexStack; d_bondConjGrpIdx.resize(nb, -1); unsigned int na = d_mol->getNumAtoms(); @@ -1202,7 +1292,9 @@ void ResonanceMolSupplier::assignConjGrpIdx() { break; } } - if (bondIndexStack.empty()) break; + if (bondIndexStack.empty()) { + break; + } while (!bondIndexStack.empty()) { unsigned int i = bondIndexStack.top(); bondIndexStack.pop(); @@ -1237,7 +1329,9 @@ void ResonanceMolSupplier::assignConjGrpIdx() { // objects are collected in ceMap void ResonanceMolSupplier::enumerateNbArrangements(CEMap &ceMap, CEMap &ceMapTmp) { - for (auto &it : ceMapTmp) it.second->enumerateNonBonded(ceMap); + for (auto &it : ceMapTmp) { + it.second->enumerateNonBonded(ceMap); + } } void ResonanceMolSupplier::pruneStructures(CEMap &ceMap) { @@ -1253,10 +1347,15 @@ void ResonanceMolSupplier::pruneStructures(CEMap &ceMap) { } for (CEMap::const_iterator it = ceMap.begin(); (it != ceMap.end()); ++it) { if (!(d_flags & ALLOW_INCOMPLETE_OCTETS) && - (it->second->nbMissing() > minNbMissing)) + (it->second->nbMissing() > minNbMissing)) { continue; - if (!it->second->hasCationRightOfN()) haveNoCationsRightOfN = true; - if (!it->second->hasChargeSeparation()) haveNoChargeSeparation = true; + } + if (!it->second->hasCationRightOfN()) { + haveNoCationsRightOfN = true; + } + if (!it->second->hasChargeSeparation()) { + haveNoChargeSeparation = true; + } } for (CEMap::iterator it = ceMap.begin(); it != ceMap.end();) { // if the flag ALLOW_INCOMPLETE_OCTETS is not set, ConjElectrons @@ -1273,8 +1372,9 @@ void ResonanceMolSupplier::pruneStructures(CEMap &ceMap) { ++it; delete (toBeDeleted->second); ceMap.erase(toBeDeleted); - } else + } else { ++it; + } } } @@ -1337,10 +1437,14 @@ void ResonanceMolSupplier::buildCEMap(CEMap &ceMap, unsigned int conjGrpIdx) { bool aiFound = false; while (aiBegin < na) { aiFound = (d_atomConjGrpIdx[aiBegin] == static_cast(conjGrpIdx)); - if (aiFound) break; + if (aiFound) { + break; + } ++aiBegin; } - if (!aiFound) continue; + if (!aiFound) { + continue; + } ce->pushToBeginStack(aiBegin); } // loop until the atom index stack is empty @@ -1361,17 +1465,22 @@ void ResonanceMolSupplier::buildCEMap(CEMap &ceMap, unsigned int conjGrpIdx) { // if this neighbor is not part of the conjugated group, // ignore it if (ce->parent()->getAtomConjGrpIdx(aiNbr) != - static_cast(conjGrpIdx)) + static_cast(conjGrpIdx)) { continue; + } AtomElectrons *aeNbr = ce->getAtomElectronsWithIdx(aiNbr); // if we've already dealt with this neighbor before, ignore it - if (aeNbr->isDefinitive()) continue; + if (aeNbr->isDefinitive()) { + continue; + } unsigned int biNbr = d_mol->getBondBetweenAtoms(ai[BEGIN_POS], aiNbr)->getIdx(); BondElectrons *beNbr = ce->getBondElectronsWithIdx(biNbr); // if we have already assigned the bond order to this bond, // ignore it - if (beNbr->isDefinitive()) continue; + if (beNbr->isDefinitive()) { + continue; + } // if this is the first neighbor we find, process it if (!ae[END_POS]) { bi = biNbr; @@ -1381,12 +1490,15 @@ void ResonanceMolSupplier::buildCEMap(CEMap &ceMap, unsigned int conjGrpIdx) { } // otherwise, if there are multiple neighbors, process the first // and store the rest to the atom index stack - else + else { ce->pushToBeginStack(aiNbr); + } } // if no neighbors were found, move on to the next atom index // in the stack - if (!be) continue; + if (!be) { + continue; + } std::uint8_t allowedBondsPerAtom[2]; // loop over the two atoms that need be bonded for (unsigned int i = 0; i < 2; ++i) { @@ -1397,8 +1509,9 @@ void ResonanceMolSupplier::buildCEMap(CEMap &ceMap, unsigned int conjGrpIdx) { // to the stack if (ae[i]->isLastBond()) { ae[i]->setDefinitive(); - } else + } else { ce->pushToBeginStack(ai[i]); + } } // logical AND between allowed bond masks for the two atoms std::uint8_t allowedBonds = @@ -1439,8 +1552,9 @@ void ResonanceMolSupplier::buildCEMap(CEMap &ceMap, unsigned int conjGrpIdx) { // set bond orders and finalize atoms as needed ceToSet->getBondElectronsWithIdx(bi)->setOrder(bo); for (unsigned int j = 0; j < 2; ++j) { - if (ae[j]->isLastBond()) + if (ae[j]->isLastBond()) { ceToSet->getAtomElectronsWithIdx(ai[j])->finalizeAtom(); + } } } } @@ -1454,7 +1568,9 @@ void ResonanceMolSupplier::buildCEMap(CEMap &ceMap, unsigned int conjGrpIdx) { if (ce) { // if this bond arrangement was already stored previously, // discard it - if (!ce->storeFP(ceMapTmp, fpFlagsTmp)) delete ce; + if (!ce->storeFP(ceMapTmp, fpFlagsTmp)) { + delete ce; + } } } // for each bond arrangement in ceMapTmp, enumerate possible diff --git a/Code/GraphMol/RingInfo.cpp b/Code/GraphMol/RingInfo.cpp index 414526f9f..f37e64b4b 100644 --- a/Code/GraphMol/RingInfo.cpp +++ b/Code/GraphMol/RingInfo.cpp @@ -101,13 +101,15 @@ unsigned int RingInfo::addRing(const INT_VECT &atomIndices, PRECONDITION(atomIndices.size() == bondIndices.size(), "length mismatch"); int sz = rdcast(atomIndices.size()); for (auto i : atomIndices) { - if (i >= static_cast(d_atomMembers.size())) + if (i >= static_cast(d_atomMembers.size())) { d_atomMembers.resize((i) + 1); + } d_atomMembers[i].push_back(sz); } for (auto i : bondIndices) { - if (i >= static_cast(d_bondMembers.size())) + if (i >= static_cast(d_bondMembers.size())) { d_bondMembers.resize((i) + 1); + } d_bondMembers[i].push_back(sz); } d_atomRings.push_back(atomIndices); @@ -144,7 +146,9 @@ void RingInfo::initialize() { df_init = true; }; void RingInfo::reset() { - if (!df_init) return; + if (!df_init) { + return; + } df_init = false; d_atomMembers.clear(); d_bondMembers.clear(); diff --git a/Code/GraphMol/SLNParse/SLNAttribs.cpp b/Code/GraphMol/SLNParse/SLNAttribs.cpp index a4174e6a8..3394300bb 100644 --- a/Code/GraphMol/SLNParse/SLNAttribs.cpp +++ b/Code/GraphMol/SLNParse/SLNAttribs.cpp @@ -224,27 +224,39 @@ void parseAtomAttribs(Atom *atom, AttribListType attribs, bool doingQuery) { val = -666; } if (attribName == "rbc") { - if (fTag == "") val = parseIntAttribVal(attribName, attribVal); + if (fTag == "") { + val = parseIntAttribVal(attribName, attribVal); + } query = makeQueryFromOp(attribPtr->op, val, queryAtomRingBondCount, fTag + "AtomRingBondCount"); } else if (attribName == "tbo") { - if (fTag == "") val = parseIntAttribVal(attribName, attribVal); + if (fTag == "") { + val = parseIntAttribVal(attribName, attribVal); + } query = makeQueryFromOp(attribPtr->op, val, queryAtomTotalValence, fTag + "AtomTotalValence"); } else if (attribName == "tac") { - if (fTag == "") val = parseIntAttribVal(attribName, attribVal); + if (fTag == "") { + val = parseIntAttribVal(attribName, attribVal); + } query = makeQueryFromOp(attribPtr->op, val, queryAtomTotalDegree, fTag + "AtomTotalDegree"); } else if (attribName == "hc") { - if (fTag == "") val = parseIntAttribVal(attribName, attribVal); + if (fTag == "") { + val = parseIntAttribVal(attribName, attribVal); + } query = makeQueryFromOp(attribPtr->op, val, queryAtomHCount, fTag + "AtomHCount"); } else if (attribName == "hac") { - if (fTag == "") val = parseIntAttribVal(attribName, attribVal); + if (fTag == "") { + val = parseIntAttribVal(attribName, attribVal); + } query = makeQueryFromOp(attribPtr->op, val, queryAtomNonHydrogenDegree, fTag + "AtomHeavyAtomDegree"); } else if (attribName == "f") { - if (fTag == "") val = parseIntAttribVal(attribName, attribVal); + if (fTag == "") { + val = parseIntAttribVal(attribName, attribVal); + } query = makeQueryFromOp( "=", val, (int (*)(const RDKit::Atom *))(queryAtomAllBondProduct), fTag + "AtomBondEnvironment"); @@ -262,7 +274,9 @@ void parseAtomAttribs(Atom *atom, AttribListType attribs, bool doingQuery) { << "' ignored on non-query atom\n"; delete query; } else { - if (attribPtr->negated) query->setNegation(!query->getNegation()); + if (attribPtr->negated) { + query->setNegation(!query->getNegation()); + } if (!atomQuery) { // first one is easy: atomQuery = query; @@ -338,8 +352,9 @@ void parseFinalAtomAttribs(Atom *atom, bool doingQuery) { // attributes that had "f" in the original SLN. We will recognize // these by the fact that their names start with "_SLN_" if (!doingQuery || !atom->hasQuery() || - !atom->hasProp(common_properties::_Unfinished_SLN_)) + !atom->hasProp(common_properties::_Unfinished_SLN_)) { return; + } atom->clearProp(common_properties::_Unfinished_SLN_); std::list q; q.push_back(atom->getQuery()); @@ -405,7 +420,9 @@ void parseBondAttribs(Bond *bond, AttribListType attribs, bool doingQuery) { bond->setBondType(bondType); } else { QueryBond::QUERYBOND_QUERY *query = makeBondOrderEqualsQuery(bondType); - if (attribPtr->negated) query->setNegation(!query->getNegation()); + if (attribPtr->negated) { + query->setNegation(!query->getNegation()); + } if (seenTypeQuery) { static_cast(bond)->expandQuery(query, how, true); } else { @@ -426,7 +443,9 @@ void parseBondAttribs(Bond *bond, AttribListType attribs, bool doingQuery) { << "' ignored on non-query bond\n"; } else { QueryBond::QUERYBOND_QUERY *query = makeBondIsInRingQuery(); - if (attribPtr->negated) query->setNegation(true); + if (attribPtr->negated) { + query->setNegation(true); + } static_cast(bond)->expandQuery(query, how); } } else { diff --git a/Code/GraphMol/SLNParse/SLNParse.cpp b/Code/GraphMol/SLNParse/SLNParse.cpp index 220f9eb52..b2de2c635 100644 --- a/Code/GraphMol/SLNParse/SLNParse.cpp +++ b/Code/GraphMol/SLNParse/SLNParse.cpp @@ -245,12 +245,11 @@ void SLNParse::CleanupAfterParse(RWMol *mol) { PRECONDITION(mol, "no molecule"); // blow out any partial bonds: RWMol::BOND_BOOKMARK_MAP *marks = mol->getBondBookmarks(); - RWMol::BOND_BOOKMARK_MAP::iterator markI = marks->begin(); + auto markI = marks->begin(); while (markI != marks->end()) { RWMol::BOND_PTR_LIST &bonds = markI->second; - for (RWMol::BOND_PTR_LIST::iterator bondIt = bonds.begin(); - bondIt != bonds.end(); ++bondIt) { - delete *bondIt; + for (auto &bond : bonds) { + delete bond; } ++markI; } diff --git a/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp b/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp index 89593055a..fe718f99a 100644 --- a/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp +++ b/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp @@ -32,11 +32,12 @@ void _copyTransform(const PyArrayObject *transMat, RDGeom::Transform3D &trans) { throw_value_error("The transform has to be square matrix, of size 4x4"); } if (PyArray_DESCR(const_cast(transMat))->type_num != - NPY_DOUBLE) + NPY_DOUBLE) { throw_value_error("Only double arrays allowed for transform object "); + } unsigned int dSize = nrows * nrows; - const double *inData = reinterpret_cast( + const auto *inData = reinterpret_cast( PyArray_DATA(const_cast(transMat))); double *tData = trans.getData(); memcpy(static_cast(tData), static_cast(inData), @@ -49,7 +50,7 @@ python::tuple getConformerDimsAndOffset(const Conformer &conf, RDGeom::Point3D dims, offSet; PyObject *transObj = trans.ptr(); if (PyArray_Check(transObj)) { - PyArrayObject *transMat = reinterpret_cast(transObj); + auto *transMat = reinterpret_cast(transObj); RDGeom::Transform3D ctrans; _copyTransform(transMat, ctrans); MolShapes::computeConfDimsAndOffset(conf, dims, offSet, &ctrans, padding); @@ -67,7 +68,7 @@ python::tuple getConfBox(const Conformer &conf, RDGeom::Point3D lowerCorner, upperCorner; PyObject *transObj = trans.ptr(); if (PyArray_Check(transObj)) { - PyArrayObject *transMat = reinterpret_cast(transObj); + auto *transMat = reinterpret_cast(transObj); RDGeom::Transform3D ctrans; _copyTransform(transMat, ctrans); MolShapes::computeConfBox(conf, lowerCorner, upperCorner, &ctrans, padding); @@ -110,7 +111,7 @@ void EncodeMolShape( PyObject *transObj = trans.ptr(); if (PyArray_Check(transObj)) { - PyArrayObject *transMat = reinterpret_cast(transObj); + auto *transMat = reinterpret_cast(transObj); RDGeom::Transform3D ctrans; _copyTransform(transMat, ctrans); MolShapes::EncodeShape(mol, grid, confId, &ctrans, vdwScale, stepSize, diff --git a/Code/GraphMol/SmilesParse/CXSmilesOps.cpp b/Code/GraphMol/SmilesParse/CXSmilesOps.cpp index d6bcfa033..4353b3455 100644 --- a/Code/GraphMol/SmilesParse/CXSmilesOps.cpp +++ b/Code/GraphMol/SmilesParse/CXSmilesOps.cpp @@ -40,8 +40,12 @@ bool read_int(Iterator &first, Iterator last, unsigned int &res) { template bool read_int_pair(Iterator &first, Iterator last, unsigned int &n1, unsigned int &n2, char sep = '.') { - if (!read_int(first, last, n1)) return false; - if (first >= last || *first != sep) return false; + if (!read_int(first, last, n1)) { + return false; + } + if (first >= last || *first != sep) { + return false; + } ++first; return read_int(first, last, n2); } @@ -62,10 +66,11 @@ std::string read_text_to(Iterator &first, Iterator last, std::string delims) { while (next != last && *next >= '0' && *next <= '9') { ++next; } - if (next == last || *next != ';') + if (next == last || *next != ';') { throw RDKit::SmilesParseException( "failure parsing CXSMILES extensions: quoted block not terminated " "with ';'"); + } if (next > first + 2) { std::string blk = std::string(first + 2, next); res += (char)(boost::lexical_cast(blk)); @@ -76,13 +81,17 @@ std::string read_text_to(Iterator &first, Iterator last, std::string delims) { ++first; } } - if (start != first) res += std::string(start, first); + if (start != first) { + res += std::string(start, first); + } return res; } template bool parse_atom_values(Iterator &first, Iterator last, RDKit::RWMol &mol) { - if (first >= last || *first != ':') return false; + if (first >= last || *first != ':') { + return false; + } ++first; unsigned int atIdx = 0; while (first != last && *first != '$') { @@ -92,24 +101,34 @@ bool parse_atom_values(Iterator &first, Iterator last, RDKit::RWMol &mol) { tkn); } ++atIdx; - if (first != last && *first != '$') ++first; + if (first != last && *first != '$') { + ++first; + } + } + if (first == last || *first != '$') { + return false; } - if (first == last || *first != '$') return false; ++first; return true; } template bool parse_atom_props(Iterator &first, Iterator last, RDKit::RWMol &mol) { - if (first >= last) return false; + if (first >= last) { + return false; + } while (first != last && *first != '|' && *first != ',') { unsigned int atIdx; if (read_int(first, last, atIdx)) { - if (first == last || *first != '.') return false; + if (first == last || *first != '.') { + return false; + } ++first; std::string pname = read_text_to(first, last, "."); if (pname != "") { - if (first == last || *first != '.') return false; + if (first == last || *first != '.') { + return false; + } ++first; std::string pval = read_text_to(first, last, ":|,"); if (pval != "") { @@ -117,16 +136,24 @@ bool parse_atom_props(Iterator &first, Iterator last, RDKit::RWMol &mol) { } } } - if (first != last && *first != '|' && *first != ',') ++first; + if (first != last && *first != '|' && *first != ',') { + ++first; + } + } + if (first != last && *first != '|' && *first != ',') { + return false; + } + if (*first != '|') { + ++first; } - if (first != last && *first != '|' && *first != ',') return false; - if (*first != '|') ++first; return true; } template bool parse_atom_labels(Iterator &first, Iterator last, RDKit::RWMol &mol) { - if (first >= last || *first != '$') return false; + if (first >= last || *first != '$') { + return false; + } ++first; unsigned int atIdx = 0; while (first != last && *first != '$') { @@ -136,16 +163,22 @@ bool parse_atom_labels(Iterator &first, Iterator last, RDKit::RWMol &mol) { tkn); } ++atIdx; - if (first != last && *first != '$') ++first; + if (first != last && *first != '$') { + ++first; + } + } + if (first == last || *first != '$') { + return false; } - if (first == last || *first != '$') return false; ++first; return true; } template bool parse_coords(Iterator &first, Iterator last, RDKit::RWMol &mol) { - if (first >= last || *first != '(') return false; + if (first >= last || *first != '(') { + return false; + } auto *conf = new Conformer(mol.getNumAtoms()); mol.addConformer(conf); @@ -157,28 +190,39 @@ bool parse_coords(Iterator &first, Iterator last, RDKit::RWMol &mol) { if (tkn != "") { std::vector tokens; boost::split(tokens, tkn, boost::is_any_of(std::string(","))); - if (tokens.size() >= 1 && tokens[0].size()) + if (tokens.size() >= 1 && tokens[0].size()) { pt.x = boost::lexical_cast(tokens[0]); - if (tokens.size() >= 2 && tokens[1].size()) + } + if (tokens.size() >= 2 && tokens[1].size()) { pt.y = boost::lexical_cast(tokens[1]); - if (tokens.size() >= 3 && tokens[2].size()) + } + if (tokens.size() >= 3 && tokens[2].size()) { pt.z = boost::lexical_cast(tokens[2]); + } } conf->setAtomPos(atIdx, pt); ++atIdx; - if (first != last && *first != ')') ++first; + if (first != last && *first != ')') { + ++first; + } + } + if (first == last || *first != ')') { + return false; } - if (first == last || *first != ')') return false; ++first; return true; } template bool parse_coordinate_bonds(Iterator &first, Iterator last, RDKit::RWMol &mol) { - if (first >= last || *first != 'C') return false; + if (first >= last || *first != 'C') { + return false; + } ++first; - if (first >= last || *first != ':') return false; + if (first >= last || *first != ':') { + return false; + } ++first; while (first != last && *first >= '0' && *first <= '9') { unsigned int aidx; @@ -199,7 +243,9 @@ bool parse_coordinate_bonds(Iterator &first, Iterator last, RDKit::RWMol &mol) { } else { return false; } - if (first < last && *first == ',') ++first; + if (first < last && *first == ',') { + ++first; + } } return true; } @@ -207,44 +253,67 @@ bool parse_coordinate_bonds(Iterator &first, Iterator last, RDKit::RWMol &mol) { template bool processRadicalSection(Iterator &first, Iterator last, RDKit::RWMol &mol, unsigned int numRadicalElectrons) { - if (first >= last) return false; + if (first >= last) { + return false; + } ++first; - if (first >= last || *first != ':') return false; + if (first >= last || *first != ':') { + return false; + } ++first; unsigned int atIdx; - if (!read_int(first, last, atIdx)) return false; + if (!read_int(first, last, atIdx)) { + return false; + } mol.getAtomWithIdx(atIdx)->setNumRadicalElectrons(numRadicalElectrons); while (first < last && *first == ',') { ++first; - if (first < last && (*first < '0' || *first > '9')) return true; - if (!read_int(first, last, atIdx)) return false; + if (first < last && (*first < '0' || *first > '9')) { + return true; + } + if (!read_int(first, last, atIdx)) { + return false; + } mol.getAtomWithIdx(atIdx)->setNumRadicalElectrons(numRadicalElectrons); } - if (first >= last) return false; + if (first >= last) { + return false; + } return true; } template bool parse_radicals(Iterator &first, Iterator last, RDKit::RWMol &mol) { - if (first >= last || *first != '^') return false; + if (first >= last || *first != '^') { + return false; + } while (*first == '^') { ++first; - if (first >= last) return false; - if (*first < '1' || *first > '7') + if (first >= last) { + return false; + } + if (*first < '1' || *first > '7') { return false; // these are the values that are allowed to be there + } switch (*first) { case '1': - if (!processRadicalSection(first, last, mol, 1)) return false; + if (!processRadicalSection(first, last, mol, 1)) { + return false; + } break; case '2': case '3': case '4': - if (!processRadicalSection(first, last, mol, 2)) return false; + if (!processRadicalSection(first, last, mol, 2)) { + return false; + } break; case '5': case '6': case '7': - if (!processRadicalSection(first, last, mol, 3)) return false; + if (!processRadicalSection(first, last, mol, 3)) { + return false; + } break; default: BOOST_LOG(rdWarningLog) @@ -272,7 +341,9 @@ bool parse_enhanced_stereo(Iterator &first, Iterator last, RDKit::RWMol &mol) { read_int(first, last, group_id); } - if (first >= last || *first != ':') return false; + if (first >= last || *first != ':') { + return false; + } ++first; std::vector atoms; @@ -304,36 +375,54 @@ bool parse_enhanced_stereo(Iterator &first, Iterator last, RDKit::RWMol &mol) { template bool parse_it(Iterator &first, Iterator last, RDKit::RWMol &mol) { - if (first >= last || *first != '|') return false; + if (first >= last || *first != '|') { + return false; + } ++first; while (first < last && *first != '|') { typename Iterator::difference_type length = std::distance(first, last); if (*first == '(') { - if (!parse_coords(first, last, mol)) return false; + if (!parse_coords(first, last, mol)) { + return false; + } } else if (*first == '$') { if (length > 4 && *(first + 1) == '_' && *(first + 2) == 'A' && *(first + 3) == 'V' && *(first + 4) == ':') { first += 4; - if (!parse_atom_values(first, last, mol)) return false; + if (!parse_atom_values(first, last, mol)) { + return false; + } } else { - if (!parse_atom_labels(first, last, mol)) return false; + if (!parse_atom_labels(first, last, mol)) { + return false; + } } } else if (length > 9 && std::string(first, first + 9) == "atomProp:") { first += 9; - if (!parse_atom_props(first, last, mol)) return false; + if (!parse_atom_props(first, last, mol)) { + return false; + } } else if (*first == 'C') { - if (!parse_coordinate_bonds(first, last, mol)) return false; + if (!parse_coordinate_bonds(first, last, mol)) { + return false; + } } else if (*first == '^') { - if (!parse_radicals(first, last, mol)) return false; + if (!parse_radicals(first, last, mol)) { + return false; + } } else if (*first == 'a' || *first == 'o' || (*first == '&' && first + 1 < last && first[1] != '#')) { - if (!parse_enhanced_stereo(first, last, mol)) return false; + if (!parse_enhanced_stereo(first, last, mol)) { + return false; + } } else { ++first; } // if(first < last && *first != '|') ++first; } - if (first >= last || *first != '|') return false; + if (first >= last || *first != '|') { + return false; + } ++first; // step past the last '|' return true; } @@ -347,9 +436,10 @@ void addquery(Q *qry, std::string symbol, RDKit::RWMol &mol, unsigned int idx) { qa->setQuery(qry); qa->setNoImplicit(true); mol.replaceAtom(idx, qa); - if (symbol != "") + if (symbol != "") { mol.getAtomWithIdx(idx)->setProp(RDKit::common_properties::atomLabel, symbol); + } delete qa; } void processCXSmilesLabels(RDKit::RWMol &mol) { @@ -359,7 +449,7 @@ void processCXSmilesLabels(RDKit::RWMol &mol) { if ((*atIt)->getPropIfPresent(RDKit::common_properties::atomLabel, symb)) { if (symb.size() > 3 && symb[0] == '_' && symb[1] == 'A' && symb[2] == 'P') { - unsigned int mapNum = + auto mapNum = boost::lexical_cast(symb.substr(3, symb.size() - 3)); (*atIt)->setAtomMapNum(mapNum); } else if (symb == "star_e") { @@ -399,11 +489,14 @@ void processCXSmilesLabels(RDKit::RWMol &mol) { void parseCXExtensions(RDKit::RWMol &mol, const std::string &extText, std::string::const_iterator &first) { // BOOST_LOG(rdWarningLog) << "parseCXNExtensions: " << extText << std::endl; - if (extText.empty() || extText[0] != '|') return; + if (extText.empty() || extText[0] != '|') { + return; + } first = extText.begin(); bool ok = parser::parse_it(first, extText.end(), mol); - if (!ok) + if (!ok) { throw RDKit::SmilesParseException("failure parsing CXSMILES extensions"); + } processCXSmilesLabels(mol); } } // end of namespace SmilesParseOps @@ -476,7 +569,9 @@ std::string get_enhanced_stereo_block( } } std::string resStr = res.str(); - if (!resStr.empty() && resStr.back() == ',') resStr.pop_back(); + if (!resStr.empty() && resStr.back() == ',') { + resStr.pop_back(); + } return resStr; } @@ -486,10 +581,11 @@ std::string get_value_block(const ROMol &mol, std::string res = ""; bool first = true; for (auto idx : atomOrder) { - if (!first) + if (!first) { res += ";"; - else + } else { first = false; + } std::string lbl; if (mol.getAtomWithIdx(idx)->getPropIfPresent(prop, lbl)) { res += quote_string(lbl); @@ -546,7 +642,9 @@ std::string get_coords_block(const ROMol &mol, res += boost::str(boost::format("%g,%g,") % pt.x % pt.y); if (conf.is3D()) { auto zc = boost::str(boost::format("%g") % pt.z); - if (zc != "0") res += zc; + if (zc != "0") { + res += zc; + } } } return res; @@ -563,7 +661,9 @@ std::string get_atom_props_block(const ROMol &mol, bool includePrivate = false, includeComputed = false; for (const auto &pn : atom->getPropList(includePrivate, includeComputed)) { if (std::find(skip.begin(), skip.end(), pn) == skip.end()) { - if (res.size() == 0) res += "atomProp"; + if (res.size() == 0) { + res += "atomProp"; + } res += boost::str(boost::format(":%d.%s.%s") % which % quote_string(pn) % quote_string(atom->getProp(pn))); @@ -595,28 +695,40 @@ std::string getCXExtensions(const ROMol &mol) { bool needValues = false; for (auto idx : atomOrder) { const auto at = mol.getAtomWithIdx(idx); - if (at->hasProp(common_properties::atomLabel)) needLabels = true; - if (at->hasProp(common_properties::molFileValue)) needValues = true; + if (at->hasProp(common_properties::atomLabel)) { + needLabels = true; + } + if (at->hasProp(common_properties::molFileValue)) { + needValues = true; + } } if (mol.getNumConformers()) { res += "(" + get_coords_block(mol, atomOrder) + ")"; } if (needLabels) { - if (res.size() > 1) res += ","; + if (res.size() > 1) { + res += ","; + } res += "$" + get_value_block(mol, atomOrder, common_properties::atomLabel) + "$"; } if (needValues) { - if (res.size() > 1) res += ","; + if (res.size() > 1) { + res += ","; + } res += "$_AV:" + get_value_block(mol, atomOrder, common_properties::molFileValue) + "$"; } auto radblock = get_radical_block(mol, atomOrder); if (radblock.size()) { - if (res.size() > 1) res += ","; + if (res.size() > 1) { + res += ","; + } res += radblock; - if (res.back() == ',') res.erase(res.size() - 1); + if (res.back() == ',') { + res.erase(res.size() - 1); + } } const auto atomblock = get_atom_props_block(mol, atomOrder); diff --git a/Code/GraphMol/SmilesParse/SmartsWrite.cpp b/Code/GraphMol/SmilesParse/SmartsWrite.cpp index 658335112..e45779079 100644 --- a/Code/GraphMol/SmilesParse/SmartsWrite.cpp +++ b/Code/GraphMol/SmilesParse/SmartsWrite.cpp @@ -56,8 +56,9 @@ std::string _combineChildSmarts(std::string cs1, unsigned int features1, "binary tree"); } res += cs1; - if (!(cs1.empty() || cs2.empty())) + if (!(cs1.empty() || cs2.empty())) { res += ","; + } res += cs2; features |= static_cast(QueryBoolFeatures::HAS_OR); } else if ((descrip.find("And") > 0) && @@ -72,8 +73,9 @@ std::string _combineChildSmarts(std::string cs1, unsigned int features1, features |= static_cast(QueryBoolFeatures::HAS_AND); } res += cs1; - if (!(cs1.empty() || cs2.empty())) + if (!(cs1.empty() || cs2.empty())) { res += symb; + } res += cs2; } else { std::stringstream err; @@ -245,9 +247,13 @@ std::string getAtomSmartsSimple(const QueryAtom *qatom, bool isAromatic; parseAtomType(query->getVal(), atNum, isAromatic); std::string symbol = PeriodicTable::getTable()->getElementSymbol(atNum); - if (isAromatic) symbol[0] += ('a' - 'A'); + if (isAromatic) { + symbol[0] += ('a' - 'A'); + } res << symbol; - if (!SmilesWrite::inOrganicSubset(atNum)) needParen = true; + if (!SmilesWrite::inOrganicSubset(atNum)) { + needParen = true; + } } else { BOOST_LOG(rdWarningLog) << "Cannot write SMARTS for query type : " << descrip @@ -305,9 +311,8 @@ std::string getRecursiveStructureQuerySmarts( const QueryAtom::QUERYATOM_QUERY *query) { PRECONDITION(query, "bad query"); PRECONDITION(query->getDescription() == "RecursiveStructure", "bad query"); - const RecursiveStructureQuery *rquery = - static_cast(query); - ROMol *qmol = const_cast(rquery->getQueryMol()); + const auto *rquery = static_cast(query); + auto *qmol = const_cast(rquery->getQueryMol()); std::string res = MolToSmarts(*qmol); res = "$(" + res + ")"; if (rquery->getNegation()) { @@ -340,10 +345,11 @@ std::string getBasicBondRepr(Bond::BondType typ, Bond::BondDir dir, res = ":"; break; case Bond::DATIVE: - if (reverseDative) + if (reverseDative) { res = "<-"; - else + } else { res = "->"; + } break; default: res = ""; @@ -446,8 +452,7 @@ std::string _recurseGetSmarts(const QueryAtom *qatom, features |= static_cast(QueryBoolFeatures::HAS_RECURSION); } else if ((dsc1 != "AtomOr") && (dsc1 != "AtomAnd")) { // child 1 is a simple node - const ATOM_EQUALS_QUERY *tchild = - static_cast(child1); + const auto *tchild = static_cast(child1); csmarts1 = getAtomSmartsSimple(qatom, tchild, needParen); bool nneg = (negate) ^ (tchild->getNegation()); if (nneg) { @@ -465,8 +470,7 @@ std::string _recurseGetSmarts(const QueryAtom *qatom, features |= static_cast(QueryBoolFeatures::HAS_RECURSION); } else if ((dsc2 != "AtomOr") && (dsc2 != "AtomAnd")) { // child 2 is a simple node - const ATOM_EQUALS_QUERY *tchild = - static_cast(child2); + const auto *tchild = static_cast(child2); csmarts2 = getAtomSmartsSimple(qatom, tchild, needParen); bool nneg = (negate) ^ (tchild->getNegation()); if (nneg) { @@ -545,8 +549,7 @@ std::string _recurseBondSmarts(const Bond *bond, if ((dsc1 != "BondOr") && (dsc1 != "BondAnd")) { // child1 is simple node get the smarts directly - const BOND_EQUALS_QUERY *tchild = - static_cast(child1); + const auto *tchild = static_cast(child1); csmarts1 = getBondSmartsSimple(bond, tchild, atomToLeftIdx); bool nneg = (negate) ^ (tchild->getNegation()); if (nneg) { @@ -562,8 +565,7 @@ std::string _recurseBondSmarts(const Bond *bond, // now deal with the second child if ((dsc2 != "BondOr") && (dsc2 != "BondAnd")) { // child 2 is a simple node - const BOND_EQUALS_QUERY *tchild = - static_cast(child2); + const auto *tchild = static_cast(child2); csmarts2 = getBondSmartsSimple(bond, tchild, atomToLeftIdx); bool nneg = (negate) ^ (tchild->getNegation()); if (nneg) { @@ -636,20 +638,21 @@ std::string FragmentSmartsConstruct( for (msCI = molStack.begin(); msCI != molStack.end(); msCI++) { switch (msCI->type) { case Canon::MOL_STACK_ATOM: { - QueryAtom *qatm = static_cast(msCI->obj.atom); + auto *qatm = static_cast(msCI->obj.atom); res << SmartsWrite::GetAtomSmarts(qatm); break; } case Canon::MOL_STACK_BOND: { - QueryBond *qbnd = static_cast(msCI->obj.bond); + auto *qbnd = static_cast(msCI->obj.bond); res << SmartsWrite::GetBondSmarts(qbnd, msCI->number); break; } case Canon::MOL_STACK_RING: { - if (msCI->number < 10) + if (msCI->number < 10) { res << msCI->number; - else + } else { res << "%" << msCI->number; + } break; } case Canon::MOL_STACK_BRANCH_OPEN: { @@ -709,7 +712,9 @@ std::string getNonQueryAtomSmarts(const QueryAtom *qatom) { // FIX: probably should be smarter about Hs: if (hs) { res << "H"; - if (hs > 1) res << hs; + if (hs > 1) { + res << hs; + } } int chg = qatom->getFormalCharge(); if (chg) { @@ -838,8 +843,7 @@ std::string GetAtomSmarts(const QueryAtom *qatom) { res = getRecursiveStructureQuerySmarts(query); needParen = true; } else { // we have a simple smarts - ATOM_EQUALS_QUERY *tquery = - static_cast(qatom->getQuery()); + auto *tquery = static_cast(qatom->getQuery()); res = getAtomSmartsSimple(qatom, tquery, needParen); if (tquery->getNegation()) { res = "!" + res; @@ -890,8 +894,7 @@ std::string GetBondSmarts(const QueryBond *bond, int atomToLeftIdx) { if (query->getNegation()) { res = "!"; } - const BOND_EQUALS_QUERY *tquery = - static_cast(query); + const auto *tquery = static_cast(query); res += getBondSmartsSimple(bond, tquery, atomToLeftIdx); } // BOOST_LOG(rdInfoLog) << "\t query:" << descrip << " " << res << std::endl; @@ -902,7 +905,9 @@ std::string GetBondSmarts(const QueryBond *bond, int atomToLeftIdx) { std::string MolToSmarts(const ROMol &mol, bool doIsomericSmarts) { const unsigned int nAtoms = mol.getNumAtoms(); - if (!nAtoms) return ""; + if (!nAtoms) { + return ""; + } std::vector colors(nAtoms, Canon::WHITE_NODE); return molToSmarts(mol, doIsomericSmarts, std::move(colors)); diff --git a/Code/GraphMol/SmilesParse/SmilesParse.cpp b/Code/GraphMol/SmilesParse/SmilesParse.cpp index fedf7af69..5b31a983e 100644 --- a/Code/GraphMol/SmilesParse/SmilesParse.cpp +++ b/Code/GraphMol/SmilesParse/SmilesParse.cpp @@ -272,7 +272,9 @@ RWMol *toMol(const std::string &inp, int func(const std::string &, std::vector &), const std::string &origInp) { // empty strings produce empty molecules: - if (inp.empty()) return new RWMol(); + if (inp.empty()) { + return new RWMol(); + } RWMol *res = nullptr; std::vector molVect; try { @@ -312,7 +314,9 @@ RWMol *toMol(const std::string &inp, Atom *toAtom(const std::string &inp, int func(const std::string &, Atom *&)) { // empty strings produce empty molecules: - if (inp.empty()) return nullptr; + if (inp.empty()) { + return nullptr; + } Atom *res = nullptr; try { func(inp, res); @@ -330,7 +334,9 @@ Atom *toAtom(const std::string &inp, int func(const std::string &, Atom *&)) { Bond *toBond(const std::string &inp, int func(const std::string &, Bond *&)) { // empty strings produce empty molecules: - if (inp.empty()) return nullptr; + if (inp.empty()) { + return nullptr; + } Bond *res = nullptr; try { func(inp, res); @@ -355,7 +361,9 @@ void preprocessSmiles(const std::string &smiles, boost::split(tokens, smiles, boost::is_any_of(" \t"), boost::token_compress_on); lsmiles = tokens[0]; - if (tokens.size() > 1) name = tokens[1]; + if (tokens.size() > 1) { + name = tokens[1]; + } } else if (params.allowCXSMILES) { size_t sidx = smiles.find_first_of(" \t"); if (sidx != std::string::npos && sidx != 0) { @@ -446,7 +454,9 @@ RWMol *SmilesToMol(const std::string &smiles, bool cleanIt = true, force = true, flagPossible = true; MolOps::assignStereochemistry(*res, cleanIt, force, flagPossible); } - if (res && !name.empty()) res->setProp(common_properties::_Name, name); + if (res && !name.empty()) { + res->setProp(common_properties::_Name, name); + } return res; }; diff --git a/Code/GraphMol/SmilesParse/SmilesParseOps.cpp b/Code/GraphMol/SmilesParse/SmilesParseOps.cpp index a3321f70a..72354e821 100644 --- a/Code/GraphMol/SmilesParse/SmilesParseOps.cpp +++ b/Code/GraphMol/SmilesParse/SmilesParseOps.cpp @@ -111,7 +111,9 @@ void AddFragToMol(RWMol *mol, RWMol *frag, Bond::BondType bondOrder, tmpVect)) { BOOST_FOREACH (int &v, tmpVect) { // if the ring closure is not already a bond, don't touch it: - if (v >= 0) v += nOrigBonds; + if (v >= 0) { + v += nOrigBonds; + } } Atom *newAtom = mol->getAtomWithIdx(nOrigAtoms + (*atomIt)->getIdx()); newAtom->setProp(common_properties::_RingClosures, tmpVect); @@ -592,15 +594,18 @@ void CleanupAfterParsing(RWMol *mol) { PRECONDITION(mol, "no molecule"); for (RWMol::AtomIterator atomIt = mol->beginAtoms(); atomIt != mol->endAtoms(); ++atomIt) { - if ((*atomIt)->hasProp(common_properties::_RingClosures)) + if ((*atomIt)->hasProp(common_properties::_RingClosures)) { (*atomIt)->clearProp(common_properties::_RingClosures); - if ((*atomIt)->hasProp(common_properties::_SmilesStart)) + } + if ((*atomIt)->hasProp(common_properties::_SmilesStart)) { (*atomIt)->clearProp(common_properties::_SmilesStart); + } } for (RWMol::BondIterator bondIt = mol->beginBonds(); bondIt != mol->endBonds(); ++bondIt) { - if ((*bondIt)->hasProp(common_properties::_unspecifiedOrder)) + if ((*bondIt)->hasProp(common_properties::_unspecifiedOrder)) { (*bondIt)->clearProp(common_properties::_unspecifiedOrder); + } } } diff --git a/Code/GraphMol/SmilesParse/SmilesWrite.cpp b/Code/GraphMol/SmilesParse/SmilesWrite.cpp index 36315e131..60161b87a 100644 --- a/Code/GraphMol/SmilesParse/SmilesWrite.cpp +++ b/Code/GraphMol/SmilesParse/SmilesWrite.cpp @@ -118,7 +118,9 @@ std::string GetAtomSmiles(const Atom *atom, bool doKekule, const Bond *bondIn, } else { needsBracket = true; } - if (needsBracket) res += "["; + if (needsBracket) { + res += "["; + } if (isotope && (isomericSmiles || (atom->hasOwningMol() && atom->getOwningMol().hasProp( @@ -138,16 +140,21 @@ std::string GetAtomSmiles(const Atom *atom, bool doKekule, const Bond *bondIn, unsigned int totNumHs = atom->getTotalNumHs(); if (totNumHs > 0) { res += "H"; - if (totNumHs > 1) res += std::to_string(totNumHs); + if (totNumHs > 1) { + res += std::to_string(totNumHs); + } } if (fc > 0) { res += "+"; - if (fc > 1) res += std::to_string(fc); - } else if (fc < 0) { - if (fc < -1) + if (fc > 1) { res += std::to_string(fc); - else + } + } else if (fc < 0) { + if (fc < -1) { + res += std::to_string(fc); + } else { res += "-"; + } } int mapNum; @@ -172,7 +179,9 @@ std::string GetAtomSmiles(const Atom *atom, bool doKekule, const Bond *bondIn, std::string GetBondSmiles(const Bond *bond, int atomToLeftIdx, bool doKekule, bool allBondsExplicit) { PRECONDITION(bond, "bad bond"); - if (atomToLeftIdx < 0) atomToLeftIdx = bond->getBeginAtomIdx(); + if (atomToLeftIdx < 0) { + atomToLeftIdx = bond->getBeginAtomIdx(); + } std::string res = ""; bool aromatic = false; @@ -184,8 +193,9 @@ std::string GetBondSmiles(const Bond *bond, int atomToLeftIdx, bool doKekule, auto a2 = bond->getOwningMol().getAtomWithIdx( bond->getOtherAtomIdx(atomToLeftIdx)); if ((a1->getIsAromatic() && a2->getIsAromatic()) && - (a1->getAtomicNum() || a2->getAtomicNum())) + (a1->getAtomicNum() || a2->getAtomicNum())) { aromatic = true; + } } else { aromatic = false; } @@ -206,19 +216,23 @@ std::string GetBondSmiles(const Bond *bond, int atomToLeftIdx, bool doKekule, if (dir != Bond::NONE && dir != Bond::UNKNOWN) { switch (dir) { case Bond::ENDDOWNRIGHT: - if (allBondsExplicit || - (bond->hasOwningMol() && - bond->getOwningMol().hasProp(common_properties::_doIsoSmiles))) + if (allBondsExplicit || (bond->hasOwningMol() && + bond->getOwningMol().hasProp( + common_properties::_doIsoSmiles))) { res = "\\"; + } break; case Bond::ENDUPRIGHT: - if (allBondsExplicit || - (bond->hasOwningMol() && - bond->getOwningMol().hasProp(common_properties::_doIsoSmiles))) + if (allBondsExplicit || (bond->hasOwningMol() && + bond->getOwningMol().hasProp( + common_properties::_doIsoSmiles))) { res = "/"; + } break; default: - if (allBondsExplicit) res = "-"; + if (allBondsExplicit) { + res = "-"; + } break; } } else { @@ -228,15 +242,18 @@ std::string GetBondSmiles(const Bond *bond, int atomToLeftIdx, bool doKekule, // FIX: we should be able to dump kekulized smiles // currently this is possible by removing all // isAromatic flags, but there should maybe be another way - if (allBondsExplicit) + if (allBondsExplicit) { res = "-"; - else if (aromatic && !bond->getIsAromatic()) + } else if (aromatic && !bond->getIsAromatic()) { res = "-"; + } } break; case Bond::DOUBLE: // see note above - if (!aromatic || !bond->getIsAromatic() || allBondsExplicit) res = "="; + if (!aromatic || !bond->getIsAromatic() || allBondsExplicit) { + res = "="; + } break; case Bond::TRIPLE: res = "#"; @@ -245,19 +262,23 @@ std::string GetBondSmiles(const Bond *bond, int atomToLeftIdx, bool doKekule, if (dir != Bond::NONE && dir != Bond::UNKNOWN) { switch (dir) { case Bond::ENDDOWNRIGHT: - if (allBondsExplicit || - (bond->hasOwningMol() && - bond->getOwningMol().hasProp(common_properties::_doIsoSmiles))) + if (allBondsExplicit || (bond->hasOwningMol() && + bond->getOwningMol().hasProp( + common_properties::_doIsoSmiles))) { res = "\\"; + } break; case Bond::ENDUPRIGHT: - if (allBondsExplicit || - (bond->hasOwningMol() && - bond->getOwningMol().hasProp(common_properties::_doIsoSmiles))) + if (allBondsExplicit || (bond->hasOwningMol() && + bond->getOwningMol().hasProp( + common_properties::_doIsoSmiles))) { res = "/"; + } break; default: - if (allBondsExplicit || !aromatic) res = ":"; + if (allBondsExplicit || !aromatic) { + res = ":"; + } break; } } else if (allBondsExplicit || !aromatic) { @@ -266,10 +287,11 @@ std::string GetBondSmiles(const Bond *bond, int atomToLeftIdx, bool doKekule, break; case Bond::DATIVE: if (atomToLeftIdx >= 0 && - bond->getBeginAtomIdx() == static_cast(atomToLeftIdx)) + bond->getBeginAtomIdx() == static_cast(atomToLeftIdx)) { res = "->"; - else + } else { res = "<-"; + } break; default: res = "~"; @@ -299,7 +321,9 @@ std::string FragmentSmilesConstruct( std::map ringClosureMap; int ringIdx, closureVal; - if (!canonical) mol.setProp(common_properties::_StereochemDone, 1); + if (!canonical) { + mol.setProp(common_properties::_StereochemDone, 1); + } std::list ringClosuresToErase; Canon::canonicalizeFragment(mol, atomIdx, colors, ranks, molStack, @@ -353,7 +377,9 @@ std::string FragmentSmilesConstruct( std::map::iterator mapIt; for (mapIt = ringClosureMap.begin(); mapIt != ringClosureMap.end(); mapIt++) { - if (mapIt->second == closureVal) break; + if (mapIt->second == closureVal) { + break; + } } if (mapIt == ringClosureMap.end()) { done = true; @@ -363,12 +389,13 @@ std::string FragmentSmilesConstruct( } ringClosureMap[ringIdx] = closureVal; } - if (closureVal < 10) + if (closureVal < 10) { res << (char)(closureVal + '0'); - else if (closureVal < 100) + } else if (closureVal < 100) { res << '%' << closureVal; - else // use extension to OpenSMILES + } else { // use extension to OpenSMILES res << "%(" << closureVal << ')'; + } break; case Canon::MOL_STACK_BRANCH_OPEN: res << "("; @@ -394,7 +421,9 @@ static bool SortBasedOnFirstElement( std::string MolToSmiles(const ROMol &mol, bool doIsomericSmiles, bool doKekule, int rootedAtAtom, bool canonical, bool allBondsExplicit, bool allHsExplicit, bool doRandom) { - if (!mol.getNumAtoms()) return ""; + if (!mol.getNumAtoms()) { + return ""; + } PRECONDITION(rootedAtAtom < 0 || static_cast(rootedAtAtom) < mol.getNumAtoms(), "rootedAtomAtom must be less than the number of atoms"); @@ -463,7 +492,9 @@ std::string MolToSmiles(const ROMol &mol, bool doIsomericSmiles, bool doKekule, doIsomericSmiles); } } else { - for (unsigned int i = 0; i < tmol->getNumAtoms(); ++i) ranks[i] = i; + for (unsigned int i = 0; i < tmol->getNumAtoms(); ++i) { + ranks[i] = i; + } } #ifdef VERBOSE_CANON for (unsigned int tmpI = 0; tmpI < ranks.size(); tmpI++) { @@ -523,22 +554,26 @@ std::string MolToSmiles(const ROMol &mol, bool doIsomericSmiles, bool doKekule, // order typedef std::pair> PairStrAndVec; std::vector tmp(vfragsmi.size()); - for (unsigned int ti = 0; ti < vfragsmi.size(); ++ti) + for (unsigned int ti = 0; ti < vfragsmi.size(); ++ti) { tmp[ti] = PairStrAndVec(vfragsmi[ti], allAtomOrdering[ti]); + } std::sort(tmp.begin(), tmp.end(), SortBasedOnFirstElement); for (unsigned int ti = 0; ti < vfragsmi.size(); ++ti) { result += tmp[ti].first; - if (ti < vfragsmi.size() - 1) result += "."; + if (ti < vfragsmi.size() - 1) { + result += "."; + } flattenedAtomOrdering.insert(flattenedAtomOrdering.end(), tmp[ti].second.begin(), tmp[ti].second.end()); } } else { // Not canonical - for (auto &i : allAtomOrdering) + for (auto &i : allAtomOrdering) { flattenedAtomOrdering.insert(flattenedAtomOrdering.end(), i.begin(), i.end()); + } for (unsigned i = 0; i < vfragsmi.size(); ++i) { result += vfragsmi[i]; if (i < vfragsmi.size() - 1) { @@ -586,7 +621,9 @@ std::string MolFragmentToSmiles(const ROMol &mol, "bad atomSymbols vector"); PRECONDITION(!bondSymbols || bondSymbols->size() >= mol.getNumBonds(), "bad bondSymbols vector"); - if (!mol.getNumAtoms()) return ""; + if (!mol.getNumAtoms()) { + return ""; + } ROMol tmol(mol, true); if (doIsomericSmiles) { @@ -606,8 +643,9 @@ std::string MolFragmentToSmiles(const ROMol &mol, boost::tie(beg, end) = mol.getAtomBonds(mol.getAtomWithIdx(aidx)); while (beg != end) { const Bond *bond = mol[*beg]; - if (atomsInPlay[bond->getOtherAtomIdx(aidx)]) + if (atomsInPlay[bond->getOtherAtomIdx(aidx)]) { bondsInPlay.set(bond->getIdx()); + } ++beg; } } @@ -678,7 +716,9 @@ std::string MolFragmentToSmiles(const ROMol &mol, // std::cerr << std::endl; // MolOps::rankAtomsInFragment(tmol,ranks,atomsInPlay,bondsInPlay,atomSymbols,bondSymbols); } else { - for (unsigned int i = 0; i < tmol.getNumAtoms(); ++i) ranks[i] = i; + for (unsigned int i = 0; i < tmol.getNumAtoms(); ++i) { + ranks[i] = i; + } } #ifdef VERBOSE_CANON for (unsigned int tmpI = 0; tmpI < ranks.size(); tmpI++) { diff --git a/Code/GraphMol/SmilesParse/smatest.cpp b/Code/GraphMol/SmilesParse/smatest.cpp index d4c413883..6c4376d80 100644 --- a/Code/GraphMol/SmilesParse/smatest.cpp +++ b/Code/GraphMol/SmilesParse/smatest.cpp @@ -2658,7 +2658,7 @@ void testGithub2142() { std::string sma2 = "[C]"; std::unique_ptr m2(SmartsToMol(sma2)); TEST_ASSERT(m2); - QueryAtom *qa = static_cast(m2->getAtomWithIdx(0)); + auto *qa = static_cast(m2->getAtomWithIdx(0)); const auto q1 = static_cast(m1->getAtomWithIdx(0))->getQuery(); qa->expandQuery(q1->copy(), Queries::COMPOSITE_OR); bool ok = true; diff --git a/Code/GraphMol/SmilesParse/test.cpp b/Code/GraphMol/SmilesParse/test.cpp index 14e4f3018..1f8b60c61 100644 --- a/Code/GraphMol/SmilesParse/test.cpp +++ b/Code/GraphMol/SmilesParse/test.cpp @@ -3879,8 +3879,9 @@ void testDativeBonds() { int dative_bond_count = 0; for (size_t i = 0; i < m->getNumBonds(); i++) { - if (m->getBondWithIdx(i)->getBondType() == Bond::DATIVE) + if (m->getBondWithIdx(i)->getBondType() == Bond::DATIVE) { dative_bond_count++; + } } TEST_ASSERT(dative_bond_count == 1); @@ -3895,8 +3896,9 @@ void testDativeBonds() { int dative_bond_count = 0; for (size_t i = 0; i < m->getNumBonds(); i++) { - if (m->getBondWithIdx(i)->getBondType() == Bond::DATIVE) + if (m->getBondWithIdx(i)->getBondType() == Bond::DATIVE) { dative_bond_count++; + } } TEST_ASSERT(dative_bond_count == 2); @@ -4048,10 +4050,9 @@ void testRingClosureNumberWithBrackets() { const char *benzenes[6] = { "c1ccccc1", "c%(1)ccccc%(1)", "c%(12)ccccc%(12)", "c%(123)ccccc%(123)", "c%(1234)ccccc%(1234)", "c%(99999)ccccc%(99999)"}; - for (int i = 0; i < 6; ++i) { - BOOST_LOG(rdInfoLog) << "Test: " << benzenes[i] << " (should be read)" - << std::endl; - ROMol *m = SmilesToMol(benzenes[i]); + for (auto &i : benzenes) { + BOOST_LOG(rdInfoLog) << "Test: " << i << " (should be read)" << std::endl; + ROMol *m = SmilesToMol(i); TEST_ASSERT(m); TEST_ASSERT(m->getNumAtoms() == 6); TEST_ASSERT(m->getBondWithIdx(0)->getIsAromatic()); @@ -4061,11 +4062,11 @@ void testRingClosureNumberWithBrackets() { } const char *not_allowed[2] = {"c%()ccccc%()", "c%(100000)ccccc%(100000)"}; - for (int i = 0; i < 2; ++i) { - BOOST_LOG(rdInfoLog) << "Test: " << not_allowed[i] - << " (should NOT be read)" << std::endl; - ROMol *m = SmilesToMol(not_allowed[i]); - TEST_ASSERT(m == (ROMol *)0); + for (auto &i : not_allowed) { + BOOST_LOG(rdInfoLog) << "Test: " << i << " (should NOT be read)" + << std::endl; + ROMol *m = SmilesToMol(i); + TEST_ASSERT(m == (ROMol *)nullptr); delete m; } } diff --git a/Code/GraphMol/StereoGroup.cpp b/Code/GraphMol/StereoGroup.cpp index 302fe2b26..71dd5e456 100644 --- a/Code/GraphMol/StereoGroup.cpp +++ b/Code/GraphMol/StereoGroup.cpp @@ -1,4 +1,5 @@ #include +#include #include "StereoGroup.h" namespace RDKit { @@ -7,7 +8,7 @@ StereoGroup::StereoGroup(StereoGroupType grouptype, std::vector &&atoms) : d_grouptype(grouptype), d_atoms(atoms) {} StereoGroup::StereoGroup(StereoGroupType grouptype, const std::vector &atoms) - : d_grouptype(grouptype), d_atoms(atoms) {} + : d_grouptype(grouptype), d_atoms(std::move(atoms)) {} StereoGroupType StereoGroup::getGroupType() const { return d_grouptype; } diff --git a/Code/GraphMol/Subgraphs/SubgraphUtils.cpp b/Code/GraphMol/Subgraphs/SubgraphUtils.cpp index cba11b1a9..0e7bff443 100644 --- a/Code/GraphMol/Subgraphs/SubgraphUtils.cpp +++ b/Code/GraphMol/Subgraphs/SubgraphUtils.cpp @@ -40,7 +40,7 @@ ROMol *pathToSubmol(const ROMol &mol, const PATH_TYPE &path, bool useQuery, // have to do this in two different blocks because of issues with variable // scopes. for(auto bondidx : sorted_path) { - QueryBond *bond = new QueryBond(*(mol.getBondWithIdx(bondidx))); + auto *bond = new QueryBond(*(mol.getBondWithIdx(bondidx))); int begIdx = bond->getBeginAtomIdx(); int endIdx = bond->getEndAtomIdx(); @@ -132,9 +132,10 @@ using std::int32_t; DiscrimTuple calcPathDiscriminators(const ROMol &mol, const PATH_TYPE &path, bool useBO, std::vector *extraInvars) { - if (extraInvars) + if (extraInvars) { CHECK_INVARIANT(extraInvars->size() == mol.getNumAtoms(), "bad extra invars"); + } DiscrimTuple res; // Start by collecting the atoms in the path and their degrees diff --git a/Code/GraphMol/Subgraphs/Subgraphs.cpp b/Code/GraphMol/Subgraphs/Subgraphs.cpp index 2c887f157..89bb7c8ee 100644 --- a/Code/GraphMol/Subgraphs/Subgraphs.cpp +++ b/Code/GraphMol/Subgraphs/Subgraphs.cpp @@ -270,7 +270,9 @@ pathFinderHelper(int *adjMat, unsigned int dim, unsigned int minLen, // and build them up one index at a time: for (unsigned int length = 1; length < maxLen; length++) { // extend each path: - if (length >= minLen) res[length] = paths; + if (length >= minLen) { + res[length] = paths; + } paths = extendPaths(adjMat, dim, paths, maxLen); } res[maxLen] = paths; @@ -540,8 +542,9 @@ findAllPathsOfLengthN(const ROMol &mol, unsigned int targetLen, bool useBonds, PATH_TYPE findAtomEnvironmentOfRadiusN(const ROMol &mol, unsigned int radius, unsigned int rootedAtAtom, bool useHs) { - if (rootedAtAtom >= mol.getNumAtoms()) + if (rootedAtAtom >= mol.getNumAtoms()) { throw ValueErrorException("bad atom index"); + } PATH_TYPE res; std::list > nbrStack; diff --git a/Code/GraphMol/Substruct/SubstructMatch.cpp b/Code/GraphMol/Substruct/SubstructMatch.cpp index 9d6162dab..4a7fd291a 100644 --- a/Code/GraphMol/Substruct/SubstructMatch.cpp +++ b/Code/GraphMol/Substruct/SubstructMatch.cpp @@ -149,11 +149,14 @@ class MolMatchFinalCheckFunctor { for (unsigned int i = 0; i < d_query.getNumBonds(); ++i) { const Bond *qBnd = d_query.getBondWithIdx(i); if (qBnd->getBondType() != Bond::DOUBLE || - qBnd->getStereo() <= Bond::STEREOANY) + qBnd->getStereo() <= Bond::STEREOANY) { continue; + } // don't think this can actually happen, but check to be sure: - if (qBnd->getStereoAtoms().size() != 2) continue; + if (qBnd->getStereoAtoms().size() != 2) { + continue; + } std::map qMap; for (unsigned int j = 0; j < d_query.getNumAtoms(); ++j) { @@ -163,25 +166,32 @@ class MolMatchFinalCheckFunctor { c2[qMap[qBnd->getBeginAtomIdx()]], c2[qMap[qBnd->getEndAtomIdx()]]); CHECK_INVARIANT(mBnd, "Matching bond not found"); if (mBnd->getBondType() != Bond::DOUBLE || - qBnd->getStereo() <= Bond::STEREOANY) + qBnd->getStereo() <= Bond::STEREOANY) { continue; + } // don't think this can actually happen, but check to be sure: - if (mBnd->getStereoAtoms().size() != 2) continue; + if (mBnd->getStereoAtoms().size() != 2) { + continue; + } unsigned int end1Matches = 0; unsigned int end2Matches = 0; if (c2[qMap[qBnd->getBeginAtomIdx()]] == mBnd->getBeginAtomIdx()) { // query Begin == mol Begin - if (c2[qMap[qBnd->getStereoAtoms()[0]]] == mBnd->getStereoAtoms()[0]) + if (c2[qMap[qBnd->getStereoAtoms()[0]]] == mBnd->getStereoAtoms()[0]) { end1Matches = 1; - if (c2[qMap[qBnd->getStereoAtoms()[1]]] == mBnd->getStereoAtoms()[1]) + } + if (c2[qMap[qBnd->getStereoAtoms()[1]]] == mBnd->getStereoAtoms()[1]) { end2Matches = 1; + } } else { // query End == mol Begin - if (c2[qMap[qBnd->getStereoAtoms()[0]]] == mBnd->getStereoAtoms()[1]) + if (c2[qMap[qBnd->getStereoAtoms()[0]]] == mBnd->getStereoAtoms()[1]) { end1Matches = 1; - if (c2[qMap[qBnd->getStereoAtoms()[1]]] == mBnd->getStereoAtoms()[0]) + } + if (c2[qMap[qBnd->getStereoAtoms()[1]]] == mBnd->getStereoAtoms()[0]) { end2Matches = 1; + } } const unsigned totalMatches = end1Matches + end2Matches; @@ -190,8 +200,12 @@ class MolMatchFinalCheckFunctor { const auto qStereo = Chirality::translateEZLabelToCisTrans(qBnd->getStereo()); - if (mStereo == qStereo && totalMatches == 1) return false; - if (mStereo != qStereo && totalMatches != 1) return false; + if (mStereo == qStereo && totalMatches == 1) { + return false; + } + if (mStereo != qStereo && totalMatches != 1) { + return false; + } } return true; @@ -216,8 +230,9 @@ class AtomLabelFunctor { qAt->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW) { const Atom *mAt = d_mol.getAtomWithIdx(j); if (mAt->getChiralTag() != Atom::CHI_TETRAHEDRAL_CW && - mAt->getChiralTag() != Atom::CHI_TETRAHEDRAL_CCW) + mAt->getChiralTag() != Atom::CHI_TETRAHEDRAL_CCW) { return false; + } } } res = atomCompat(d_query[i], d_mol[j], d_params); @@ -242,8 +257,9 @@ class BondLabelFunctor { qBnd->getStereo() > Bond::STEREOANY) { const Bond *mBnd = d_mol[j]; if (mBnd->getBondType() == Bond::DOUBLE && - mBnd->getStereo() <= Bond::STEREOANY) + mBnd->getStereo() <= Bond::STEREOANY) { return false; + } } } bool res = bondCompat(d_query[i], d_mol[j], d_params); @@ -262,8 +278,9 @@ void mergeMatchVect(std::vector &matches, (matches.size() < args.params.maxMatches) && (it != matchesTmp.end()); ++it) { if ((std::find(matches.begin(), matches.end(), *it) == matches.end()) && - (!args.params.uniquify || isToBeAddedToVector(matches, *it))) + (!args.params.uniquify || isToBeAddedToVector(matches, *it))) { matches.push_back(*it); + } } }; void ResSubstructMatchHelper_(const ResSubstructMatchHelperArgs_ &args, @@ -386,11 +403,11 @@ std::vector SubstructMatch( detail::ResSubstructMatchHelperArgs_ args = {resMolSupplier, query, params}; unsigned int nt = std::min(resMolSupplier.length(), getNumThreadsToUse(params.numThreads)); - if (nt == 1) + if (nt == 1) { detail::ResSubstructMatchHelper_(args, &matches, 0, resMolSupplier.length()); #ifdef RDK_THREADSAFE_SSS - else { + } else { std::vector> tg; std::vector *> matchesThread(nt); unsigned int ei = 0; @@ -411,8 +428,9 @@ std::vector SubstructMatch( } unsigned int matchSize = 0; - for (unsigned int ti = 0; ti < nt; ++ti) + for (unsigned int ti = 0; ti < nt; ++ti) { matchSize += matchesThread[ti]->size(); + } matches.reserve(matchSize); for (unsigned int ti = 0; ti < nt; ++ti) { mergeMatchVect(matches, *(matchesThread[ti]), args); @@ -489,7 +507,7 @@ void MatchSubqueries(const ROMol &mol, QueryAtom::QUERYATOM_QUERY *query, // std::cout << "*-*-* MS: " << (int)query << std::endl; // std::cout << "\t\t" << typeid(*query).name() << std::endl; if (query->getDescription() == "RecursiveStructure") { - RecursiveStructureQuery *rsq = (RecursiveStructureQuery *)query; + auto *rsq = (RecursiveStructureQuery *)query; #ifdef RDK_THREADSAFE_SSS rsq->d_mutex.lock(); locked.push_back(rsq); @@ -551,7 +569,9 @@ bool matchCompare(const std::pair &a, const std::pair &b) { bool matchVectCompare(const MatchVectType &a, const MatchVectType &b) { for (unsigned int i = 0; i < std::min(a.size(), b.size()); ++i) { - if (a[i].second != b[i].second) return (a[i].second < b[i].second); + if (a[i].second != b[i].second) { + return (a[i].second < b[i].second); + } } return (a.size() < b.size()); } @@ -567,11 +587,13 @@ bool isToBeAddedToVector(std::vector &matches, if (!isToBeAdded) { MatchVectType matchCopy = *it; std::sort(matchCopy.begin(), matchCopy.end(), matchCompare); - for (unsigned int i = 0; !isToBeAdded && (i < matchCopy.size()); ++i) + for (unsigned int i = 0; !isToBeAdded && (i < matchCopy.size()); ++i) { isToBeAdded = (mCopy[i].second != matchCopy[i].second); + } if (!isToBeAdded) { - for (unsigned int i = 0; !isToBeAdded && (i < m.size()); ++i) + for (unsigned int i = 0; !isToBeAdded && (i < m.size()); ++i) { isToBeAdded = (m[i].second < (*it)[i].second); + } if (isToBeAdded) { matches.erase(it); break; diff --git a/Code/GraphMol/Substruct/test1.cpp b/Code/GraphMol/Substruct/test1.cpp index 0ee1c09cb..61452f87e 100644 --- a/Code/GraphMol/Substruct/test1.cpp +++ b/Code/GraphMol/Substruct/test1.cpp @@ -481,7 +481,9 @@ void test7() { n = SubstructMatch(*m, *q1, matches, true, true); CHECK_INVARIANT(n == 1, ""); CHECK_INVARIANT(matches[0].size() == 3, ""); - if (!(i % 500)) std::cout << i << std::endl; + if (!(i % 500)) { + std::cout << i << std::endl; + } } delete m; delete a6; @@ -676,7 +678,9 @@ void runblock(const std::vector &mols, const ROMol *query, unsigned int idx) { for (unsigned int j = 0; j < 100; j++) { for (unsigned int i = 0; i < mols.size(); ++i) { - if (i % count != idx) continue; + if (i % count != idx) { + continue; + } ROMol *mol = mols[i]; MatchVectType matchV; @@ -703,7 +707,9 @@ void testMultiThread() { } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } mols.push_back(mol); } std::vector> tg; @@ -771,7 +777,9 @@ void testMultiThread() { std::cerr << " done" << std::endl; delete query; - for (auto &mol : mols) delete mol; + for (auto &mol : mols) { + delete mol; + } BOOST_LOG(rdErrorLog) << " done" << std::endl; } @@ -1852,7 +1860,9 @@ int main(int argc, char *argv[]) { test5(); test5QueryRoot(); test6(); - if (argc > 1 && !strcmp(argv[1], "-l")) test7(); + if (argc > 1 && !strcmp(argv[1], "-l")) { + test7(); + } // test9(); testRecursiveSerialNumbers(); testMultiThread(); diff --git a/Code/GraphMol/SubstructLibrary/SubstructLibrary.cpp b/Code/GraphMol/SubstructLibrary/SubstructLibrary.cpp index e7a434c41..18d7c9295 100644 --- a/Code/GraphMol/SubstructLibrary/SubstructLibrary.cpp +++ b/Code/GraphMol/SubstructLibrary/SubstructLibrary.cpp @@ -65,8 +65,9 @@ struct Bits { useQueryQueryMatches(useQueryQueryMatches) { if (fps) { queryBits = fps->makeFingerprint(m); - } else + } else { queryBits = nullptr; + } } bool check(unsigned int idx) const { @@ -117,7 +118,9 @@ void SubSearcher(const ROMol &in_query, const Bits &bits, for (unsigned int idx = start; idx < end && (maxResults == -1 || counter < maxResults); idx += numThreads) { - if (!bits.check(idx)) continue; + if (!bits.check(idx)) { + continue; + } // need shared_ptr as it (may) control the lifespan of the // returned molecule! const boost::shared_ptr &m = mols.getMol(idx); @@ -136,9 +139,13 @@ void SubSearcher(const ROMol &in_query, const Bits &bits, // atomic // several substructure runs can update the counter beyond the maxResults // This okay: if we get one or two extra, we can fix it on the way out - if (maxResults != -1 && counter >= maxResults) break; + if (maxResults != -1 && counter >= maxResults) { + break; + } idxs.push_back(idx); - if (maxResults != -1) counter++; + if (maxResults != -1) { + counter++; + } } } } @@ -151,7 +158,9 @@ void SubSearchMatchCounter(const ROMol &in_query, const Bits &bits, ROMol query(in_query); MatchVectType matchVect; for (unsigned int idx = start; idx < end; idx += numThreads) { - if (!bits.check(idx)) continue; + if (!bits.check(idx)) { + continue; + } // need shared_ptr as it (may) controls the lifespan of the // returned molecule! const boost::shared_ptr &m = mols.getMol(idx); @@ -177,13 +186,16 @@ std::vector internalGetMatches( int maxResults = 1000) { PRECONDITION(startIdx < mols.size(), "startIdx out of bounds"); PRECONDITION(endIdx > startIdx, "endIdx > startIdx"); - if (numThreads == -1) + if (numThreads == -1) { numThreads = (int)getNumThreadsToUse(numThreads); - else + } else { numThreads = std::min(numThreads, (int)getNumThreadsToUse(numThreads)); + } endIdx = std::min(mols.size(), endIdx); - if (endIdx < static_cast(numThreads)) numThreads = endIdx; + if (endIdx < static_cast(numThreads)) { + numThreads = endIdx; + } std::vector> thread_group; std::atomic counter(0); @@ -214,8 +226,9 @@ std::vector internalGetMatches( } // this is so we don't really have to do locking on the atomic counter... - if (maxResults != -1 && rdcast(results.size()) > maxResults) + if (maxResults != -1 && rdcast(results.size()) > maxResults) { results.resize(maxResults); + } return results; } @@ -230,12 +243,15 @@ int internalMatchCounter(const ROMol &query, MolHolderBase &mols, endIdx = std::min(mols.size(), endIdx); - if (numThreads == -1) + if (numThreads == -1) { numThreads = (int)getNumThreadsToUse(numThreads); - else + } else { numThreads = std::min(numThreads, (int)getNumThreadsToUse(numThreads)); + } - if (endIdx < static_cast(numThreads)) numThreads = endIdx; + if (endIdx < static_cast(numThreads)) { + numThreads = endIdx; + } std::vector> thread_group; std::atomic counter(0); diff --git a/Code/GraphMol/SubstructLibrary/substructLibraryTest.cpp b/Code/GraphMol/SubstructLibrary/substructLibraryTest.cpp index 54dd6ca8e..11d710120 100644 --- a/Code/GraphMol/SubstructLibrary/substructLibraryTest.cpp +++ b/Code/GraphMol/SubstructLibrary/substructLibraryTest.cpp @@ -101,7 +101,9 @@ void test1() { } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } ssslib.addMol(*mol); delete mol; } @@ -122,11 +124,12 @@ void test1() { int i=0; for(auto lib: libs) { ROMol *query = SmartsToMol("[#6;$([#6]([#6])[!#6])]"); - if (i == 0) + if (i == 0) { hasMatch = runTest(*lib, *query, 1); - else + } else { runTest(*lib, *query, 1, hasMatch); - + } + #ifdef RDK_TEST_MULTITHREADED runTest(*lib, *query, -1, hasMatch); #endif @@ -137,10 +140,11 @@ void test1() { i = 0; for(auto lib: libs) { ROMol *query = SmartsToMol("[$([O,S]-[!$(*=O)])]"); - if (i == 0) + if (i == 0) { hasMatch = runTest(*lib, *query, 1); - else + } else { runTest(*lib, *query, 1, hasMatch); + } #ifdef RDK_TEST_MULTITHREADED runTest(*lib, *query, -1, hasMatch); @@ -172,7 +176,9 @@ void test2() { } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } ssslib.addMol(*mol); delete mol; } diff --git a/Code/GraphMol/Trajectory/Trajectory.cpp b/Code/GraphMol/Trajectory/Trajectory.cpp index cad1a89ae..daebad882 100644 --- a/Code/GraphMol/Trajectory/Trajectory.cpp +++ b/Code/GraphMol/Trajectory/Trajectory.cpp @@ -44,9 +44,13 @@ RDGeom::Point3D Snapshot::getPoint3D(unsigned int pointNum) const { Trajectory::Trajectory(unsigned int dimension, unsigned int numPoints, SnapshotVect *snapshotVect) : d_dimension(dimension), d_numPoints(numPoints) { - if (!snapshotVect) snapshotVect = new SnapshotVect; + if (!snapshotVect) { + snapshotVect = new SnapshotVect; + } d_snapshotVect.reset(snapshotVect); - for (auto &vectIt : *d_snapshotVect) vectIt.d_trajectory = this; + for (auto &vectIt : *d_snapshotVect) { + vectIt.d_trajectory = this; + } } Trajectory::Trajectory(const Trajectory &other) @@ -54,8 +58,9 @@ Trajectory::Trajectory(const Trajectory &other) d_numPoints(other.d_numPoints), d_snapshotVect(new SnapshotVect) { for (SnapshotVect::const_iterator vectIt = other.d_snapshotVect->begin(); - vectIt != other.d_snapshotVect->end(); ++vectIt) + vectIt != other.d_snapshotVect->end(); ++vectIt) { addSnapshot(*vectIt); + } } unsigned int Trajectory::addSnapshot(const Snapshot &s) { @@ -85,15 +90,20 @@ unsigned int Trajectory::addConformersToMol(ROMol &mol, int from, int to) { "Number of atom mismatch between ROMol and Trajectory"); PRECONDITION(from < static_cast(size()), "from must be < size()"); PRECONDITION(to < static_cast(size()), "to must be < size()"); - if (from < 0) from = 0; - if (to < 0) to = size() - 1; + if (from < 0) { + from = 0; + } + if (to < 0) { + to = size() - 1; + } PRECONDITION(!size() || (from <= to), "from must be <= to"); int n; unsigned int nConf; for (n = from, nConf = 0; size() && (n <= to); ++n, ++nConf) { auto *conf = new Conformer(mol.getNumAtoms()); - for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) + for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) { conf->setAtomPos(i, getSnapshot(n).getPoint3D(i)); + } mol.addConformer(conf, true); } return nConf; @@ -155,29 +165,37 @@ unsigned int readGromosTrajectory(const std::string &fName, Trajectory &traj) { const static char *ignoredKeywordArray[] = { "TITLE", "TIMESTEP", "VELOCITYRED", "VELOCITY", "GENBOX", "BOX"}; std::set ignoredKeywordSet; - for (auto &kw : ignoredKeywordArray) + for (auto &kw : ignoredKeywordArray) { ignoredKeywordSet.insert(std::string(kw)); + } while (inStream.good() && !inStream.eof()) { std::getline(inStream, tempStr); - if (inStream.bad() || inStream.eof()) continue; + if (inStream.bad() || inStream.eof()) { + continue; + } if (ignoredKeywordSet.find(tempStr) != ignoredKeywordSet.end()) { // ignored block - while (inStream.good() && !inStream.eof() && (tempStr != "END")) + while (inStream.good() && !inStream.eof() && (tempStr != "END")) { std::getline(inStream, tempStr); + } } else if ((tempStr == "POSITIONRED") || (tempStr == "POSITION")) { // these are the positions boost::shared_array c(new double[nCoords]()); unsigned int j = 0; for (unsigned int i = 0; i < traj.numPoints();) { std::getline(inStream, tempStr); - if (inStream.bad() || inStream.eof() || (tempStr == "END")) + if (inStream.bad() || inStream.eof() || (tempStr == "END")) { throw ValueErrorException("Wrong number of coordinates"); + } // ignore comments - if (tempStr.find("#") != std::string::npos) continue; + if (tempStr.find("#") != std::string::npos) { + continue; + } std::stringstream ls(tempStr); double x, y, z; - if (!(ls >> x >> y >> z)) + if (!(ls >> x >> y >> z)) { throw ValueErrorException("Error while reading file"); + } // store the coordinates (convert to Angstrom!) c[j++] = x * 10.0; c[j++] = y * 10.0; @@ -185,13 +203,16 @@ unsigned int readGromosTrajectory(const std::string &fName, Trajectory &traj) { ++i; } std::getline(inStream, tempStr); // the END line - if (inStream.bad() || inStream.eof() || (tempStr != "END")) + if (inStream.bad() || inStream.eof() || (tempStr != "END")) { throw ValueErrorException("Wrong number of coordinates"); + } traj.addSnapshot(Snapshot(c)); ++nSnapshots; } else { std::string supportedBlocks("POSITIONRED, POSITION"); - for (const auto &it : ignoredKeywordSet) supportedBlocks += ", " + it; + for (const auto &it : ignoredKeywordSet) { + supportedBlocks += ", " + it; + } throw ValueErrorException("Unsupported block: " + tempStr + ". Supported blocks are " + supportedBlocks); } diff --git a/Code/GraphMol/Trajectory/trajectoryTest.cpp b/Code/GraphMol/Trajectory/trajectoryTest.cpp index 5040a4350..04bdd8553 100644 --- a/Code/GraphMol/Trajectory/trajectoryTest.cpp +++ b/Code/GraphMol/Trajectory/trajectoryTest.cpp @@ -61,10 +61,12 @@ void testTrajectory2D() { CHECK_INVARIANT(traj.dimension() == dim, ""); CHECK_INVARIANT(traj.numPoints() == np, ""); boost::shared_array c(new double [np * dim]); - for (unsigned int i = 0; i < np * dim; ++i) + for (unsigned int i = 0; i < np * dim; ++i) { c[i] = static_cast(i); - for (unsigned int i = 0; i < ns; ++i) + } + for (unsigned int i = 0; i < ns; ++i) { traj.addSnapshot(Snapshot(c, static_cast(i))); + } TEST_ASSERT(traj.size() == ns); { bool e = false; @@ -98,12 +100,14 @@ void testTrajectory2D() { } TEST_ASSERT(!e); } - for (unsigned int i = 0; i < ns; ++i) + for (unsigned int i = 0; i < ns; ++i) { TEST_ASSERT(RDKit::feq(RDKit::round(traj.getSnapshot(i).getEnergy()), static_cast(i))); + } traj.removeSnapshot(0); TEST_ASSERT(traj.size() == ns - 1); - for (unsigned int i = 0; i < ns - 1; ++i) + for (unsigned int i = 0; i < ns - 1; ++i) { TEST_ASSERT(RDKit::feq(RDKit::round(traj.getSnapshot(i).getEnergy()), static_cast(i + 1))); + } traj.insertSnapshot(0, Snapshot(c, 999.0)); TEST_ASSERT(traj.size() == ns); Snapshot copySnapshot(traj.getSnapshot(0)); @@ -126,10 +130,12 @@ void testTrajectory3D() { CHECK_INVARIANT(traj.dimension() == dim, ""); CHECK_INVARIANT(traj.numPoints() == np, ""); boost::shared_array c(new double [np * dim]); - for (unsigned int i = 0; i < np * dim; ++i) + for (unsigned int i = 0; i < np * dim; ++i) { c[i] = static_cast(i); - for (unsigned int i = 0; i < ns; ++i) + } + for (unsigned int i = 0; i < ns; ++i) { traj.addSnapshot(Snapshot(c, static_cast(i))); + } TEST_ASSERT(traj.size() == ns); { bool e = false; @@ -166,12 +172,14 @@ void testTrajectory3D() { TEST_ASSERT(e); } } - for (unsigned int i = 0; i < ns; ++i) + for (unsigned int i = 0; i < ns; ++i) { TEST_ASSERT(RDKit::feq(RDKit::round(traj.getSnapshot(i).getEnergy()), static_cast(i))); + } traj.removeSnapshot(0); TEST_ASSERT(traj.size() == ns - 1); - for (unsigned int i = 0; i < ns - 1; ++i) + for (unsigned int i = 0; i < ns - 1; ++i) { TEST_ASSERT(RDKit::feq(RDKit::round(traj.getSnapshot(i).getEnergy()), static_cast(i + 1))); + } traj.insertSnapshot(0, Snapshot(c, 999.0)); TEST_ASSERT(traj.size() == ns); Snapshot copySnapshot(traj.getSnapshot(0)); diff --git a/Code/GraphMol/Wrap/Atom.cpp b/Code/GraphMol/Wrap/Atom.cpp index e59ff8f52..4fb3ab2c5 100644 --- a/Code/GraphMol/Wrap/Atom.cpp +++ b/Code/GraphMol/Wrap/Atom.cpp @@ -121,7 +121,9 @@ AtomMonomerInfo *AtomGetMonomerInfo(Atom *atom) { } AtomPDBResidueInfo *AtomGetPDBResidueInfo(Atom *atom) { AtomMonomerInfo *res = atom->getMonomerInfo(); - if (!res) return nullptr; + if (!res) { + return nullptr; + } if (res->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) { throw_value_error("MonomerInfo is not a PDB Residue"); } diff --git a/Code/GraphMol/Wrap/Conformer.cpp b/Code/GraphMol/Wrap/Conformer.cpp index 10f0f4ac4..b9d4d4b68 100644 --- a/Code/GraphMol/Wrap/Conformer.cpp +++ b/Code/GraphMol/Wrap/Conformer.cpp @@ -39,10 +39,10 @@ PyObject* GetPos(const Conformer *conf) { dims[1] = 3; // initialize the array - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); + auto *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); // represent the array as a 1D/flat array of doubles - double *resData = reinterpret_cast(PyArray_DATA(res)); + auto *resData = reinterpret_cast(PyArray_DATA(res)); // manually insert the data, 3 corresponds to the x, y and z dimensions for (unsigned int i = 0; i < pos.size(); ++i) { diff --git a/Code/GraphMol/Wrap/Mol.cpp b/Code/GraphMol/Wrap/Mol.cpp index 56efdbf40..198faf96f 100644 --- a/Code/GraphMol/Wrap/Mol.cpp +++ b/Code/GraphMol/Wrap/Mol.cpp @@ -197,10 +197,13 @@ class ReadWriteMol : public RWMol { pythonObjectToVect(stereo_groups, groups); for (const auto group : groups) { for (const auto atom : group.getAtoms()) { - if (!atom) throw_value_error("NULL atom in StereoGroup"); - if (&atom->getOwningMol() != this) + if (!atom) { + throw_value_error("NULL atom in StereoGroup"); + } + if (&atom->getOwningMol() != this) { throw_value_error( "atom in StereoGroup does not belong to this molecule."); + } } } setStereoGroups(std::move(groups)); diff --git a/Code/GraphMol/Wrap/MolOps.cpp b/Code/GraphMol/Wrap/MolOps.cpp index 907fa5c3f..5348da160 100644 --- a/Code/GraphMol/Wrap/MolOps.cpp +++ b/Code/GraphMol/Wrap/MolOps.cpp @@ -59,7 +59,9 @@ python::tuple fragmentOnSomeBondsHelper(const ROMol &mol, bool returnCutsPerAtom) { std::unique_ptr> bondIndices = pythonObjectToVect(pyBondIndices, mol.getNumBonds()); - if (!bondIndices.get()) throw_value_error("empty bond indices"); + if (!bondIndices.get()) { + throw_value_error("empty bond indices"); + } std::vector> *dummyLabels = nullptr; if (pyDummyLabels) { @@ -132,7 +134,9 @@ ROMol *fragmentOnBondsHelper(const ROMol &mol, python::object pyBondIndices, python::list pyCutsPerAtom) { std::unique_ptr> bondIndices = pythonObjectToVect(pyBondIndices, mol.getNumBonds()); - if (!bondIndices.get()) throw_value_error("empty bond indices"); + if (!bondIndices.get()) { + throw_value_error("empty bond indices"); + } std::vector> *dummyLabels = nullptr; if (pyDummyLabels) { unsigned int nVs = @@ -195,15 +199,17 @@ ROMol *renumberAtomsHelper(const ROMol &mol, python::object &pyNewOrder) { namespace { std::string getResidue(const ROMol &m, const Atom *at) { RDUNUSED_PARAM(m); - if (at->getMonomerInfo()->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) + if (at->getMonomerInfo()->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) { return ""; + } return static_cast(at->getMonomerInfo()) ->getResidueName(); } std::string getChainId(const ROMol &m, const Atom *at) { RDUNUSED_PARAM(m); - if (at->getMonomerInfo()->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) + if (at->getMonomerInfo()->getMonomerType() != AtomMonomerInfo::PDBRESIDUE) { return ""; + } return static_cast(at->getMonomerInfo()) ->getChainId(); } @@ -354,7 +360,7 @@ void addRecursiveQuery(ROMol &mol, const ROMol &query, unsigned int atomIdx, MolOps::SanitizeFlags sanitizeMol(ROMol &mol, boost::uint64_t sanitizeOps, bool catchErrors) { - RWMol &wmol = static_cast(mol); + auto &wmol = static_cast(mol); unsigned int operationThatFailed; if (catchErrors) { try { @@ -372,42 +378,42 @@ MolOps::SanitizeFlags sanitizeMol(ROMol &mol, boost::uint64_t sanitizeOps, } RWMol *getEditable(const ROMol &mol) { - RWMol *res = new RWMol(mol, false); + auto *res = new RWMol(mol, false); return res; } ROMol *getNormal(const RWMol &mol) { - ROMol *res = static_cast(new RWMol(mol)); + auto *res = static_cast(new RWMol(mol)); return res; } void kekulizeMol(ROMol &mol, bool clearAromaticFlags = false) { - RWMol &wmol = static_cast(mol); + auto &wmol = static_cast(mol); MolOps::Kekulize(wmol, clearAromaticFlags); } void cleanupMol(ROMol &mol) { - RWMol &rwmol = static_cast(mol); + auto &rwmol = static_cast(mol); MolOps::cleanUp(rwmol); } void setAromaticityMol(ROMol &mol, MolOps::AromaticityModel model) { - RWMol &wmol = static_cast(mol); + auto &wmol = static_cast(mol); MolOps::setAromaticity(wmol, model); } void setConjugationMol(ROMol &mol) { - RWMol &wmol = static_cast(mol); + auto &wmol = static_cast(mol); MolOps::setConjugation(wmol); } void assignRadicalsMol(ROMol &mol) { - RWMol &wmol = static_cast(mol); + auto &wmol = static_cast(mol); MolOps::assignRadicals(wmol); } void setHybridizationMol(ROMol &mol) { - RWMol &wmol = static_cast(mol); + auto &wmol = static_cast(mol); MolOps::setHybridization(wmol); } @@ -427,7 +433,7 @@ PyObject *getDistanceMatrix(ROMol &mol, bool useBO = false, distMat = MolOps::getDistanceMat(mol, useBO, useAtomWts, force, prefix); - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); + auto *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); memcpy(PyArray_DATA(res), static_cast(distMat), nats * nats * sizeof(double)); @@ -445,7 +451,7 @@ PyObject *get3DDistanceMatrix(ROMol &mol, int confId = -1, distMat = MolOps::get3DDistanceMat(mol, confId, useAtomWts, force, prefix); - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); + auto *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); memcpy(PyArray_DATA(res), static_cast(distMat), nats * nats * sizeof(double)); @@ -494,10 +500,10 @@ python::tuple GetMolFragsWithMapping( VECT_INT_VECT fragsVec; MolOps::getMolFrags(mol, fragsVec); - for (unsigned int i = 0; i < fragsVec.size(); ++i) { + for (auto &i : fragsVec) { python::list tpl; - for (unsigned int j = 0; j < fragsVec[i].size(); ++j) { - tpl.append(fragsVec[i][j]); + for (unsigned int j = 0; j < i.size(); ++j) { + tpl.append(i[j]); } res.append(python::tuple(tpl)); } @@ -505,30 +511,34 @@ python::tuple GetMolFragsWithMapping( std::vector> fragsMolAtomMappingVec; std::vector fragsVec; std::vector> molFrags; - python::list &fragsList = reinterpret_cast(frags); - python::list &fragsMolAtomMappingList = + auto &fragsList = reinterpret_cast(frags); + auto &fragsMolAtomMappingList = reinterpret_cast(fragsMolAtomMapping); bool hasFrags = fragsList != python::object(); bool hasFragsMolAtomMapping = fragsMolAtomMappingList != python::object(); molFrags = hasFrags || hasFragsMolAtomMapping ? MolOps::getMolFrags( - mol, sanitizeFrags, hasFrags ? &fragsVec : NULL, - hasFragsMolAtomMapping ? &fragsMolAtomMappingVec : NULL) + mol, sanitizeFrags, hasFrags ? &fragsVec : nullptr, + hasFragsMolAtomMapping ? &fragsMolAtomMappingVec : nullptr) : MolOps::getMolFrags(mol, sanitizeFrags); if (hasFrags) { - for (unsigned int i = 0; i < fragsVec.size(); ++i) - fragsList.append(fragsVec[i]); + for (int i : fragsVec) { + fragsList.append(i); + } } if (hasFragsMolAtomMapping) { - for (unsigned int i = 0; i < fragsMolAtomMappingVec.size(); ++i) { + for (auto &i : fragsMolAtomMappingVec) { python::list perFragMolAtomMappingTpl; - for (unsigned int j = 0; j < fragsMolAtomMappingVec[i].size(); ++j) - perFragMolAtomMappingTpl.append(fragsMolAtomMappingVec[i][j]); + for (unsigned int j = 0; j < i.size(); ++j) { + perFragMolAtomMappingTpl.append(i[j]); + } fragsMolAtomMappingList.append(python::tuple(perFragMolAtomMappingTpl)); } } - for (unsigned int i = 0; i < molFrags.size(); ++i) res.append(molFrags[i]); + for (const auto &molFrag : molFrags) { + res.append(molFrag); + } } return python::tuple(res); } @@ -628,7 +638,7 @@ ExplicitBitVect *wrapRDKFingerprintMol( lFromAtoms.get(), lAtomBits, lBitInfo); if (lAtomBits) { - python::list &pyl = static_cast(atomBits); + auto &pyl = static_cast(atomBits); for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) { python::list tmp; BOOST_FOREACH (std::uint32_t v, (*lAtomBits)[i]) { tmp.append(v); } @@ -637,7 +647,7 @@ ExplicitBitVect *wrapRDKFingerprintMol( delete lAtomBits; } if (lBitInfo) { - python::dict &pyd = static_cast(bitInfo); + auto &pyd = static_cast(bitInfo); for (auto &it : (*lBitInfo)) { python::list temp; std::vector>::iterator itset; @@ -684,7 +694,7 @@ SparseIntVect *wrapUnfoldedRDKFingerprintMol( lAtomInvariants.get(), lFromAtoms.get(), lAtomBits, lBitInfo); if (lAtomBits) { - python::list &pyl = static_cast(atomBits); + auto &pyl = static_cast(atomBits); for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) { python::list tmp; BOOST_FOREACH (boost::uint64_t v, (*lAtomBits)[i]) { tmp.append(v); } @@ -693,7 +703,7 @@ SparseIntVect *wrapUnfoldedRDKFingerprintMol( delete lAtomBits; } if (lBitInfo) { - python::dict &pyd = static_cast(bitInfo); + auto &pyd = static_cast(bitInfo); for (auto &it : (*lBitInfo)) { python::list temp; std::vector>::iterator itset; diff --git a/Code/GraphMol/Wrap/Queries.cpp b/Code/GraphMol/Wrap/Queries.cpp index 48cb10e3a..ef937ae3f 100644 --- a/Code/GraphMol/Wrap/Queries.cpp +++ b/Code/GraphMol/Wrap/Queries.cpp @@ -86,14 +86,18 @@ QAFUNC2(MissingChiralTagQueryAtom, makeAtomMissingChiralTagQuery, int); QueryAtom *HasPropQueryAtom(const std::string &propname, bool negate) { auto *res = new QueryAtom(); res->setQuery(makeHasPropQuery(propname)); - if (negate) res->getQuery()->setNegation(true); + if (negate) { + res->getQuery()->setNegation(true); + } return res; } QueryBond *HasPropQueryBond(const std::string &propname, bool negate) { auto *res = new QueryBond(); res->setQuery(makeHasPropQuery(propname)); - if (negate) res->getQuery()->setNegation(true); + if (negate) { + res->getQuery()->setNegation(true); + } return res; } @@ -101,7 +105,9 @@ template Ret *PropQuery(const std::string &propname, const T &v, bool negate) { auto *res = new Ret(); res->setQuery(makePropQuery(propname, v)); - if (negate) res->getQuery()->setNegation(true); + if (negate) { + res->getQuery()->setNegation(true); + } return res; } @@ -110,7 +116,9 @@ Ret *PropQueryWithTol(const std::string &propname, const T &v, bool negate, const T &tol = T()) { auto *res = new Ret(); res->setQuery(makePropQuery(propname, v, tol)); - if (negate) res->getQuery()->setNegation(true); + if (negate) { + res->getQuery()->setNegation(true); + } return res; } @@ -119,7 +127,9 @@ Ret *PropQueryWithTol(const std::string &propname, const ExplicitBitVect &v, bool negate, float tol = 0.0) { auto *res = new Ret(); res->setQuery(makePropQuery(propname, v, tol)); - if (negate) res->getQuery()->setNegation(true); + if (negate) { + res->getQuery()->setNegation(true); + } return res; } diff --git a/Code/GraphMol/Wrap/RingInfo.cpp b/Code/GraphMol/Wrap/RingInfo.cpp index b4e393b18..d3b4ad784 100644 --- a/Code/GraphMol/Wrap/RingInfo.cpp +++ b/Code/GraphMol/Wrap/RingInfo.cpp @@ -54,8 +54,12 @@ python::object bondRingFamilies(const RingInfo *self) { void addRing(RingInfo *self,python::object atomRing, python::object bondRing){ unsigned int nAts = python::extract(atomRing.attr("__len__")()); unsigned int nBnds = python::extract(bondRing.attr("__len__")()); - if(nAts != nBnds) throw_value_error("list sizes must match"); - if(!self->isInitialized()) self->initialize(); + if (nAts != nBnds) { + throw_value_error("list sizes must match"); + } + if (!self->isInitialized()) { + self->initialize(); + } INT_VECT aring(nAts); INT_VECT bring(nAts); for (unsigned int i = 0; i < nAts; ++i) { diff --git a/Code/GraphMol/Wrap/StereoGroup.cpp b/Code/GraphMol/Wrap/StereoGroup.cpp index d37a8f2c5..f352eca7f 100644 --- a/Code/GraphMol/Wrap/StereoGroup.cpp +++ b/Code/GraphMol/Wrap/StereoGroup.cpp @@ -33,12 +33,13 @@ StereoGroup *createStereoGroup(StereoGroupType typ, ROMol &mol, python::stl_input_iterator beg(atomIds), end; while (beg != end) { unsigned int v = *beg; - if (v >= mol.getNumAtoms()) + if (v >= mol.getNumAtoms()) { throw_value_error("atom index exceeds mol.GetNumAtoms()"); + } cppAtoms.push_back(mol.getAtomWithIdx(v)); ++beg; } - StereoGroup *sg = new StereoGroup(typ, cppAtoms); + auto *sg = new StereoGroup(typ, cppAtoms); return sg; } diff --git a/Code/GraphMol/Wrap/SubstanceGroup.cpp b/Code/GraphMol/Wrap/SubstanceGroup.cpp index 0564f338e..0f051e9f1 100644 --- a/Code/GraphMol/Wrap/SubstanceGroup.cpp +++ b/Code/GraphMol/Wrap/SubstanceGroup.cpp @@ -47,8 +47,9 @@ SubstanceGroup *createMolSubstanceGroup(ROMol &mol, std::string type) { void addBracketHelper(SubstanceGroup &self, python::object pts) { unsigned int sz = python::extract(pts.attr("__len__")()); - if (sz != 2 && sz != 3) + if (sz != 2 && sz != 3) { throw_value_error("pts object have a length of 2 or 3"); + } SubstanceGroup::Bracket bkt; python::stl_input_iterator beg(pts); @@ -74,7 +75,7 @@ struct sgroup_wrap { boost::python::type_id>(); const boost::python::converter::registration *reg = boost::python::converter::registry::query(info); - if (reg == NULL || (*reg).m_to_python == NULL) { + if (reg == nullptr || (*reg).m_to_python == nullptr) { python::class_>("SubstanceGroup_VECT") .def(python::vector_indexing_suite< std::vector>()); diff --git a/Code/GraphMol/Wrap/Trajectory.cpp b/Code/GraphMol/Wrap/Trajectory.cpp index 2a0e00f97..aa010ef68 100644 --- a/Code/GraphMol/Wrap/Trajectory.cpp +++ b/Code/GraphMol/Wrap/Trajectory.cpp @@ -25,10 +25,12 @@ Snapshot *getSnapshot_wrap(Trajectory *traj, unsigned int snapshotNum) { Snapshot *constructSnapshot_wrap(python::list &coordList, double energy) { unsigned int l = python::len(coordList); boost::shared_array c; - if (l) + if (l) { c.reset(new double[l]); - for (unsigned int i = 0; i < l; ++i) + } + for (unsigned int i = 0; i < l; ++i) { c[i] = python::extract(coordList[i]); + } return new Snapshot(c, energy); } diff --git a/Code/GraphMol/Wrap/rdchem.cpp b/Code/GraphMol/Wrap/rdchem.cpp index 570a7202f..6c3debe49 100644 --- a/Code/GraphMol/Wrap/rdchem.cpp +++ b/Code/GraphMol/Wrap/rdchem.cpp @@ -104,10 +104,18 @@ void WrapLogs() { if (!rdDebugLog || !rdInfoLog || !rdErrorLog || !rdWarningLog) { RDLog::InitLogs(); } - if (rdDebugLog != nullptr) rdDebugLog->SetTee(debug); - if (rdInfoLog != nullptr) rdInfoLog->SetTee(info); - if (rdErrorLog != nullptr) rdErrorLog->SetTee(error); - if (rdWarningLog != nullptr) rdWarningLog->SetTee(warning); + if (rdDebugLog != nullptr) { + rdDebugLog->SetTee(debug); + } + if (rdInfoLog != nullptr) { + rdInfoLog->SetTee(info); + } + if (rdErrorLog != nullptr) { + rdErrorLog->SetTee(error); + } + if (rdWarningLog != nullptr) { + rdWarningLog->SetTee(warning); + } } python::tuple getAtomIndicesHelper(const KekulizeException &self) { @@ -143,8 +151,10 @@ PyObject *createExceptionClass(const char *name, std::string qualifiedName0 = scopeName + "." + name; char *qualifiedName1 = const_cast(qualifiedName0.c_str()); - PyObject *typeObj = PyErr_NewException(qualifiedName1, baseTypeObj, 0); - if (!typeObj) python::throw_error_already_set(); + PyObject *typeObj = PyErr_NewException(qualifiedName1, baseTypeObj, nullptr); + if (!typeObj) { + python::throw_error_already_set(); + } python::scope().attr(name) = python::handle<>(python::borrowed(typeObj)); return typeObj; } diff --git a/Code/GraphMol/Wrap/rdmolfiles.cpp b/Code/GraphMol/Wrap/rdmolfiles.cpp index 24fdcf1fb..6074faa69 100644 --- a/Code/GraphMol/Wrap/rdmolfiles.cpp +++ b/Code/GraphMol/Wrap/rdmolfiles.cpp @@ -50,7 +50,9 @@ void rdFileParseExceptionTranslator(RDKit::FileParseException const &x) { namespace RDKit { std::string pyObjectToString(python::object input) { python::extract ex(input); - if (ex.check()) return ex(); + if (ex.check()) { + return ex(); + } std::wstring ws = python::extract(input); return std::string(ws.begin(), ws.end()); } @@ -343,11 +345,14 @@ std::vector CanonicalRankAtomsInFragment( } boost::dynamic_bitset<> atoms(mol.getNumAtoms()); - for (size_t i = 0; i < avect->size(); ++i) atoms[(*avect)[i]] = true; + for (size_t i = 0; i < avect->size(); ++i) { + atoms[(*avect)[i]] = true; + } boost::dynamic_bitset<> bonds(mol.getNumBonds()); - for (size_t i = 0; bvect.get() && i < bvect->size(); ++i) + for (size_t i = 0; bvect.get() && i < bvect->size(); ++i) { bonds[(*bvect)[i]] = true; + } std::vector ranks(mol.getNumAtoms()); Canon::rankFragmentAtoms(mol, ranks, atoms, bonds, asymbols.get(), breakTies, diff --git a/Code/GraphMol/cptest.cpp b/Code/GraphMol/cptest.cpp index 1896fa0d7..e4c297559 100644 --- a/Code/GraphMol/cptest.cpp +++ b/Code/GraphMol/cptest.cpp @@ -58,7 +58,7 @@ void testQueryCopying() { std::string smi = "[$([O,S;H1;v2]-[!$(*=[O,N,P,S])]),$([O,S;H0;v2]),$([O,S;-]),$([N;v3;!$" "(N-*=!@[O,N,P,S])]),$([nH0,o,s;+0])]"; - ROMol *m = static_cast(SmartsToMol(smi)); + auto *m = static_cast(SmartsToMol(smi)); TEST_ASSERT(m); std::cerr << "\n\n\nCOPY" << std::endl; auto *m2 = new ROMol(*m, true); @@ -76,7 +76,7 @@ void testConformerCopying() { { std::string smi = "CCC"; - ROMol *m = static_cast(SmilesToMol(smi)); + auto *m = static_cast(SmilesToMol(smi)); TEST_ASSERT(m); auto *conf = new Conformer(m->getNumAtoms()); diff --git a/Code/GraphMol/hanoitest.cpp b/Code/GraphMol/hanoitest.cpp index 6939abc93..522a72d60 100644 --- a/Code/GraphMol/hanoitest.cpp +++ b/Code/GraphMol/hanoitest.cpp @@ -52,12 +52,13 @@ class int_compare_ftor { PRECONDITION(dp_ints, "no ints"); unsigned int ivi = dp_ints[i]; unsigned int ivj = dp_ints[j]; - if (ivi < ivj) + if (ivi < ivj) { return -1; - else if (ivi > ivj) + } else if (ivi > ivj) { return 1; - else + } else { return 0; + } } }; @@ -79,7 +80,9 @@ void hs1(const std::vector> &vects) { const int *data = &vect.front(); int_compare_ftor icmp(data); int *indices = (int *)malloc(vect.size() * sizeof(int)); - for (unsigned int j = 0; j < vect.size(); ++j) indices[j] = j; + for (unsigned int j = 0; j < vect.size(); ++j) { + indices[j] = j; + } int *count = (int *)malloc(vect.size() * sizeof(int)); int *changed = (int *)malloc(vect.size() * sizeof(int)); memset(changed, 1, vect.size() * sizeof(int)); @@ -139,17 +142,19 @@ class atomcomparefunctor { // always start with the current class: ivi = d_atoms[i].index; ivj = d_atoms[j].index; - if (ivi < ivj) + if (ivi < ivj) { return -1; - else if (ivi > ivj) + } else if (ivi > ivj) { return 1; + } ivi = d_atoms[i].atom->getAtomicNum(); ivj = d_atoms[j].atom->getAtomicNum(); - if (ivi < ivj) + if (ivi < ivj) { return -1; - else if (ivi > ivj) + } else if (ivi > ivj) { return 1; + } return 0; } @@ -167,26 +172,29 @@ class atomcomparefunctor2 { // always start with the current class: ivi = d_atoms[i].index; ivj = d_atoms[j].index; - if (ivi < ivj) + if (ivi < ivj) { return -1; - else if (ivi > ivj) + } else if (ivi > ivj) { return 1; + } // start by comparing degree ivi = d_atoms[i].atom->getDegree(); ivj = d_atoms[j].atom->getDegree(); - if (ivi < ivj) + if (ivi < ivj) { return -1; - else if (ivi > ivj) + } else if (ivi > ivj) { return 1; + } // move onto atomic number ivi = d_atoms[i].atom->getAtomicNum(); ivj = d_atoms[j].atom->getAtomicNum(); - if (ivi < ivj) + if (ivi < ivj) { return -1; - else if (ivi > ivj) + } else if (ivi > ivj) { return 1; + } return 0; } @@ -383,26 +391,29 @@ class atomcomparefunctor3 { // always start with the current class: ivi = dp_atoms[i].index; ivj = dp_atoms[j].index; - if (ivi < ivj) + if (ivi < ivj) { return -1; - else if (ivi > ivj) + } else if (ivi > ivj) { return 1; + } // start by comparing degree ivi = dp_atoms[i].atom->getDegree(); ivj = dp_atoms[j].atom->getDegree(); - if (ivi < ivj) + if (ivi < ivj) { return -1; - else if (ivi > ivj) + } else if (ivi > ivj) { return 1; + } // move onto atomic number ivi = dp_atoms[i].atom->getAtomicNum(); ivj = dp_atoms[j].atom->getAtomicNum(); - if (ivi < ivj) + if (ivi < ivj) { return -1; - else if (ivi > ivj) + } else if (ivi > ivj) { return 1; + } return 0; } @@ -417,17 +428,20 @@ class atomcomparefunctor3 { PRECONDITION(dp_atoms, "no atoms"); PRECONDITION(dp_mol, "no molecule"); int v = basecomp(i, j); - if (v) return v; + if (v) { + return v; + } unsigned int ivi, ivj; if (df_useNbrs) { ivi = dp_atoms[i].index + 1 + getAtomNeighborhood(i); ivj = dp_atoms[j].index + 1 + getAtomNeighborhood(j); // std::cerr<<" "< ivj) + } else if (ivi > ivj) { return 1; + } } return 0; } @@ -883,7 +897,9 @@ void _renumberTest(const ROMol *m, std::string inSmiles, // std::cerr<<">>>>>>>>>>>>>>>>>>>>>>>>>>>"< idxV(m->getNumAtoms()); - for (unsigned int i = 0; i < m->getNumAtoms(); ++i) idxV[i] = i; + for (unsigned int i = 0; i < m->getNumAtoms(); ++i) { + idxV[i] = i; + } std::srand(0xF00D); for (unsigned int i = 0; i < numRenumbers; ++i) { @@ -920,7 +936,9 @@ void _renumberTest2(const ROMol *m, std::string inSmiles, unsigned int nAtoms = m->getNumAtoms(); std::vector idxV(m->getNumAtoms()); - for (unsigned int i = 0; i < m->getNumAtoms(); ++i) idxV[i] = i; + for (unsigned int i = 0; i < m->getNumAtoms(); ++i) { + idxV[i] = i; + } std::srand(0xF00D); for (unsigned int i = 0; i < numRenumbers; ++i) { @@ -1223,7 +1241,9 @@ void test8() { m = SmilesToMol(smi1); TEST_ASSERT(m); std::string smi2 = MolToSmiles(*m, true); - if (smi1 != smi2) std::cerr << smi1 << "\n" << smi2 << std::endl; + if (smi1 != smi2) { + std::cerr << smi1 << "\n" << smi2 << std::endl; + } TEST_ASSERT(smi1 == smi2); delete m; } diff --git a/Code/GraphMol/molopstest.cpp b/Code/GraphMol/molopstest.cpp index 151764e9b..da7a7bd5f 100644 --- a/Code/GraphMol/molopstest.cpp +++ b/Code/GraphMol/molopstest.cpp @@ -1486,10 +1486,11 @@ void testIssue183() { bondIt++) { if ((*bondIt)->getBondType() == Bond::DOUBLE) { nDbl++; - if ((*bondIt)->getStereo() == Bond::STEREOE) + if ((*bondIt)->getStereo() == Bond::STEREOE) { nEs++; - else if ((*bondIt)->getStereo() == Bond::STEREOZ) + } else if ((*bondIt)->getStereo() == Bond::STEREOZ) { nZs++; + } } } // BOOST_LOG(rdInfoLog) << ">> " << nDbl << " " << nEs << " " << nZs << @@ -4673,7 +4674,9 @@ namespace { void _renumberTest(const ROMol *m) { PRECONDITION(m, "no molecule"); std::vector idxV(m->getNumAtoms()); - for (unsigned int i = 0; i < m->getNumAtoms(); ++i) idxV[i] = i; + for (unsigned int i = 0; i < m->getNumAtoms(); ++i) { + idxV[i] = i; + } std::string refSmi = MolToSmiles(*m, true); for (unsigned int i = 0; i < m->getNumAtoms(); ++i) { @@ -4713,7 +4716,9 @@ void _renumberTest(const ROMol *m) { } std::string nSmi = MolToSmiles(*nm, true); - if (nSmi != refSmi) std::cerr << refSmi << std::endl << nSmi << std::endl; + if (nSmi != refSmi) { + std::cerr << refSmi << std::endl << nSmi << std::endl; + } TEST_ASSERT(nSmi == refSmi); delete nm; } @@ -4757,7 +4762,7 @@ void testRenumberAtoms() { } { // github issue 1735 renumber empty molecules - ROMol *m = new ROMol; + auto *m = new ROMol; TEST_ASSERT(m); std::vector nVect; auto *m1 = MolOps::renumberAtoms(*m, nVect); @@ -5289,8 +5294,9 @@ void testGithubIssue539() { RWMol *m = SmilesToMol(smiles); TEST_ASSERT(m); bool allConjugated = true; - for (unsigned int i = 0; allConjugated && i < m->getNumBonds(); ++i) + for (unsigned int i = 0; allConjugated && i < m->getNumBonds(); ++i) { allConjugated = m->getBondWithIdx(i)->getIsConjugated(); + } TEST_ASSERT(allConjugated); delete m; } @@ -5305,12 +5311,14 @@ void testGithubIssue539() { RWMol *m = SmilesToMol(*smiles); TEST_ASSERT(m); bool allConjugated = true; - for (unsigned int i = 0; allConjugated && i < m->getNumBonds(); ++i) + for (unsigned int i = 0; allConjugated && i < m->getNumBonds(); ++i) { allConjugated = m->getBondWithIdx(i)->getIsConjugated(); + } TEST_ASSERT(allConjugated); bool allAromatic = true; - for (unsigned int i = 0; allAromatic && i < m->getNumBonds(); ++i) + for (unsigned int i = 0; allAromatic && i < m->getNumBonds(); ++i) { allAromatic = m->getBondWithIdx(i)->getIsAromatic(); + } TEST_ASSERT(allAromatic); delete m; } diff --git a/Code/GraphMol/new_canon.cpp b/Code/GraphMol/new_canon.cpp index e8cc006e3..c1c354e86 100644 --- a/Code/GraphMol/new_canon.cpp +++ b/Code/GraphMol/new_canon.cpp @@ -41,7 +41,9 @@ void ActivatePartitions(unsigned int nAtoms, int *order, int *count, PRECONDITION(changed, "bad pointer"); unsigned int i, j; activeset = -1; - for (i = 0; i < nAtoms; i++) next[i] = -2; + for (i = 0; i < nAtoms; i++) { + next[i] = -2; + } i = 0; do { @@ -50,8 +52,9 @@ void ActivatePartitions(unsigned int nAtoms, int *order, int *count, next[j] = activeset; activeset = j; i += count[j]; - } else + } else { i++; + } } while (i < nAtoms); for (i = 0; i < nAtoms; i++) { @@ -490,8 +493,9 @@ void initFragmentCanonAtoms(const ROMol &mol, ++bI) { if (!bondsInPlay[(*bI)->getIdx()] || !atomsInPlay[(*bI)->getBeginAtomIdx()] || - !atomsInPlay[(*bI)->getEndAtomIdx()]) + !atomsInPlay[(*bI)->getEndAtomIdx()]) { continue; + } Canon::canon_atom &begAt = atoms[(*bI)->getBeginAtomIdx()]; Canon::canon_atom &endAt = atoms[(*bI)->getEndAtomIdx()]; begAt.nbrIds[begAt.degree] = (*bI)->getEndAtomIdx(); @@ -506,7 +510,9 @@ void initFragmentCanonAtoms(const ROMol &mol, // and now we can do the last bit for each atom for (size_t i = 0; i < mol.getNumAtoms(); ++i) { - if (!atomsInPlay[i]) continue; + if (!atomsInPlay[i]) { + continue; + } // this is the fix for github #1567: we let the atom's degree // in the original molecule influence its degree in the fragment atoms[i].totalNumHs += @@ -590,7 +596,9 @@ void rankMolAtoms(const ROMol &mol, std::vector &res, bool breakTies, bool includeChirality, bool includeIsotopes) { res.resize(mol.getNumAtoms()); - if (!mol.getNumAtoms()) return; + if (!mol.getNumAtoms()) { + return; + } std::vector atoms(mol.getNumAtoms()); initCanonAtoms(mol, atoms, includeChirality); @@ -623,7 +631,9 @@ void rankFragmentAtoms(const ROMol &mol, std::vector &res, res.resize(mol.getNumAtoms()); - if (!mol.getNumAtoms()) return; + if (!mol.getNumAtoms()) { + return; + } std::vector atoms(mol.getNumAtoms()); initFragmentCanonAtoms(mol, atoms, includeChirality, atomSymbols, atomsInPlay, @@ -648,7 +658,9 @@ void rankFragmentAtoms(const ROMol &mol, std::vector &res, void chiralRankMolAtoms(const ROMol &mol, std::vector &res) { res.resize(mol.getNumAtoms()); - if (!mol.getNumAtoms()) return; + if (!mol.getNumAtoms()) { + return; + } std::vector atoms(mol.getNumAtoms()); initChiralCanonAtoms(mol, atoms); diff --git a/Code/GraphMol/resMolSupplierTest.cpp b/Code/GraphMol/resMolSupplierTest.cpp index b8dad2a4e..074f912c2 100644 --- a/Code/GraphMol/resMolSupplierTest.cpp +++ b/Code/GraphMol/resMolSupplierTest.cpp @@ -19,10 +19,11 @@ void addFormalChargeIndices(const ROMol *mol, int fc = (*it)->getFormalCharge(); unsigned int idx = (*it)->getIdx(); if (fc) { - if (fcMap.find(idx) == fcMap.end()) + if (fcMap.find(idx) == fcMap.end()) { fcMap[idx] = fc; - else + } else { fcMap[idx] += fc; + } } } } @@ -30,20 +31,23 @@ void addFormalChargeIndices(const ROMol *mol, int getTotalFormalCharge(const ROMol *mol) { int totalFormalCharge = 0; for (ROMol::ConstAtomIterator it = mol->beginAtoms(); it != mol->endAtoms(); - ++it) + ++it) { totalFormalCharge += (*it)->getFormalCharge(); + } return totalFormalCharge; } void cmpFormalChargeBondOrder(const ROMol *mol1, const ROMol *mol2) { TEST_ASSERT(mol1->getNumAtoms() == mol2->getNumAtoms()); TEST_ASSERT(mol1->getNumBonds() == mol2->getNumBonds()); - for (unsigned int i = 0; i < mol1->getNumAtoms(); ++i) + for (unsigned int i = 0; i < mol1->getNumAtoms(); ++i) { TEST_ASSERT(mol1->getAtomWithIdx(i)->getFormalCharge() == mol2->getAtomWithIdx(i)->getFormalCharge()); - for (unsigned int i = 0; i < mol1->getNumBonds(); ++i) + } + for (unsigned int i = 0; i < mol1->getNumBonds(); ++i) { TEST_ASSERT(mol1->getBondWithIdx(i)->getBondType() == mol2->getBondWithIdx(i)->getBondType()); + } } void testBaseFunctionality() { @@ -340,8 +344,9 @@ void testChargeSeparation2() { bool haveCarbanion = false; for (ROMol::ConstAtomIterator it = resMol->beginAtoms(); it != resMol->endAtoms(); ++it) { - if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) + if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) { haveCarbanion = true; + } } TEST_ASSERT(!haveCarbanion); delete resMol; @@ -351,8 +356,9 @@ void testChargeSeparation2() { bool haveCarbanion = false; for (ROMol::ConstAtomIterator it = resMol->beginAtoms(); it != resMol->endAtoms(); ++it) { - if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) + if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) { haveCarbanion = true; + } } TEST_ASSERT(haveCarbanion); delete resMol; @@ -375,8 +381,9 @@ void testMultipleConjGroups1() { bool haveCarbanion = false; for (ROMol::ConstAtomIterator it = resMol->beginAtoms(); it != resMol->endAtoms(); ++it) { - if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) + if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) { haveCarbanion = true; + } } TEST_ASSERT(!haveCarbanion); delete resMol; @@ -386,8 +393,9 @@ void testMultipleConjGroups1() { bool haveCarbanion = false; for (ROMol::ConstAtomIterator it = resMol->beginAtoms(); it != resMol->endAtoms(); ++it) { - if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) + if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) { haveCarbanion = true; + } } TEST_ASSERT(haveCarbanion); delete resMol; @@ -402,8 +410,9 @@ void testMultipleConjGroups1() { bool haveCarbanion = false; for (ROMol::ConstAtomIterator it = resMol->beginAtoms(); it != resMol->endAtoms(); ++it) { - if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) + if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) { haveCarbanion = true; + } } TEST_ASSERT(!haveCarbanion); delete resMol; @@ -428,10 +437,13 @@ void testMultipleConjGroups2() { bool haveDoubleNeg = false; for (ROMol::ConstAtomIterator it = resMol->beginAtoms(); it != resMol->endAtoms(); ++it) { - if (((*it)->getAtomicNum() == 7) && ((*it)->getFormalCharge() == -2)) + if (((*it)->getAtomicNum() == 7) && ((*it)->getFormalCharge() == -2)) { haveDoubleNeg = true; + } + } + if (!haveFirstDoubleNeg && haveDoubleNeg) { + haveFirstDoubleNeg = true; } - if (!haveFirstDoubleNeg && haveDoubleNeg) haveFirstDoubleNeg = true; TEST_ASSERT(!haveFirstDoubleNeg || (haveFirstDoubleNeg && haveDoubleNeg)); delete resMol; } @@ -453,8 +465,9 @@ void testDimethylMalonate() { bool haveCarbanion = false; for (ROMol::ConstAtomIterator it = resMol->beginAtoms(); it != resMol->endAtoms(); ++it) { - if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) + if (((*it)->getAtomicNum() == 6) && ((*it)->getFormalCharge() == -1)) { haveCarbanion = true; + } } TEST_ASSERT(((i < 2) && !haveCarbanion) || ((i == 2) && haveCarbanion)); delete resMol; @@ -477,8 +490,9 @@ void testMethylAcetate() { bool haveCation = false; for (ROMol::ConstAtomIterator it = resMol->beginAtoms(); it != resMol->endAtoms(); ++it) { - if (((*it)->getAtomicNum() == 8) && ((*it)->getFormalCharge() == 1)) + if (((*it)->getAtomicNum() == 8) && ((*it)->getFormalCharge() == 1)) { haveCation = true; + } } delete resMol; TEST_ASSERT(!haveCation); @@ -493,8 +507,9 @@ void testMethylAcetate() { bool haveCation = false; for (ROMol::ConstAtomIterator it = resMol->beginAtoms(); it != resMol->endAtoms(); ++it) { - if (((*it)->getAtomicNum() == 8) && ((*it)->getFormalCharge() == 1)) + if (((*it)->getAtomicNum() == 8) && ((*it)->getFormalCharge() == 1)) { haveCation = true; + } } TEST_ASSERT(((i == 0) && !haveCation) || ((i == 1) && haveCation)); delete resMol; @@ -584,8 +599,9 @@ void setResidueFormalCharge(RWMol *mol, std::vector &res, int fc) { std::vector matchVect; SubstructMatch(*mol, *(*it), matchVect); for (std::vector::const_iterator it = matchVect.begin(); - it != matchVect.end(); ++it) + it != matchVect.end(); ++it) { mol->getAtomWithIdx((*it).back().second)->setFormalCharge(fc); + } } } @@ -596,18 +612,25 @@ void getBtVectVect(ResonanceMolSupplier *resMolSuppl, std::vector bt; bt.reserve(resMol->getNumBonds()); for (ROMol::BondIterator bi = resMol->beginBonds(); - bi != resMol->endBonds(); ++bi) + bi != resMol->endBonds(); ++bi) { bt.push_back(static_cast((*bi)->getBondTypeAsDouble())); + } btVect2.push_back(bt); delete resMol; } for (unsigned int i = 0; i < btVect2.size(); ++i) { bool same = true; for (unsigned int j = 0; same && (j < btVect2[i].size()); ++j) { - if (!i) continue; - if (same) same = (btVect2[i][j] == btVect2[i - 1][j]); + if (!i) { + continue; + } + if (same) { + same = (btVect2[i][j] == btVect2[i - 1][j]); + } + } + if (i) { + TEST_ASSERT(!same); } - if (i) TEST_ASSERT(!same); } } @@ -631,8 +654,9 @@ void testCrambin() { res.push_back(query); setResidueFormalCharge(crambin, res, 1); for (std::vector::const_iterator it = res.begin(); it != res.end(); - ++it) + ++it) { delete *it; + } res.clear(); // deprotonate COOH query = SmartsToMol("C(=O)[Oh]"); @@ -640,8 +664,9 @@ void testCrambin() { res.push_back(query); setResidueFormalCharge(crambin, res, -1); for (std::vector::const_iterator it = res.begin(); it != res.end(); - ++it) + ++it) { delete *it; + } auto *resMolSupplST = new ResonanceMolSupplier((ROMol &)*crambin); TEST_ASSERT(resMolSupplST); // crambin has 2 Arg (3 resonance structures each); 1 Asp, 1 Glu @@ -687,8 +712,9 @@ void testCrambin() { getBtVectVect(resMolSupplMT, btVect2MT); TEST_ASSERT(btVect2ST.size() == btVect2MT.size()); for (unsigned int i = 0; i < btVect2ST.size(); ++i) { - for (unsigned int j = 0; j < btVect2ST[i].size(); ++j) + for (unsigned int j = 0; j < btVect2ST[i].size(); ++j) { TEST_ASSERT(btVect2ST[i][j] == btVect2MT[i][j]); + } } ResonanceMolSupplier *ptr[2] = {resMolSupplST, resMolSupplMT}; for (auto &i : ptr) { @@ -811,14 +837,15 @@ void testGitHub1166() { auto *smol0 = (*resMolSuppl)[i]; auto *smol1 = (*resMolSuppl)[i + 1]; TEST_ASSERT(smol0->getNumAtoms() == smol1->getNumAtoms()); - for (unsigned int atomIdx = 0; atomIdx < smol0->getNumAtoms(); ++atomIdx) + for (unsigned int atomIdx = 0; atomIdx < smol0->getNumAtoms(); ++atomIdx) { TEST_ASSERT( smol0->getAtomWithIdx(atomIdx)->getFormalCharge() == smol1->getAtomWithIdx(atomIdx)->getFormalCharge()); + } // check that bond orders are alternate on aromatic bonds between // structures on odd indices and structures on even indices TEST_ASSERT(smol0->getNumBonds() == smol1->getNumBonds()); - for (unsigned int bondIdx = 0; bondIdx < smol0->getNumBonds(); ++bondIdx) + for (unsigned int bondIdx = 0; bondIdx < smol0->getNumBonds(); ++bondIdx) { TEST_ASSERT( (!smol0->getBondWithIdx(bondIdx)->getIsAromatic() && !smol1->getBondWithIdx(bondIdx)->getIsAromatic() && @@ -828,6 +855,7 @@ void testGitHub1166() { smol1->getBondWithIdx(bondIdx)->getIsAromatic() && (static_cast(smol0->getBondWithIdx(bondIdx)->getBondTypeAsDouble() + smol1->getBondWithIdx(bondIdx)->getBondTypeAsDouble()) == 3))); + } delete smol0; delete smol1; } diff --git a/Code/GraphMol/test-valgrind.cpp b/Code/GraphMol/test-valgrind.cpp index 717419333..fb224299c 100644 --- a/Code/GraphMol/test-valgrind.cpp +++ b/Code/GraphMol/test-valgrind.cpp @@ -27,8 +27,12 @@ using namespace RDKit; // memory tests for valgrind void testRemoveAtomBond(RWMol &m, int atomidx, int bondidx) { const Bond *b = m.getBondWithIdx(bondidx); - if (bondidx >= 0) m.removeBond(b->getBeginAtomIdx(), b->getEndAtomIdx()); - if (atomidx >= 0) m.removeAtom(atomidx); + if (bondidx >= 0) { + m.removeBond(b->getBeginAtomIdx(), b->getEndAtomIdx()); + } + if (atomidx >= 0) { + m.removeAtom(atomidx); + } } void testRemovals(RWMol m) { diff --git a/Code/GraphMol/test1.cpp b/Code/GraphMol/test1.cpp index eb2881a75..c701af99f 100644 --- a/Code/GraphMol/test1.cpp +++ b/Code/GraphMol/test1.cpp @@ -1154,7 +1154,9 @@ namespace { std::string qhelper(Atom::QUERYATOM_QUERY *q, unsigned int depth = 0) { std::string res = ""; if (q) { - for (unsigned int i = 0; i < depth; ++i) res += " "; + for (unsigned int i = 0; i < depth; ++i) { + res += " "; + } res += q->getFullDescription() + "\n"; for (auto ci = q->beginChildren(); ci != q->endChildren(); ++ci) { res += qhelper((*ci).get(), depth + 1); diff --git a/Code/GraphMol/testChirality.cpp b/Code/GraphMol/testChirality.cpp index 94fecbb21..5ea422f6d 100644 --- a/Code/GraphMol/testChirality.cpp +++ b/Code/GraphMol/testChirality.cpp @@ -1674,7 +1674,9 @@ void testBondDirRemoval() { std::vector colors(m->getNumAtoms()); Canon::MolStack stack; std::vector ranks(oranks.size()); - for (unsigned int i = 0; i < ranks.size(); ++i) ranks[i] = oranks[i]; + for (unsigned int i = 0; i < ranks.size(); ++i) { + ranks[i] = oranks[i]; + } Canon::canonicalizeFragment(*m, 0, colors, ranks, stack); TEST_ASSERT(m->getBondBetweenAtoms(0, 1)->getBondDir() == Bond::NONE); @@ -2668,25 +2670,25 @@ void testAssignStereochemistryFrom3D() { { SDMolSupplier suppl(pathName + "stereochem.sdf", false); // don't sanitize { - RWMol *m = (RWMol *)suppl.next(); + auto *m = (RWMol *)suppl.next(); TEST_ASSERT(m->getProp(common_properties::_Name) == "R-Z"); stereochemTester(m, "R", Bond::STEREOZ); delete m; } { - RWMol *m = (RWMol *)suppl.next(); + auto *m = (RWMol *)suppl.next(); TEST_ASSERT(m->getProp(common_properties::_Name) == "R-E"); stereochemTester(m, "R", Bond::STEREOE); delete m; } { - RWMol *m = (RWMol *)suppl.next(); + auto *m = (RWMol *)suppl.next(); TEST_ASSERT(m->getProp(common_properties::_Name) == "S-Z"); stereochemTester(m, "S", Bond::STEREOZ); delete m; } { - RWMol *m = (RWMol *)suppl.next(); + auto *m = (RWMol *)suppl.next(); TEST_ASSERT(m->getProp(common_properties::_Name) == "S-E"); stereochemTester(m, "S", Bond::STEREOE); delete m; @@ -2821,9 +2823,10 @@ class TestAssignChiralTypesFromMolParity { } } void fillBondDefVect() { - for (auto bi = d_rwMol->beginBonds(); bi != d_rwMol->endBonds(); ++bi) + for (auto bi = d_rwMol->beginBonds(); bi != d_rwMol->endBonds(); ++bi) { d_bondDefVect.emplace_back(BondDef((*bi)->getBeginAtomIdx(), (*bi)->getEndAtomIdx(), (*bi)->getBondType())); + } } void stripBonds() { for (unsigned int i = d_rwMol->getNumBonds(); i--;) { @@ -2832,8 +2835,9 @@ class TestAssignChiralTypesFromMolParity { } } void addBonds() { - for (auto bondDef: d_bondDefVect) + for (auto bondDef : d_bondDefVect) { d_rwMol->addBond(bondDef.beginIdx, bondDef.endIdx, bondDef.type); + } } void checkBondPermutation() { stripBonds(); @@ -2844,8 +2848,9 @@ class TestAssignChiralTypesFromMolParity { } void heapPermutation(size_t s = 0) { // if size becomes 1 the permutation is ready to use - if (s == 0) + if (s == 0) { s = d_bondDefVect.size(); + } if (s == 1) { checkBondPermutation(); return; diff --git a/Code/GraphMol/testPickler.cpp b/Code/GraphMol/testPickler.cpp index c75d3bdfd..3d40804d9 100644 --- a/Code/GraphMol/testPickler.cpp +++ b/Code/GraphMol/testPickler.cpp @@ -61,7 +61,9 @@ void test1(bool doLong = 0) { TEST_ASSERT(smi1 == smi2); delete m; count++; - if (!doLong && count >= 100) break; + if (!doLong && count >= 100) { + break; + } } BOOST_LOG(rdErrorLog) << "\tdone" << std::endl; } @@ -122,7 +124,9 @@ void test2(bool doLong = 0) { TEST_ASSERT(smi1 == smi2); delete m1; count++; - if (!doLong && count >= 100) break; + if (!doLong && count >= 100) { + break; + } } BOOST_LOG(rdErrorLog) << "\tdone" << std::endl; } @@ -156,7 +160,9 @@ void test3(bool doLong = 0) { TEST_ASSERT(smi1 == smi2); delete m1; count++; - if (!doLong && count >= 100) break; + if (!doLong && count >= 100) { + break; + } } BOOST_LOG(rdErrorLog) << "\tdone" << std::endl; } @@ -179,7 +185,9 @@ void timeTest(bool doLong = 0) { ROMol *m1 = suppl.next(); TEST_ASSERT(m1); count++; - if (!doLong && count >= 100) break; + if (!doLong && count >= 100) { + break; + } delete m1; } t2 = std::time(nullptr); @@ -193,7 +201,9 @@ void timeTest(bool doLong = 0) { ROMol m2; MolPickler::molFromPickle(inStream, m2); count--; - if (!doLong && count >= 100) break; + if (!doLong && count >= 100) { + break; + } } t2 = std::time(nullptr); BOOST_LOG(rdInfoLog) << " Pickle time: " << std::difftime(t2, t1) @@ -260,7 +270,7 @@ void testIssue164() { // the issue had to do with number of atoms, so let's make an enormous // molecule and try again: - RWMol *m3 = static_cast(SmilesToMol(smi)); + auto *m3 = static_cast(SmilesToMol(smi)); m3->insertMol(*m1); m3->insertMol(*m1); MolOps::sanitizeMol(*m3); @@ -855,7 +865,9 @@ void testIssue3496759() { while (!inf.eof()) { std::string inl; std::getline(inf, inl); - if (inl[0] == '#' || inl.size() < 2) continue; + if (inl[0] == '#' || inl.size() < 2) { + continue; + } std::vector tokens; boost::split(tokens, inl, boost::is_any_of(" \t")); // std::cerr << "smarts: " << tokens[0] << std::endl; diff --git a/Code/ML/Cluster/Murtagh/hc.c b/Code/ML/Cluster/Murtagh/hc.c index 955b8b965..4b51aded2 100644 --- a/Code/ML/Cluster/Murtagh/hc.c +++ b/Code/ML/Cluster/Murtagh/hc.c @@ -286,8 +286,11 @@ integer *n, *i__, *j; /* Map row I and column J of upper half diagonal symmetric matrix */ /* onto vector. */ /*ret_val = *j + (*i__ - 1) * *n - *i__ * (*i__ + 1) / 2;*/ - if(*j > *i__) ret_val = (*j-1)*(*j-2)/2+*i__; - else ret_val = (*i__-1)*(*i__-2)/2+*j; + if (*j > *i__) { + ret_val = (*j - 1) * (*j - 2) / 2 + *i__; + } else { + ret_val = (*i__ - 1) * (*i__ - 2) / 2 + *j; + } return ret_val; } /* ioffset_ */ diff --git a/Code/ML/Data/cQuantize.cpp b/Code/ML/Data/cQuantize.cpp index 2faab6f71..015b64679 100644 --- a/Code/ML/Data/cQuantize.cpp +++ b/Code/ML/Data/cQuantize.cpp @@ -162,17 +162,20 @@ double RecurseHelper(double *vals, int nVals, long int *cuts, int nCuts, cuts[which] += 1; int top, bot; bot = starts[oldCut]; - if (oldCut + 1 < nStarts) + if (oldCut + 1 < nStarts) { top = starts[oldCut + 1]; - else + } else { top = starts[nStarts - 1]; + } for (i = bot; i < top; i++) { int v = results[i]; varTable[which * nPossibleRes + v] += 1; varTable[(which + 1) * nPossibleRes + v] -= 1; } for (i = which + 1; i < nBounds; i++) { - if (cuts[i] == cuts[i - 1]) cuts[i] += 1; + if (cuts[i] == cuts[i - 1]) { + cuts[i] += 1; + } } } memcpy(cuts, bestCuts, nCuts * sizeof(long int)); @@ -293,15 +296,15 @@ static python::list cQuantize_FindStartPoints(python::object values, return startPts; } - PyArrayObject *contigVals = reinterpret_cast( + auto *contigVals = reinterpret_cast( PyArray_ContiguousFromObject(values.ptr(), NPY_DOUBLE, 1, 1)); if (!contigVals) { throw_value_error("could not convert value argument"); } - double *vals = (double *)PyArray_DATA(contigVals); + auto *vals = (double *)PyArray_DATA(contigVals); - PyArrayObject *contigResults = reinterpret_cast( + auto *contigResults = reinterpret_cast( PyArray_ContiguousFromObject(results.ptr(), NPY_LONG, 1, 1)); if (!contigResults) { throw_value_error("could not convert results argument"); @@ -335,7 +338,9 @@ static python::list cQuantize_FindStartPoints(python::object values, lastDiv = i; } } - if (i < nData) blockAct = res[i]; + if (i < nData) { + blockAct = res[i]; + } ++i; } diff --git a/Code/ML/InfoTheory/InfoBitRanker.cpp b/Code/ML/InfoTheory/InfoBitRanker.cpp index 821e3be0a..4ce35c031 100644 --- a/Code/ML/InfoTheory/InfoBitRanker.cpp +++ b/Code/ML/InfoTheory/InfoBitRanker.cpp @@ -148,12 +148,14 @@ double *InfoBitRanker::getTopN(unsigned int num) { // in addition the infogain function pretends that this is a 2D matrix // with the number of rows equal to nVals and num of columns equal to // d_classes - if (num > d_dims) + if (num > d_dims) { throw ValueErrorException( "attempt to rank more bits than present in the bit vectors"); - if (dp_maskBits) + } + if (dp_maskBits) { CHECK_INVARIANT(num <= dp_maskBits->getNumOnBits(), "Can't rank more bits than the ensemble size"); + } auto *resMat = new RDKit::USHORT[2 * d_classes]; PR_QUEUE topN; @@ -280,7 +282,7 @@ void InfoBitRanker::writeTopBitsToFile(const std::string &fileName) const { throw RDKit::FileParseException(errout.str()); } - std::ostream &outStream = static_cast(tmpStream); + auto &outStream = static_cast(tmpStream); this->writeTopBitsToStream(&outStream); } } diff --git a/Code/ML/InfoTheory/Wrap/BitCorrMatGenerator.cpp b/Code/ML/InfoTheory/Wrap/BitCorrMatGenerator.cpp index 52c75c2b6..e0d130eb6 100644 --- a/Code/ML/InfoTheory/Wrap/BitCorrMatGenerator.cpp +++ b/Code/ML/InfoTheory/Wrap/BitCorrMatGenerator.cpp @@ -26,7 +26,7 @@ PyObject *getCorrMatrix(BitCorrMatGenerator *cmGen) { double *dres = cmGen->getCorrMat(); unsigned int nb = cmGen->getCorrBitList().size(); npy_intp dim = nb * (nb - 1) / 2; - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(1, &dim, NPY_DOUBLE); + auto *res = (PyArrayObject *)PyArray_SimpleNew(1, &dim, NPY_DOUBLE); memcpy(static_cast(PyArray_DATA(res)), static_cast(dres), dim * sizeof(double)); return PyArray_Return(res); diff --git a/Code/ML/InfoTheory/Wrap/InfoBitRanker.cpp b/Code/ML/InfoTheory/Wrap/InfoBitRanker.cpp index 5b80fb41e..d20317ac9 100644 --- a/Code/ML/InfoTheory/Wrap/InfoBitRanker.cpp +++ b/Code/ML/InfoTheory/Wrap/InfoBitRanker.cpp @@ -30,7 +30,7 @@ PyObject *getTopNbits(InfoBitRanker *ranker, npy_intp dims[2]; dims[0] = num; dims[1] = ranker->getNumClasses() + 2; - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); + auto *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); memcpy(static_cast(PyArray_DATA(res)), static_cast(dres), dims[0] * dims[1] * sizeof(double)); return PyArray_Return(res); diff --git a/Code/ML/InfoTheory/Wrap/rdInfoTheory.cpp b/Code/ML/InfoTheory/Wrap/rdInfoTheory.cpp index 5fd9c07cc..e23b32d4e 100644 --- a/Code/ML/InfoTheory/Wrap/rdInfoTheory.cpp +++ b/Code/ML/InfoTheory/Wrap/rdInfoTheory.cpp @@ -27,19 +27,19 @@ double infoEntropy(python::object resArr) { matObj, PyArray_DESCR((PyArrayObject *)matObj)->type_num, 1, 1); double res = 0.0; // we are expecting a 1 dimensional array - long int ncols = (long int)PyArray_DIM((PyArrayObject *)matObj, 0); + auto ncols = (long int)PyArray_DIM((PyArrayObject *)matObj, 0); CHECK_INVARIANT(ncols > 0, ""); if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_DOUBLE) { - double *data = (double *)PyArray_DATA(copy); + auto *data = (double *)PyArray_DATA(copy); res = InfoEntropy(data, ncols); } else if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_FLOAT) { - float *data = (float *)PyArray_DATA(copy); + auto *data = (float *)PyArray_DATA(copy); res = InfoEntropy(data, ncols); } else if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_INT) { int *data = (int *)PyArray_DATA(copy); res = InfoEntropy(data, ncols); } else if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_LONG) { - long int *data = (long int *)PyArray_DATA(copy); + auto *data = (long int *)PyArray_DATA(copy); res = InfoEntropy(data, ncols); } Py_DECREF(copy); @@ -54,20 +54,20 @@ double infoGain(python::object resArr) { PyArrayObject *copy; copy = (PyArrayObject *)PyArray_ContiguousFromObject( matObj, PyArray_DESCR((PyArrayObject *)matObj)->type_num, 2, 2); - long int rows = (long int)PyArray_DIM((PyArrayObject *)matObj, 0); - long int cols = (long int)PyArray_DIM((PyArrayObject *)matObj, 1); + auto rows = (long int)PyArray_DIM((PyArrayObject *)matObj, 0); + auto cols = (long int)PyArray_DIM((PyArrayObject *)matObj, 1); double res = 0.0; if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_DOUBLE) { - double *data = (double *)PyArray_DATA(copy); + auto *data = (double *)PyArray_DATA(copy); res = InfoEntropyGain(data, rows, cols); } else if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_FLOAT) { - float *data = (float *)PyArray_DATA(copy); + auto *data = (float *)PyArray_DATA(copy); res = InfoEntropyGain(data, rows, cols); } else if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_INT) { int *data = (int *)PyArray_DATA(copy); res = InfoEntropyGain(data, rows, cols); } else if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_LONG) { - long int *data = (long int *)PyArray_DATA(copy); + auto *data = (long int *)PyArray_DATA(copy); res = InfoEntropyGain(data, rows, cols); } else { throw_value_error( @@ -85,20 +85,20 @@ double chiSquare(python::object resArr) { PyArrayObject *copy; copy = (PyArrayObject *)PyArray_ContiguousFromObject( matObj, PyArray_DESCR((PyArrayObject *)matObj)->type_num, 2, 2); - long int rows = (long int)PyArray_DIM((PyArrayObject *)matObj, 0); - long int cols = (long int)PyArray_DIM((PyArrayObject *)matObj, 1); + auto rows = (long int)PyArray_DIM((PyArrayObject *)matObj, 0); + auto cols = (long int)PyArray_DIM((PyArrayObject *)matObj, 1); double res = 0.0; if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_DOUBLE) { - double *data = (double *)PyArray_DATA(copy); + auto *data = (double *)PyArray_DATA(copy); res = ChiSquare(data, rows, cols); } else if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_FLOAT) { - float *data = (float *)PyArray_DATA(copy); + auto *data = (float *)PyArray_DATA(copy); res = ChiSquare(data, rows, cols); } else if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_INT) { int *data = (int *)PyArray_DATA(copy); res = ChiSquare(data, rows, cols); } else if (PyArray_DESCR((PyArrayObject *)matObj)->type_num == NPY_LONG) { - long int *data = (long int *)PyArray_DATA(copy); + auto *data = (long int *)PyArray_DATA(copy); res = ChiSquare(data, rows, cols); } else { throw_value_error( diff --git a/Code/Numerics/Alignment/AlignPoints.cpp b/Code/Numerics/Alignment/AlignPoints.cpp index 6c9b0b21b..10269bdf5 100644 --- a/Code/Numerics/Alignment/AlignPoints.cpp +++ b/Code/Numerics/Alignment/AlignPoints.cpp @@ -172,7 +172,9 @@ unsigned int jacobi(double quad[4][4], double eigenVals[4], // initialize the eigen vector to Identity for (j = 0; j <= 3; j++) { - for (i = 0; i <= 3; i++) eigenVecs[i][j] = 0.0; + for (i = 0; i <= 3; i++) { + eigenVecs[i][j] = 0.0; + } eigenVecs[j][j] = 1.0; eigenVals[j] = quad[j][j]; } @@ -186,7 +188,9 @@ unsigned int jacobi(double quad[4][4], double eigenVals[4], offDiagNorm += fabs(quad[i][j]); } } - if ((offDiagNorm / diagNorm) <= TOLERANCE) goto Exit_now; + if ((offDiagNorm / diagNorm) <= TOLERANCE) { + goto Exit_now; + } for (j = 1; j <= 3; j++) { for (i = 0; i <= j - 1; i++) { b = quad[i][j]; diff --git a/Code/Numerics/Alignment/Wrap/rdAlignment.cpp b/Code/Numerics/Alignment/Wrap/rdAlignment.cpp index d811a203f..2e71a42a9 100644 --- a/Code/Numerics/Alignment/Wrap/rdAlignment.cpp +++ b/Code/Numerics/Alignment/Wrap/rdAlignment.cpp @@ -30,11 +30,13 @@ void GetPointsFromPythonSequence(python::object &points, double *data; if (PyArray_Check(pyObj)) { // get the dimensions of the array - PyArrayObject *ptsMat = reinterpret_cast(pyObj); + auto *ptsMat = reinterpret_cast(pyObj); nrows = PyArray_DIM(ptsMat, 0); ncols = PyArray_DIM(ptsMat, 1); - if (ncols != 3) throw_value_error("Wrong dimension for the points array"); + if (ncols != 3) { + throw_value_error("Wrong dimension for the points array"); + } data = reinterpret_cast(PyArray_DATA(ptsMat)); @@ -45,13 +47,16 @@ void GetPointsFromPythonSequence(python::object &points, } } else if (PySequence_Check(pyObj)) { nrows = PySequence_Size(pyObj); - if (nrows <= 0) throw_value_error("Empty sequence passed in"); + if (nrows <= 0) { + throw_value_error("Empty sequence passed in"); + } python::extract ptOk(points[0]); if (!ptOk.check()) { for (unsigned int i = 0; i < nrows; i++) { PySequenceHolder row(points[i]); - if (row.size() != 3) + if (row.size() != 3) { throw_value_error("Wrong number of entries in the list of lists"); + } auto *rpt = new RDGeom::Point3D(row[0], row[1], row[2]); pts.push_back(rpt); } @@ -90,19 +95,21 @@ PyObject *AlignPointPairs(python::object refPoints, python::object probePoints, GetPointsFromPythonSequence(probePoints, probePts); unsigned int npt = refPts.size(); - if (npt != probePts.size()) + if (npt != probePts.size()) { throw_value_error("Mis-match in number of points"); + } PyObject *weightsObj = weights.ptr(); RDNumeric::DoubleVector *wtsVec; wtsVec = nullptr; double *data; if (PyArray_Check(weightsObj)) { - PyArrayObject *wtsMat = reinterpret_cast(weightsObj); + auto *wtsMat = reinterpret_cast(weightsObj); unsigned int nwts = PyArray_DIM(wtsMat, 0); - if (nwts != npt) + if (nwts != npt) { throw_value_error( "Number of weights supplied do not match the number of points"); + } wtsVec = new RDNumeric::DoubleVector(nwts); data = reinterpret_cast(PyArray_DATA(wtsMat)); for (unsigned int i = 0; i < nwts; i++) { @@ -113,9 +120,10 @@ PyObject *AlignPointPairs(python::object refPoints, python::object probePoints, unsigned int nwts = wts.size(); if (nwts > 0) { - if (nwts != npt) + if (nwts != npt) { throw_value_error( "Number of weights supplied do not match the number of points"); + } wtsVec = new RDNumeric::DoubleVector(nwts); for (unsigned int i = 0; i < npt; i++) { wtsVec->setVal(i, wts[i]); @@ -130,8 +138,8 @@ PyObject *AlignPointPairs(python::object refPoints, python::object probePoints, npy_intp dims[2]; dims[0] = 4; dims[1] = 4; - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); - double *resData = reinterpret_cast(PyArray_DATA(res)); + auto *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); + auto *resData = reinterpret_cast(PyArray_DATA(res)); const double *tdata = trans.getData(); for (unsigned int i = 0; i < trans.numRows(); ++i) { unsigned int itab = i * 4; diff --git a/Code/Numerics/EigenSolvers/PowerEigenSolver.cpp b/Code/Numerics/EigenSolvers/PowerEigenSolver.cpp index 88d81efb7..13d6bbbcb 100644 --- a/Code/Numerics/EigenSolvers/PowerEigenSolver.cpp +++ b/Code/Numerics/EigenSolvers/PowerEigenSolver.cpp @@ -43,7 +43,9 @@ bool powerEigenSolver(unsigned int numEig, DoubleSymmMatrix &mat, unsigned int i, j, id, iter, evalId; DoubleVector v(N), z(N); - if (seed <= 0) seed = clock(); + if (seed <= 0) { + seed = clock(); + } for (ei = 0; ei < numEig; ei++) { eigVal = -HUGE_EIGVAL; seed += ei; diff --git a/Code/Numerics/testConrec.cpp b/Code/Numerics/testConrec.cpp index 1d90d2e9e..85c479afe 100644 --- a/Code/Numerics/testConrec.cpp +++ b/Code/Numerics/testConrec.cpp @@ -24,7 +24,7 @@ TEST_CASE("Conrec basics", "[conrec]") { SECTION("basics") { std::vector pts = {{0., 0.}, {1., 0.}, {1., 1.}, {0., 1.}}; const size_t gridSz = 100; - double *grid = new double[gridSz * gridSz]; + auto *grid = new double[gridSz * gridSz]; double xps[gridSz]; double yps[gridSz]; double x1 = -4, y1 = -4, x2 = 6, y2 = 6; @@ -35,13 +35,17 @@ TEST_CASE("Conrec basics", "[conrec]") { xps[ix] = px; for (size_t iy = 0; iy < gridSz; ++iy) { auto py = y1 + iy * dy; - if (ix == 0) yps[iy] = py; + if (ix == 0) { + yps[iy] = py; + } RDGeom::Point2D loc(px, py); double val = 0.0; for (const auto &pt : pts) { auto dv = loc - pt; auto r = dv.length(); - if (r > 0) val += 1 / r; + if (r > 0) { + val += 1 / r; + } } maxV = std::max(val, maxV); grid[ix * gridSz + iy] = val; diff --git a/Code/PgSQL/rdkit/adapter.cpp b/Code/PgSQL/rdkit/adapter.cpp index 9f4eab22d..c30d0b26f 100644 --- a/Code/PgSQL/rdkit/adapter.cpp +++ b/Code/PgSQL/rdkit/adapter.cpp @@ -121,7 +121,7 @@ typedef SparseIntVect SparseFP; *******************************************/ extern "C" void freeCROMol(CROMol data) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; delete mol; } @@ -141,7 +141,7 @@ extern "C" CROMol constructROMol(Mol *data) { } extern "C" Mol *deconstructROMol(CROMol data) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; ByteA b; try { @@ -233,7 +233,9 @@ extern "C" CROMol parseMolCTAB(char *data, bool keepConformer, bool warnOnFail, errmsg("could not create molecule from CTAB '%s'", data))); } } else { - if (!keepConformer) mol->clearConformers(); + if (!keepConformer) { + mol->clearConformers(); + } } return (CROMol)mol; @@ -331,7 +333,7 @@ extern "C" bool isValidMolBlob(char *data, int len) { extern "C" char *makeMolText(CROMol data, int *len, bool asSmarts, bool cxSmiles) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; try { if (!asSmarts) { @@ -357,7 +359,7 @@ extern "C" char *makeMolText(CROMol data, int *len, bool asSmarts, extern "C" char *makeCtabText(CROMol data, int *len, bool createDepictionIfMissing) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; try { if (createDepictionIfMissing && mol->getNumConformers() == 0) { @@ -376,7 +378,7 @@ extern "C" char *makeCtabText(CROMol data, int *len, } extern "C" char *makeMolBlob(CROMol data, int *len) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; StringData.clear(); try { MolPickler::pickleMol(*mol, StringData); @@ -389,7 +391,7 @@ extern "C" char *makeMolBlob(CROMol data, int *len) { } extern "C" bytea *makeMolSignature(CROMol data) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; ExplicitBitVect *res = nullptr; bytea *ret = nullptr; @@ -411,34 +413,48 @@ extern "C" bytea *makeMolSignature(CROMol data) { } } catch (...) { elog(ERROR, "makeMolSignature: Unknown exception"); - if (res) delete res; + if (res) { + delete res; + } } return ret; } extern "C" int molcmp(CROMol i, CROMol a) { - ROMol *im = (ROMol *)i; - ROMol *am = (ROMol *)a; + auto *im = (ROMol *)i; + auto *am = (ROMol *)a; if (!im) { - if (!am) return 0; + if (!am) { + return 0; + } return -1; } - if (!am) return 1; + if (!am) { + return 1; + } int res = im->getNumAtoms() - am->getNumAtoms(); - if (res) return res; + if (res) { + return res; + } res = im->getNumBonds() - am->getNumBonds(); - if (res) return res; + if (res) { + return res; + } res = int(RDKit::Descriptors::calcAMW(*im, false)) - int(RDKit::Descriptors::calcAMW(*am, false)); - if (res) return res; + if (res) { + return res; + } res = im->getRingInfo()->numRings() - am->getRingInfo()->numRings(); - if (res) return res; + if (res) { + return res; + } RDKit::MatchVectType matchVect; bool recursionPossible = false; @@ -447,10 +463,11 @@ extern "C" int molcmp(CROMol i, CROMol a) { doChiralMatch); bool ss2 = RDKit::SubstructMatch(*am, *im, matchVect, recursionPossible, doChiralMatch); - if (ss1 && !ss2) + if (ss1 && !ss2) { return 1; - else if (!ss1 && ss2) + } else if (!ss1 && ss2) { return -1; + } // the above can still fail in some chirality cases std::string smi1 = MolToSmiles(*im, doChiralMatch); @@ -459,16 +476,16 @@ extern "C" int molcmp(CROMol i, CROMol a) { } extern "C" int MolSubstruct(CROMol i, CROMol a) { - ROMol *im = (ROMol *)i; - ROMol *am = (ROMol *)a; + auto *im = (ROMol *)i; + auto *am = (ROMol *)a; RDKit::MatchVectType matchVect; return RDKit::SubstructMatch(*im, *am, matchVect, true, getDoChiralSSS()); } extern "C" int MolSubstructCount(CROMol i, CROMol a, bool uniquify) { - ROMol *im = (ROMol *)i; - ROMol *am = (ROMol *)a; + auto *im = (ROMol *)i; + auto *am = (ROMol *)a; std::vector matchVect; return static_cast(RDKit::SubstructMatch(*im, *am, matchVect, uniquify, @@ -541,7 +558,7 @@ extern "C" int MolNumHeavyAtoms(CROMol i) { extern "C" char *makeMolFormulaText(CROMol data, int *len, bool separateIsotopes, bool abbreviateHIsotopes) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; try { StringData = RDKit::Descriptors::calcMolFormula(*mol, separateIsotopes, @@ -727,7 +744,7 @@ extern "C" char *MolGetSVG(CROMol i, unsigned int w, unsigned int h, extern "C" char *ReactionGetSVG(CChemicalReaction i, unsigned int w, unsigned int h, bool highlightByReactant, const char *params) { - ChemicalReaction *rxn = (ChemicalReaction *)i; + auto *rxn = (ChemicalReaction *)i; MolDraw2DSVG drawer(w, h); if (params && strlen(params)) { @@ -749,7 +766,7 @@ extern "C" char *ReactionGetSVG(CChemicalReaction i, unsigned int w, *******************************************/ extern "C" void freeCBfp(CBfp data) { - std::string *fp = (std::string *)data; + auto *fp = (std::string *)data; delete fp; } @@ -766,7 +783,7 @@ extern "C" CBfp constructCBfp(Bfp *data) { } extern "C" Bfp *deconstructCBfp(CBfp data) { - std::string *ebv = (std::string *)data; + auto *ebv = (std::string *)data; ByteA b; try { @@ -779,7 +796,7 @@ extern "C" Bfp *deconstructCBfp(CBfp data) { } extern "C" BfpSignature *makeBfpSignature(CBfp data) { - std::string *ebv = (std::string *)data; + auto *ebv = (std::string *)data; int siglen = ebv->size(); unsigned int varsize = sizeof(BfpSignature) + siglen; @@ -793,33 +810,33 @@ extern "C" BfpSignature *makeBfpSignature(CBfp data) { } extern "C" int CBfpSize(CBfp a) { - std::string *ebv = (std::string *)a; + auto *ebv = (std::string *)a; int numBits = ebv->size() * 8; return numBits; } extern "C" double calcBitmapTanimotoSml(CBfp a, CBfp b) { - std::string *abv = (std::string *)a; - std::string *bbv = (std::string *)b; - const unsigned char *afp = (const unsigned char *)abv->c_str(); - const unsigned char *bfp = (const unsigned char *)bbv->c_str(); + auto *abv = (std::string *)a; + auto *bbv = (std::string *)b; + const auto *afp = (const unsigned char *)abv->c_str(); + const auto *bfp = (const unsigned char *)bbv->c_str(); /* return CalcBitmapTanimoto(afp, bfp, abv->size()); */ return bitstringTanimotoSimilarity(abv->size(), (uint8 *)afp, (uint8 *)bfp); } extern "C" double calcBitmapDiceSml(CBfp a, CBfp b) { - std::string *abv = (std::string *)a; - std::string *bbv = (std::string *)b; - const unsigned char *afp = (const unsigned char *)abv->c_str(); - const unsigned char *bfp = (const unsigned char *)bbv->c_str(); + auto *abv = (std::string *)a; + auto *bbv = (std::string *)b; + const auto *afp = (const unsigned char *)abv->c_str(); + const auto *bfp = (const unsigned char *)bbv->c_str(); return CalcBitmapDice(afp, bfp, abv->size()); } double calcBitmapTverskySml(CBfp a, CBfp b, float ca, float cb) { - std::string *abv = (std::string *)a; - std::string *bbv = (std::string *)b; - const unsigned char *afp = (const unsigned char *)abv->c_str(); - const unsigned char *bfp = (const unsigned char *)bbv->c_str(); + auto *abv = (std::string *)a; + auto *bbv = (std::string *)b; + const auto *afp = (const unsigned char *)abv->c_str(); + const auto *bfp = (const unsigned char *)bbv->c_str(); return CalcBitmapTversky(afp, bfp, abv->size(), ca, cb); } @@ -828,7 +845,7 @@ double calcBitmapTverskySml(CBfp a, CBfp b, float ca, float cb) { *******************************************/ extern "C" void freeCSfp(CSfp data) { - SparseFP *fp = (SparseFP *)data; + auto *fp = (SparseFP *)data; delete fp; } @@ -845,7 +862,7 @@ extern "C" CSfp constructCSfp(Sfp *data) { } extern "C" Sfp *deconstructCSfp(CSfp data) { - SparseFP *ebv = (SparseFP *)data; + auto *ebv = (SparseFP *)data; ByteA b; try { @@ -858,14 +875,16 @@ extern "C" Sfp *deconstructCSfp(CSfp data) { } extern "C" bytea *makeSfpSignature(CSfp data, int numBits) { - SparseFP *v = (SparseFP *)data; + auto *v = (SparseFP *)data; int n, numBytes; bytea *res; unsigned char *s; SparseFP::StorageType::const_iterator iter; numBytes = VARHDRSZ + (numBits / 8); - if ((numBits % 8) != 0) numBytes++; + if ((numBits % 8) != 0) { + numBytes++; + } res = (bytea *)palloc0(numBytes); SET_VARSIZE(res, numBytes); @@ -881,7 +900,7 @@ extern "C" bytea *makeSfpSignature(CSfp data, int numBits) { } extern "C" bytea *makeLowSparseFingerPrint(CSfp data, int numInts) { - SparseFP *v = (SparseFP *)data; + auto *v = (SparseFP *)data; int numBytes; bytea *res; IntRange *s; @@ -916,7 +935,7 @@ extern "C" bytea *makeLowSparseFingerPrint(CSfp data, int numInts) { extern "C" void countOverlapValues(bytea *sign, CSfp data, int numBits, int *sum, int *overlapSum, int *overlapN) { - SparseFP *v = (SparseFP *)data; + auto *v = (SparseFP *)data; SparseFP::StorageType::const_iterator iter; *sum = *overlapSum = *overlapN = 0; @@ -948,7 +967,7 @@ extern "C" void countOverlapValues(bytea *sign, CSfp data, int numBits, extern "C" void countLowOverlapValues(bytea *sign, CSfp data, int numInts, int *querySum, int *keySum, int *overlapUp, int *overlapDown) { - SparseFP *v = (SparseFP *)data; + auto *v = (SparseFP *)data; SparseFP::StorageType::const_iterator iter; IntRange *s = (IntRange *)VARDATA(sign); int n; @@ -1018,8 +1037,8 @@ extern "C" double calcSparseDiceSml(CSfp a, CSfp b) { extern "C" double calcSparseStringDiceSml(const char *a, unsigned int sza, const char *b, unsigned int szb) { - const unsigned char *t1 = (const unsigned char *)a; - const unsigned char *t2 = (const unsigned char *)b; + const auto *t1 = (const unsigned char *)a; + const auto *t2 = (const unsigned char *)b; std::uint32_t tmp; tmp = *(reinterpret_cast(t1)); @@ -1131,7 +1150,7 @@ extern "C" double calcSparseStringDiceSml(const char *a, unsigned int sza, extern "C" bool calcSparseStringAllValsGT(const char *a, unsigned int sza, int tgt) { - const unsigned char *t1 = (const unsigned char *)a; + const auto *t1 = (const unsigned char *)a; std::uint32_t tmp; tmp = *(reinterpret_cast(t1)); @@ -1163,13 +1182,15 @@ extern "C" bool calcSparseStringAllValsGT(const char *a, unsigned int sza, std::int32_t v1 = *(reinterpret_cast(t1)); t1 += sizeof(std::int32_t); - if (v1 <= tgt) return false; + if (v1 <= tgt) { + return false; + } } return true; } extern "C" bool calcSparseStringAllValsLT(const char *a, unsigned int sza, int tgt) { - const unsigned char *t1 = (const unsigned char *)a; + const auto *t1 = (const unsigned char *)a; std::uint32_t tmp; tmp = *(reinterpret_cast(t1)); @@ -1201,7 +1222,9 @@ extern "C" bool calcSparseStringAllValsLT(const char *a, unsigned int sza, std::int32_t v1 = *(reinterpret_cast(t1)); t1 += sizeof(std::int32_t); - if (v1 >= tgt) return false; + if (v1 >= tgt) { + return false; + } } return true; } @@ -1232,7 +1255,7 @@ extern "C" CSfp subtractSFP(CSfp a, CSfp b) { * Mol -> fp */ extern "C" CBfp makeLayeredBFP(CROMol data) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; ExplicitBitVect *res = nullptr; try { @@ -1240,7 +1263,9 @@ extern "C" CBfp makeLayeredBFP(CROMol data) { getLayeredFpSize()); } catch (...) { elog(ERROR, "makeLayeredBFP: Unknown exception"); - if (res) delete res; + if (res) { + delete res; + } res = nullptr; } if (res) { @@ -1253,14 +1278,16 @@ extern "C" CBfp makeLayeredBFP(CROMol data) { } extern "C" CBfp makeRDKitBFP(CROMol data) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; ExplicitBitVect *res = nullptr; try { res = RDKit::RDKFingerprintMol(*mol, 1, 6, getRDKitFpSize(), 2); } catch (...) { elog(ERROR, "makeRDKitBFP: Unknown exception"); - if (res) delete res; + if (res) { + delete res; + } res = nullptr; } @@ -1274,7 +1301,7 @@ extern "C" CBfp makeRDKitBFP(CROMol data) { } extern "C" CSfp makeMorganSFP(CROMol data, int radius) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; SparseFP *res = nullptr; std::vector invars(mol->getNumAtoms()); try { @@ -1289,7 +1316,7 @@ extern "C" CSfp makeMorganSFP(CROMol data, int radius) { } extern "C" CBfp makeMorganBFP(CROMol data, int radius) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; ExplicitBitVect *res = nullptr; std::vector invars(mol->getNumAtoms()); try { @@ -1310,7 +1337,7 @@ extern "C" CBfp makeMorganBFP(CROMol data, int radius) { } extern "C" CSfp makeFeatMorganSFP(CROMol data, int radius) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; SparseFP *res = nullptr; std::vector invars(mol->getNumAtoms()); try { @@ -1325,7 +1352,7 @@ extern "C" CSfp makeFeatMorganSFP(CROMol data, int radius) { } extern "C" CBfp makeFeatMorganBFP(CROMol data, int radius) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; ExplicitBitVect *res = nullptr; std::vector invars(mol->getNumAtoms()); try { @@ -1346,7 +1373,7 @@ extern "C" CBfp makeFeatMorganBFP(CROMol data, int radius) { } extern "C" CSfp makeAtomPairSFP(CROMol data) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; SparseFP *res = nullptr; #ifdef UNHASHED_PAIR_FPS try { @@ -1380,7 +1407,7 @@ extern "C" CSfp makeAtomPairSFP(CROMol data) { } extern "C" CSfp makeTopologicalTorsionSFP(CROMol data) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; SparseFP *res = nullptr; #ifdef UNHASHED_PAIR_FPS @@ -1416,7 +1443,7 @@ extern "C" CSfp makeTopologicalTorsionSFP(CROMol data) { } extern "C" CBfp makeAtomPairBFP(CROMol data) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; ExplicitBitVect *res = nullptr; try { res = RDKit::AtomPairs::getHashedAtomPairFingerprintAsBitVect( @@ -1434,7 +1461,7 @@ extern "C" CBfp makeAtomPairBFP(CROMol data) { } extern "C" CBfp makeTopologicalTorsionBFP(CROMol data) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; ExplicitBitVect *res = nullptr; try { res = RDKit::AtomPairs::getHashedTopologicalTorsionFingerprintAsBitVect( @@ -1452,7 +1479,7 @@ extern "C" CBfp makeTopologicalTorsionBFP(CROMol data) { } extern "C" CBfp makeMACCSBFP(CROMol data) { - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; ExplicitBitVect *res = nullptr; try { res = RDKit::MACCSFingerprints::getFingerprintAsBitVect(*mol); @@ -1471,7 +1498,7 @@ extern "C" CBfp makeMACCSBFP(CROMol data) { extern "C" CBfp makeAvalonBFP(CROMol data, bool isQuery, unsigned int bitFlags) { #ifdef RDK_BUILD_AVALON_SUPPORT - ROMol *mol = (ROMol *)data; + auto *mol = (ROMol *)data; ExplicitBitVect *res = nullptr; try { res = new ExplicitBitVect(getAvalonFpSize()); @@ -1497,7 +1524,7 @@ extern "C" CBfp makeAvalonBFP(CROMol data, bool isQuery, /* chemical reactions */ extern "C" void freeChemReaction(CChemicalReaction data) { - ChemicalReaction *rxn = (ChemicalReaction *)data; + auto *rxn = (ChemicalReaction *)data; delete rxn; } @@ -1517,7 +1544,7 @@ extern "C" CChemicalReaction constructChemReact(Reaction *data) { } extern "C" Reaction *deconstructChemReact(CChemicalReaction data) { - ChemicalReaction *rxn = (ChemicalReaction *)data; + auto *rxn = (ChemicalReaction *)data; ByteA b; try { @@ -1594,7 +1621,7 @@ extern "C" CChemicalReaction parseChemReactBlob(char *data, int len) { extern "C" char *makeChemReactText(CChemicalReaction data, int *len, bool asSmarts) { - ChemicalReaction *rxn = (ChemicalReaction *)data; + auto *rxn = (ChemicalReaction *)data; try { if (!asSmarts) { @@ -1614,7 +1641,7 @@ extern "C" char *makeChemReactText(CChemicalReaction data, int *len, } extern "C" char *makeChemReactBlob(CChemicalReaction data, int *len) { - ChemicalReaction *rxn = (ChemicalReaction *)data; + auto *rxn = (ChemicalReaction *)data; StringData.clear(); try { ReactionPickler::pickleReaction(*rxn, StringData); @@ -1657,7 +1684,7 @@ extern "C" CChemicalReaction parseChemReactCTAB(char *data, bool warnOnFail) { } extern "C" char *makeCTABChemReact(CChemicalReaction data, int *len) { - ChemicalReaction *rxn = (ChemicalReaction *)data; + auto *rxn = (ChemicalReaction *)data; try { StringData = ChemicalReactionToRxnBlock(*rxn); @@ -1689,7 +1716,7 @@ extern "C" int ChemReactNumAgents(CChemicalReaction crxn) { } extern "C" bytea *makeReactionSign(CChemicalReaction data) { - ChemicalReaction *rxn = (ChemicalReaction *)data; + auto *rxn = (ChemicalReaction *)data; ExplicitBitVect *res = nullptr; bytea *ret = nullptr; @@ -1714,15 +1741,17 @@ extern "C" bytea *makeReactionSign(CChemicalReaction data) { } } catch (...) { elog(ERROR, "makeReactionSign: Unknown exception"); - if (res) delete res; + if (res) { + delete res; + } } return ret; } extern "C" int ReactionSubstruct(CChemicalReaction rxn, CChemicalReaction rxn2) { - ChemicalReaction *rxnm = (ChemicalReaction *)rxn; - ChemicalReaction *rxn2m = (ChemicalReaction *)rxn2; + auto *rxnm = (ChemicalReaction *)rxn; + auto *rxn2m = (ChemicalReaction *)rxn2; /* Reaction search */ if (rxn2m->getNumReactantTemplates() != 0 && @@ -1760,8 +1789,8 @@ extern "C" int ReactionSubstruct(CChemicalReaction rxn, extern "C" int ReactionSubstructFP(CChemicalReaction rxn, CChemicalReaction rxnquery) { - ChemicalReaction *rxnm = (ChemicalReaction *)rxn; - ChemicalReaction *rxnqm = (ChemicalReaction *)rxnquery; + auto *rxnm = (ChemicalReaction *)rxn; + auto *rxnqm = (ChemicalReaction *)rxnquery; RDKit::ReactionFingerprintParams params; params.fpType = static_cast(getReactionSubstructFpType()); @@ -1835,14 +1864,18 @@ int compareMolDescriptors(const MoleculeDescriptors &md1, } // namespace extern "C" int reactioncmp(CChemicalReaction rxn, CChemicalReaction rxn2) { - ChemicalReaction *rxnm = (ChemicalReaction *)rxn; - ChemicalReaction *rxn2m = (ChemicalReaction *)rxn2; + auto *rxnm = (ChemicalReaction *)rxn; + auto *rxn2m = (ChemicalReaction *)rxn2; if (!rxnm) { - if (!rxn2m) return 0; + if (!rxn2m) { + return 0; + } return -1; } - if (!rxn2m) return 1; + if (!rxn2m) { + return 1; + } int res = rxnm->getNumReactantTemplates() - rxn2m->getNumReactantTemplates(); if (res) { @@ -1901,14 +1934,14 @@ extern "C" int reactioncmp(CChemicalReaction rxn, CChemicalReaction rxn2) { extern "C" CSfp makeReactionDifferenceSFP(CChemicalReaction data, int size, int fpType) { - ChemicalReaction *rxn = (ChemicalReaction *)data; + auto *rxn = (ChemicalReaction *)data; SparseFP *res = nullptr; try { if (fpType > 3 || fpType < 1) { elog(ERROR, "makeReactionDifferenceSFP: Unknown Fingerprint type"); } - FingerprintType fp = static_cast(fpType); + auto fp = static_cast(fpType); RDKit::ReactionFingerprintParams params; params.fpType = static_cast(fpType); params.fpSize = size; @@ -1923,14 +1956,14 @@ extern "C" CSfp makeReactionDifferenceSFP(CChemicalReaction data, int size, } extern "C" CBfp makeReactionBFP(CChemicalReaction data, int size, int fpType) { - ChemicalReaction *rxn = (ChemicalReaction *)data; + auto *rxn = (ChemicalReaction *)data; ExplicitBitVect *res = nullptr; try { if (fpType > 5 || fpType < 1) { elog(ERROR, "makeReactionBFP: Unknown Fingerprint type"); } - FingerprintType fp = static_cast(fpType); + auto fp = static_cast(fpType); RDKit::ReactionFingerprintParams params; params.fpType = static_cast(fpType); params.fpSize = size; @@ -2035,12 +2068,18 @@ extern "C" char *findMCSsmiles(char *smiles, char *params) { char *s = str; int len, nmols = 0; std::vector molecules; - while (*s && *s <= ' ') s++; + while (*s && *s <= ' ') { + s++; + } while (*s > ' ') { len = 0; - while (s[len] > ' ') len++; + while (s[len] > ' ') { + len++; + } s[len] = '\0'; - if (0 == strlen(s)) continue; + if (0 == strlen(s)) { + continue; + } molecules.push_back(RDKit::ROMOL_SPTR(RDKit::SmilesToMol(s))); // elog(WARNING, s); s += len; @@ -2081,7 +2120,7 @@ extern "C" void *addMol2list(void *lst, Mol *mol) { std::vector &mlst = *(std::vector *)lst; // elog(WARNING, "addMol2list: create a copy of new mol"); - ROMol *m = (ROMol *)constructROMol( + auto *m = (ROMol *)constructROMol( mol); // new ROMol(*(const ROMol*)mol, false); // create a copy // elog(WARNING, "addMol2list: append new mol into list"); mlst.push_back(RDKit::ROMOL_SPTR(m)); diff --git a/Code/PgSQL/rdkit/bfp_op.c b/Code/PgSQL/rdkit/bfp_op.c index 28b4662e3..f04fea6e9 100644 --- a/Code/PgSQL/rdkit/bfp_op.c +++ b/Code/PgSQL/rdkit/bfp_op.c @@ -41,11 +41,13 @@ bfpcmp(Bfp *a, Bfp *b) { int res; res = memcmp(VARDATA(a), VARDATA(b), Min(VARSIZE(a), VARSIZE(b)) - VARHDRSZ); - if ( res ) + if (res) { return res; + } - if (VARSIZE(a) == VARSIZE(b)) + if (VARSIZE(a) == VARSIZE(b)) { return 0; + } return (VARSIZE(a) > VARSIZE(b)) ? 1 : -1; } diff --git a/Code/PgSQL/rdkit/mol_op.c b/Code/PgSQL/rdkit/mol_op.c index 49d278c7e..f860ec2db 100644 --- a/Code/PgSQL/rdkit/mol_op.c +++ b/Code/PgSQL/rdkit/mol_op.c @@ -261,7 +261,9 @@ Datum mol_murckoscaffold(PG_FUNCTION_ARGS) { searchMolCache(fcinfo->flinfo->fn_extra, fcinfo->flinfo->fn_mcxt, PG_GETARG_DATUM(0), NULL, &mol, NULL); CROMol scaffold = MolMurckoScaffold(mol); - if (!scaffold) PG_RETURN_NULL(); + if (!scaffold) { + PG_RETURN_NULL(); + } res = deconstructROMol(scaffold); freeCROMol(scaffold); @@ -313,7 +315,9 @@ Datum mol_adjust_query_properties(PG_FUNCTION_ARGS) { char *data = PG_GETARG_CSTRING(1); CROMol adj = MolAdjustQueryProperties(mol, data); - if (!adj) PG_RETURN_NULL(); + if (!adj) { + PG_RETURN_NULL(); + } Mol *res = deconstructROMol(adj); freeCROMol(adj); diff --git a/Code/PgSQL/rdkit/rdkit_io.c b/Code/PgSQL/rdkit/rdkit_io.c index 2a370742c..9441b050e 100644 --- a/Code/PgSQL/rdkit/rdkit_io.c +++ b/Code/PgSQL/rdkit/rdkit_io.c @@ -127,7 +127,9 @@ mol_from_ctab(PG_FUNCTION_ARGS) { Mol *res; mol = parseMolCTAB(data,keepConformer,true,false); - if(!mol) PG_RETURN_NULL(); + if (!mol) { + PG_RETURN_NULL(); + } res = deconstructROMol(mol); freeCROMol(mol); @@ -144,7 +146,9 @@ qmol_from_ctab(PG_FUNCTION_ARGS) { Mol *res; mol = parseMolCTAB(data,keepConformer,true,true); - if(!mol) PG_RETURN_NULL(); + if (!mol) { + PG_RETURN_NULL(); + } res = deconstructROMol(mol); freeCROMol(mol); @@ -160,7 +164,9 @@ mol_from_smarts(PG_FUNCTION_ARGS) { Mol *res; mol = parseMolText(data,true,true,false); - if(!mol) PG_RETURN_NULL(); + if (!mol) { + PG_RETURN_NULL(); + } res = deconstructROMol(mol); freeCROMol(mol); @@ -176,7 +182,9 @@ mol_from_smiles(PG_FUNCTION_ARGS) { Mol *res; mol = parseMolText(data,false,true,false); - if(!mol) PG_RETURN_NULL(); + if (!mol) { + PG_RETURN_NULL(); + } res = deconstructROMol(mol); freeCROMol(mol); @@ -192,7 +200,9 @@ qmol_from_smiles(PG_FUNCTION_ARGS) { Mol *res; mol = parseMolText(data,false,true,true); - if(!mol) PG_RETURN_NULL(); + if (!mol) { + PG_RETURN_NULL(); + } res = deconstructROMol(mol); freeCROMol(mol); @@ -531,7 +541,9 @@ reaction_from_ctab(PG_FUNCTION_ARGS) { Reaction *rxn; crxn = parseChemReactCTAB(data,true); - if(!crxn) PG_RETURN_NULL(); + if (!crxn) { + PG_RETURN_NULL(); + } rxn = deconstructChemReact(crxn); freeChemReaction(crxn); @@ -547,7 +559,9 @@ reaction_from_smarts(PG_FUNCTION_ARGS) { Reaction *rxn; crxn = parseChemReactText(data,true,true); - if(!crxn) PG_RETURN_NULL(); + if (!crxn) { + PG_RETURN_NULL(); + } rxn = deconstructChemReact(crxn); freeChemReaction(crxn); @@ -563,7 +577,9 @@ reaction_from_smiles(PG_FUNCTION_ARGS) { Reaction *rxn; crxn = parseChemReactText(data,false,true); - if(!crxn) PG_RETURN_NULL(); + if (!crxn) { + PG_RETURN_NULL(); + } rxn = deconstructChemReact(crxn); freeChemReaction(crxn); diff --git a/Code/PgSQL/rdkit/sfp_op.c b/Code/PgSQL/rdkit/sfp_op.c index ef265ba67..13ec7543f 100644 --- a/Code/PgSQL/rdkit/sfp_op.c +++ b/Code/PgSQL/rdkit/sfp_op.c @@ -41,11 +41,13 @@ sfpcmp(Sfp *a, Sfp *b) { int res; res = memcmp(VARDATA(a), VARDATA(b), Min(VARSIZE(a), VARSIZE(b)) - VARHDRSZ); - if ( res ) + if (res) { return res; + } - if (VARSIZE(a) == VARSIZE(b)) + if (VARSIZE(a) == VARSIZE(b)) { return 0; + } return (VARSIZE(a) > VARSIZE(b)) ? 1 : -1; } diff --git a/Code/RDGeneral/LocaleSwitcher.cpp b/Code/RDGeneral/LocaleSwitcher.cpp index 24cbed4ef..a6efd7300 100644 --- a/Code/RDGeneral/LocaleSwitcher.cpp +++ b/Code/RDGeneral/LocaleSwitcher.cpp @@ -79,10 +79,11 @@ static int recurseLocale(int state) { return recursion; #else static thread_local int recursion = 0; - if (state == SwitchLocale) + if (state == SwitchLocale) { recursion++; - else if (state == ResetLocale) + } else if (state == ResetLocale) { recursion--; + } return recursion; #endif } @@ -133,8 +134,9 @@ class LocaleSwitcherImpl { loc = newlocale(LC_ALL_MASK, "C", (locale_t) nullptr); uselocale(loc); // Don't free "C" or "GLOBAL" Locales - } else + } else { old_locale = "C"; // prevents recursion + } } ~LocaleSwitcherImpl() { if (old_locale != "C") { diff --git a/Code/RDGeneral/RDLog.cpp b/Code/RDGeneral/RDLog.cpp index b32dde705..8a62eb0cc 100644 --- a/Code/RDGeneral/RDLog.cpp +++ b/Code/RDGeneral/RDLog.cpp @@ -29,32 +29,48 @@ void enable_logs(const char *arg) { enable_logs(std::string(arg)); }; void enable_logs(const std::string &arg) { // Yes... this is extremely crude if (arg == "rdApp.debug" || arg == "rdApp.*") { - if (rdDebugLog) rdDebugLog->df_enabled = true; + if (rdDebugLog) { + rdDebugLog->df_enabled = true; + } } if (arg == "rdApp.info" || arg == "rdApp.*") { - if (rdInfoLog) rdInfoLog->df_enabled = true; + if (rdInfoLog) { + rdInfoLog->df_enabled = true; + } } if (arg == "rdApp.warning" || arg == "rdApp.*") { - if (rdWarningLog) rdWarningLog->df_enabled = true; + if (rdWarningLog) { + rdWarningLog->df_enabled = true; + } } if (arg == "rdApp.error" || arg == "rdApp.*") { - if (rdErrorLog) rdErrorLog->df_enabled = true; + if (rdErrorLog) { + rdErrorLog->df_enabled = true; + } } }; void disable_logs(const char *arg) { disable_logs(std::string(arg)); }; void disable_logs(const std::string &arg) { // Yes... this is extremely crude if (arg == "rdApp.debug" || arg == "rdApp.*") { - if (rdDebugLog) rdDebugLog->df_enabled = false; + if (rdDebugLog) { + rdDebugLog->df_enabled = false; + } } if (arg == "rdApp.info" || arg == "rdApp.*") { - if (rdInfoLog) rdInfoLog->df_enabled = false; + if (rdInfoLog) { + rdInfoLog->df_enabled = false; + } } if (arg == "rdApp.warning" || arg == "rdApp.*") { - if (rdWarningLog) rdWarningLog->df_enabled = false; + if (rdWarningLog) { + rdWarningLog->df_enabled = false; + } } if (arg == "rdApp.error" || arg == "rdApp.*") { - if (rdErrorLog) rdErrorLog->df_enabled = false; + if (rdErrorLog) { + rdErrorLog->df_enabled = false; + } } }; } // namespace logging diff --git a/Code/RDGeneral/testDict.cpp b/Code/RDGeneral/testDict.cpp index 3cadef0ef..498389929 100644 --- a/Code/RDGeneral/testDict.cpp +++ b/Code/RDGeneral/testDict.cpp @@ -152,7 +152,9 @@ void testRDAny() { { std::vector v; - for (int i = 0; i < 4; ++i) v.push_back(i); + for (int i = 0; i < 4; ++i) { + v.push_back(i); + } RDAny foo(v); RDAny bar = foo; @@ -167,7 +169,9 @@ void testRDAny() { { std::vector v; - for (double i = 0; i < 4; ++i) v.push_back(i); + for (double i = 0; i < 4; ++i) { + v.push_back(i); + } RDAny foo(v); @@ -288,7 +292,7 @@ void testRDAny() { boost::any_cast> &>(any1); RDAny vv(pvect); - boost::any &any = rdany_cast(vv); + auto &any = rdany_cast(vv); boost::any_cast>>(any); boost::any_cast> &>(any); boost::any_cast> &>(any); @@ -323,7 +327,7 @@ void testRDAny() { (*m)[0] = 1; RDAny mv(m); // leaks - std::map *anym = rdany_cast *>(mv); + auto *anym = rdany_cast *>(mv); TEST_ASSERT(anym->find(0) != anym->end()); delete anym; } @@ -654,36 +658,34 @@ void testUpdate() { class FooHandler : public CustomPropHandler { public: - virtual const char *getPropName() const { return "Foo"; } - virtual bool canSerialize(const RDValue &value) const { - return rdvalue_is(value); - } - virtual bool read(std::istream &ss, RDValue &value) const { - int version = 0; - streamRead(ss, version); - Foo f; - streamRead(ss, f.bar); - streamRead(ss, f.baz); - value = f; - return true; - } - - virtual bool write(std::ostream &ss, const RDValue &value) const { - try{ - const Foo &f = rdvalue_cast(value); - const int version = 0; - streamWrite(ss, version); - streamWrite(ss, f.bar); - streamWrite(ss, f.baz); - } catch ( boost::bad_any_cast & ) { - return false; - } - return true; - } - - virtual CustomPropHandler* clone() const { - return new FooHandler; - } + const char *getPropName() const override { return "Foo"; } + bool canSerialize(const RDValue &value) const override { + return rdvalue_is(value); + } + bool read(std::istream &ss, RDValue &value) const override { + int version = 0; + streamRead(ss, version); + Foo f; + streamRead(ss, f.bar); + streamRead(ss, f.baz); + value = f; + return true; + } + + bool write(std::ostream &ss, const RDValue &value) const override { + try { + const Foo &f = rdvalue_cast(value); + const int version = 0; + streamWrite(ss, version); + streamWrite(ss, f.bar); + streamWrite(ss, f.baz); + } catch (boost::bad_any_cast &) { + return false; + } + return true; + } + + CustomPropHandler *clone() const override { return new FooHandler; } }; void testCustomProps() { diff --git a/Code/RDGeneral/types.cpp b/Code/RDGeneral/types.cpp index a3d984e8e..64a007216 100644 --- a/Code/RDGeneral/types.cpp +++ b/Code/RDGeneral/types.cpp @@ -156,7 +156,7 @@ void Union(const VECT_INT_VECT &rings, INT_VECT &res, const INT_VECT *exclude) { res.resize(0); INT_VECT ring; unsigned int id; - unsigned int nrings = static_cast(rings.size()); + auto nrings = static_cast(rings.size()); INT_VECT_CI ri; for (id = 0; id < nrings; id++) { diff --git a/Code/SimDivPickers/HierarchicalClusterPicker.cpp b/Code/SimDivPickers/HierarchicalClusterPicker.cpp index 92e92e5a8..25a39ce99 100644 --- a/Code/SimDivPickers/HierarchicalClusterPicker.cpp +++ b/Code/SimDivPickers/HierarchicalClusterPicker.cpp @@ -26,15 +26,15 @@ RDKit::VECT_INT_VECT HierarchicalClusterPicker::cluster( "pickSize cannot be larger than the poolSize"); // Do the clustering - long int method = (long int)d_method; + auto method = (long int)d_method; long int len = poolSize * (poolSize - 1); - long int *ia = (long int *)calloc(poolSize, sizeof(long int)); - long int *ib = (long int *)calloc(poolSize, sizeof(long int)); + auto *ia = (long int *)calloc(poolSize, sizeof(long int)); + auto *ib = (long int *)calloc(poolSize, sizeof(long int)); real *crit = (real *)calloc(poolSize, sizeof(real)); CHECK_INVARIANT(ia, "failed to allocate memory"); CHECK_INVARIANT(ib, "failed to allocate memory"); CHECK_INVARIANT(crit, "failed to allocate memory"); - long int poolSize2 = static_cast(poolSize); + auto poolSize2 = static_cast(poolSize); distdriver_(&poolSize2, // number of items in the pool &len, // number of entries in the distance matrix diff --git a/Code/SimDivPickers/Wrap/HierarchicalClusterPicker.cpp b/Code/SimDivPickers/Wrap/HierarchicalClusterPicker.cpp index 703f4265c..39de847cd 100644 --- a/Code/SimDivPickers/Wrap/HierarchicalClusterPicker.cpp +++ b/Code/SimDivPickers/Wrap/HierarchicalClusterPicker.cpp @@ -40,7 +40,7 @@ RDKit::INT_VECT HierarchicalPicks(HierarchicalClusterPicker *picker, // CopyFromObject here instead of ContiguousFromObject copy = (PyArrayObject *)PyArray_CopyFromObject(distMat.ptr(), NPY_DOUBLE, 1, 1); - double *dMat = (double *)PyArray_DATA(copy); + auto *dMat = (double *)PyArray_DATA(copy); RDKit::INT_VECT res = picker->pick(dMat, poolSize, pickSize); Py_DECREF(copy); return res; @@ -61,7 +61,7 @@ RDKit::VECT_INT_VECT HierarchicalClusters(HierarchicalClusterPicker *picker, // CopyFromObject here instead of ContiguousFromObject copy = (PyArrayObject *)PyArray_CopyFromObject(distMat.ptr(), NPY_DOUBLE, 1, 1); - double *dMat = (double *)PyArray_DATA(copy); + auto *dMat = (double *)PyArray_DATA(copy); RDKit::VECT_INT_VECT res = picker->cluster(dMat, poolSize, pickSize); Py_DECREF(copy); diff --git a/Code/SimDivPickers/Wrap/MaxMinPicker.cpp b/Code/SimDivPickers/Wrap/MaxMinPicker.cpp index 16768dcfb..1b5fa72a5 100644 --- a/Code/SimDivPickers/Wrap/MaxMinPicker.cpp +++ b/Code/SimDivPickers/Wrap/MaxMinPicker.cpp @@ -44,7 +44,7 @@ RDKit::INT_VECT MaxMinPicks(MaxMinPicker *picker, python::object distMat, PyArrayObject *copy; copy = (PyArrayObject *)PyArray_ContiguousFromObject(distMat.ptr(), NPY_DOUBLE, 1, 1); - double *dMat = (double *)PyArray_DATA(copy); + auto *dMat = (double *)PyArray_DATA(copy); RDKit::INT_VECT firstPickVect; for (unsigned int i = 0; diff --git a/Code/SimDivPickers/testPickers.cpp b/Code/SimDivPickers/testPickers.cpp index 49fbcf35f..6ca216a2b 100644 --- a/Code/SimDivPickers/testPickers.cpp +++ b/Code/SimDivPickers/testPickers.cpp @@ -47,7 +47,9 @@ void testGithub2245() { --maxAllowedFailures) { auto picks2 = pkr.lazyPick(dist_on_line, poolSz, 10, RDKit::INT_VECT(), -1); - if (picks1 != picks2) break; + if (picks1 != picks2) { + break; + } } TEST_ASSERT(maxAllowedFailures); } @@ -58,7 +60,9 @@ void testGithub2245() { for (maxAllowedFailures = MAX_ALLOWED_FAILURES; maxAllowedFailures; --maxAllowedFailures) { auto picks2 = pkr.lazyPick(dist_on_line, poolSz, 10); - if (picks1 != picks2) break; + if (picks1 != picks2) { + break; + } } TEST_ASSERT(maxAllowedFailures); } diff --git a/External/AvalonTools/AvalonTools.cpp b/External/AvalonTools/AvalonTools.cpp index 3928a2aa0..ce49aaf66 100644 --- a/External/AvalonTools/AvalonTools.cpp +++ b/External/AvalonTools/AvalonTools.cpp @@ -54,7 +54,9 @@ int *getCountFp(struct reaccs_molecule_t *molPtr, unsigned int bitFlags, char *getFp(struct reaccs_molecule_t *molPtr, unsigned int bitFlags, bool isQuery, unsigned int nBytes) { PRECONDITION(molPtr, "bad molecule"); - while (nBytes % 4) ++nBytes; + while (nBytes % 4) { + ++nBytes; + } char *fingerprint = TypeAlloc(nBytes, char); SetFingerprintBits(molPtr, fingerprint, static_cast(nBytes), static_cast(bitFlags), static_cast(isQuery), 0); @@ -69,7 +71,9 @@ void reaccsToFingerprint(struct reaccs_molecule_t *molPtr, std::vector &res, unsigned int bitFlags = 32767U, bool isQuery = false, bool resetVect = true, unsigned int nBytes = 64) { - if (resetVect) res.clear(); + if (resetVect) { + res.clear(); + } char *fingerprint = getFp(molPtr, bitFlags, isQuery, nBytes); for (unsigned int i = 0; i < nBytes; i += 4) { boost::uint32_t word; @@ -101,7 +105,9 @@ void reaccsToFingerprint(struct reaccs_molecule_t *molPtr, ExplicitBitVect &res, bool resetVect = true, unsigned int nBytes = 64) { PRECONDITION(molPtr, "bad molecule"); PRECONDITION(res.getNumBits() >= nBytes * 8U, "res too small"); - if (resetVect) res.clearBits(); + if (resetVect) { + res.clearBits(); + } char *fingerprint = getFp(molPtr, bitFlags, isQuery, nBytes); @@ -163,7 +169,9 @@ struct reaccs_molecule_t *stringToReaccs(const std::string &data, } // end of anonymous namespace std::string getCanonSmiles(ROMol &mol, int flags) { - if (flags == -1) flags = DB_STEREO | CENTER_STEREO; + if (flags == -1) { + flags = DB_STEREO | CENTER_STEREO; + } std::string res; if (!mol.getNumConformers()) { std::string rdSmi = MolToSmiles(mol, true); @@ -264,7 +272,9 @@ std::string set2DCoords(const std::string &data, bool isSmiles) { } std::string getCanonSmiles(const std::string &data, bool isSmiles, int flags) { - if (flags == -1) flags = DB_STEREO | CENTER_STEREO; + if (flags == -1) { + flags = DB_STEREO | CENTER_STEREO; + } char *smiles = nullptr, *canSmiles = nullptr; if (!isSmiles) { struct reaccs_molecule_t *mp = stringToReaccs(data, isSmiles); @@ -340,7 +350,9 @@ void getAvalonFP(const std::string &data, bool isSmiles, } int _checkMolWrapper(struct reaccs_molecule_t **mpp) { - if (!*mpp) return BAD_MOLECULE; + if (!*mpp) { + return BAD_MOLECULE; + } int res; struct reaccs_molecule_t *tmp = *mpp; res = RunStruchk(mpp, nullptr); diff --git a/External/AvalonTools/test1.cpp b/External/AvalonTools/test1.cpp index 7688ebee6..65f55731a 100644 --- a/External/AvalonTools/test1.cpp +++ b/External/AvalonTools/test1.cpp @@ -201,7 +201,7 @@ void testRDK151() { { std::string tSmi = "C[C@H](F)Cl"; - ROMol *m = static_cast(SmilesToMol(tSmi)); + auto *m = static_cast(SmilesToMol(tSmi)); TEST_ASSERT(m); std::string smi = AvalonTools::getCanonSmiles(tSmi, true); CHECK_INVARIANT(smi == tSmi, smi + "!=" + tSmi); diff --git a/External/CoordGen/test.cpp b/External/CoordGen/test.cpp index ba9c0558f..cd8c1470d 100644 --- a/External/CoordGen/test.cpp +++ b/External/CoordGen/test.cpp @@ -122,7 +122,9 @@ bool compareConfs(const ROMol* m, ROMol* templ, const MatchVectType& mv, if (alignFirst) { double rmsd = MolAlign::alignMol(*templ, *m, molConfId, templateConfId, &mv); - if (rmsd > rmstol) return false; + if (rmsd > rmstol) { + return false; + } } const Conformer& conf1 = m->getConformer(molConfId); @@ -133,7 +135,9 @@ bool compareConfs(const ROMol* m, ROMol* templ, const MatchVectType& mv, RDGeom::Point3D pt1i = conf1.getAtomPos(mv[i].second); RDGeom::Point3D pt2i = conf2.getAtomPos(mv[i].first); - if ((pt1i - pt2i).length() >= postol) return false; + if ((pt1i - pt2i).length() >= postol) { + return false; + } } return true; } @@ -169,10 +173,9 @@ void test2() { { auto coreConf = core->getConformer(); RDGeom::INT_POINT2D_MAP coordMap; - for (unsigned int i = 0; i < mv.size(); ++i) { - coordMap[mv[i].second] = - RDGeom::Point2D(coreConf.getAtomPos(mv[i].first).x, - coreConf.getAtomPos(mv[i].first).y); + for (auto& i : mv) { + coordMap[i.second] = RDGeom::Point2D(coreConf.getAtomPos(i.first).x, + coreConf.getAtomPos(i.first).y); } CoordGen::CoordGenParams params; params.coordMap = coordMap; @@ -225,10 +228,9 @@ void test2() { { auto coreConf = core->getConformer(); RDGeom::INT_POINT2D_MAP coordMap; - for (unsigned int i = 0; i < mv.size(); ++i) { - coordMap[mv[i].second] = - RDGeom::Point2D(coreConf.getAtomPos(mv[i].first).x, - coreConf.getAtomPos(mv[i].first).y); + for (auto& i : mv) { + coordMap[i.second] = RDGeom::Point2D(coreConf.getAtomPos(i.first).x, + coreConf.getAtomPos(i.first).y); } CoordGen::CoordGenParams params; params.coordMap = coordMap; @@ -282,10 +284,9 @@ void test2() { { auto coreConf = core->getConformer(); RDGeom::INT_POINT2D_MAP coordMap; - for (unsigned int i = 0; i < mv.size(); ++i) { - coordMap[mv[i].second] = - RDGeom::Point2D(coreConf.getAtomPos(mv[i].first).x, - coreConf.getAtomPos(mv[i].first).y); + for (auto& i : mv) { + coordMap[i.second] = RDGeom::Point2D(coreConf.getAtomPos(i.first).x, + coreConf.getAtomPos(i.first).y); } CoordGen::CoordGenParams params; diff --git a/External/FreeSASA/RDFreeSASA.cpp b/External/FreeSASA/RDFreeSASA.cpp index 3ce536fec..055134a3d 100644 --- a/External/FreeSASA/RDFreeSASA.cpp +++ b/External/FreeSASA/RDFreeSASA.cpp @@ -159,7 +159,9 @@ double internalCalcSASA(const ROMol &mol, const std::vector &radii, freesasa_result *res = freesasa_calc_coord(&coords[0], &radii[0], mol.getNumAtoms(), ¶ms); - if (!res) return 0.0; + if (!res) { + return 0.0; + } CHECK_INVARIANT(res->n_atoms == rdcast(mol.getNumAtoms()), "freesasa didn't return the correct number of atoms"); diff --git a/External/FreeSASA/Wrap/rdFreeSASA.cpp b/External/FreeSASA/Wrap/rdFreeSASA.cpp index a7fcb906b..74df01b54 100644 --- a/External/FreeSASA/Wrap/rdFreeSASA.cpp +++ b/External/FreeSASA/Wrap/rdFreeSASA.cpp @@ -53,7 +53,9 @@ python::object classifyAtomsHelper(RDKit::ROMol &mol, std::vector radii; python::list l; if (FreeSASA::classifyAtoms(mol, radii, opts)) { - for (double &i : radii) l.append(i); + for (double &i : radii) { + l.append(i); + } return l; } return l; diff --git a/External/INCHI-API/Wrap/pyInchi.cpp b/External/INCHI-API/Wrap/pyInchi.cpp index 53d61c058..9a8c0ff1c 100644 --- a/External/INCHI-API/Wrap/pyInchi.cpp +++ b/External/INCHI-API/Wrap/pyInchi.cpp @@ -36,9 +36,10 @@ namespace { boost::python::tuple MolToInchi(const RDKit::ROMol &mol, std::string options) { RDKit::ExtraInchiReturnValues rv; - const char* _options = NULL; - if (options.size()) + const char* _options = nullptr; + if (options.size()) { _options = options.c_str(); + } std::string inchi = RDKit::MolToInchi(mol, rv, _options); return boost::python::make_tuple(inchi, rv.returnCode, rv.messagePtr, rv.logPtr, rv.auxInfoPtr); @@ -47,9 +48,10 @@ namespace { boost::python::tuple MolBlockToInchi(const std::string &molblock, std::string options) { RDKit::ExtraInchiReturnValues rv; - const char* _options = NULL; - if (options.size()) + const char* _options = nullptr; + if (options.size()) { _options = options.c_str(); + } std::string inchi = RDKit::MolBlockToInchi(molblock, rv, _options); return boost::python::make_tuple(inchi, rv.returnCode, rv.messagePtr, rv.logPtr, rv.auxInfoPtr); @@ -59,10 +61,10 @@ namespace { { RDKit::ExtraInchiReturnValues rv; RDKit::ROMol* mol = RDKit::InchiToMol(inchi, rv, sanitize, removeHs); - if (mol == NULL) + if (mol == nullptr) { return boost::python::make_tuple(boost::python::object(), rv.returnCode, rv.messagePtr, rv.logPtr); - else { + } else { return boost::python::make_tuple(RDKit::ROMOL_SPTR(mol), rv.returnCode, rv.messagePtr, rv.logPtr); } diff --git a/External/INCHI-API/inchi.cpp b/External/INCHI-API/inchi.cpp index 5372bd809..8fe5969b9 100644 --- a/External/INCHI-API/inchi.cpp +++ b/External/INCHI-API/inchi.cpp @@ -121,14 +121,17 @@ bool assignBondDirs(RWMol& mol, INT_PAIR_VECT& zBondPairs, // is it assigned already? if (bond->getBondDir() != Bond::NONE) { // assigned. then check conflict - if (bond->getBondDir() != dir) + if (bond->getBondDir() != dir) { // not doable return false; + } } else { // assign since it's not assigned yet bond->setBondDir(dir); - std::set::iterator searchItr = pending.find(curBondIdx); - if (searchItr != pending.end()) pending.erase(searchItr); + auto searchItr = pending.find(curBondIdx); + if (searchItr != pending.end()) { + pending.erase(searchItr); + } // find all affecting bonds and add to queue by going thru all rules Bond::BondDir otherDir = dir == Bond::ENDUPRIGHT ? Bond::ENDDOWNRIGHT : Bond::ENDUPRIGHT; @@ -139,19 +142,21 @@ bool assignBondDirs(RWMol& mol, INT_PAIR_VECT& zBondPairs, Bond::BondDir _dir = _ == 0 ? dir : otherDir; BOOST_FOREACH (pair, *_rules) { int other = -1; - if (pair.first == curBondIdx) + if (pair.first == curBondIdx) { other = pair.second; - else if (pair.second == curBondIdx) + } else if (pair.second == curBondIdx) { other = pair.first; + } // a match? if (other != curBondIdx && other != -1) { Bond* otherBond = mol.getBondWithIdx(other); // check if it is assigned if (otherBond->getBondDir() != Bond::NONE) { // assigned. check conflict - if (otherBond->getBondDir() != _dir) + if (otherBond->getBondDir() != _dir) { // not doable return false; + } } else { // not assigned, then add to queue queue.push(std::make_pair(otherBond->getIdx(), _dir)); @@ -208,9 +213,11 @@ Atom* findAlternatingBonds( unsigned int currentPathLength, unsigned int maxPathLength, Bond* lastBond, /*OUT*/ std::stack& path, std::set& _visited) { // memory for what has been visited - if (lastBond == NULL) { + if (lastBond == nullptr) { _visited.clear(); - while (!path.empty()) path.pop(); + while (!path.empty()) { + path.pop(); + } } _visited.insert(current->getIdx()); @@ -227,25 +234,27 @@ Atom* findAlternatingBonds( // Yes! But am I better than the existing one - if one exists? if (path.size() == 0 || path.size() > currentPathLength) { // Yes! clear the path and repopulate it - while (!path.empty()) path.pop(); + while (!path.empty()) { + path.pop(); + } // add myself to the path path.push(lastBond); return current; } else { // I am no better than the existing one. This will also cause the // path search to not continue down - return NULL; + return nullptr; } } // searching too far? if (maxPathLength <= currentPathLength) { - return NULL; + return nullptr; } // continue searching down RWMol::ADJ_ITER nid, end; - Atom *target = NULL, *temp; + Atom *target = nullptr, *temp; for (boost::tie(nid, end) = mol.getAtomNeighbors(current); nid != end; nid++) { if (_visited.find(*nid) != _visited.end()) { @@ -260,12 +269,14 @@ Atom* findAlternatingBonds( // be supported: a TRIPLE bond followed by a SINGLE bond // This is used in _Valence5NCleanUp2 Bond::BondType nextBondType = Bond::SINGLE; - if (desiredNextBondType == Bond::SINGLE) nextBondType = Bond::DOUBLE; + if (desiredNextBondType == Bond::SINGLE) { + nextBondType = Bond::DOUBLE; + } if ((temp = findAlternatingBonds( mol, mol.getAtomWithIdx(*nid), desiredAtomicNumber, desiredAtomCharge, nextBondType, desiredEndingBondType, currentPathLength + 1, maxPathLength, bond, path, _visited)) != - NULL) { + nullptr) { target = temp; } } else if (desiredEndingBondType != Bond::SINGLE && @@ -279,17 +290,20 @@ Atom* findAlternatingBonds( desiredAtomCharge, Bond::UNSPECIFIED, /* no next */ desiredEndingBondType, currentPathLength + 1, 0, /* this limits the recursion */ - bond, path, _visited))) + bond, path, _visited))) { target = temp; + } } } // about the return - if (target != NULL) { - if (lastBond) path.push(lastBond); + if (target != nullptr) { + if (lastBond) { + path.push(lastBond); + } return target; } - return NULL; + return nullptr; } int getNumDoubleBondedNegativelyChargedNeighboringSi(ROMol& mol, Atom* a) { @@ -313,13 +327,14 @@ int getNumDoubleBondedNegativelyChargedNeighboringSi(ROMol& mol, Atom* a) { bool _Valence4NCleanUp1(RWMol& mol, Atom* atom) { // replace the N- with Sn if (atom->getAtomicNum() != 7 || atom->getFormalCharge() != -1 || - atom->calcExplicitValence(false) != 4) + atom->calcExplicitValence(false) != 4) { return false; + } atom->setAtomicNum(50); atom->setFormalCharge(0); // substructure matching - RWMol* query = new RWMol(); + auto* query = new RWMol(); query->addAtom(new Atom(6), false, true); // 0 query->addAtom(new Atom(7), false, true); // 1 query->addAtom(new Atom(50), false, true); // 2 @@ -364,9 +379,12 @@ bool _Valence4NCleanUp1(RWMol& mol, Atom* atom) { bool _Valence4NCleanUp2(RWMol& mol, Atom* atom) { std::stack stack; std::set _visited; - Atom* target = findAlternatingBonds( - mol, atom, 7, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 1, NULL, stack, _visited); - if (target == NULL) return false; + Atom* target = + findAlternatingBonds(mol, atom, 7, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 1, + nullptr, stack, _visited); + if (target == nullptr) { + return false; + } stack.top()->setBondType(Bond::SINGLE); atom->setFormalCharge(0); @@ -378,16 +396,20 @@ bool _Valence4NCleanUp2(RWMol& mol, Atom* atom) { bool _Valence5NCleanUp1(RWMol& mol, Atom* atom) { std::stack stack; std::set _visited; - Atom* target = findAlternatingBonds( - mol, atom, 7, 1, Bond::DOUBLE, Bond::DOUBLE, 0, 5, NULL, stack, _visited); - if (target == NULL) return false; + Atom* target = + findAlternatingBonds(mol, atom, 7, 1, Bond::DOUBLE, Bond::DOUBLE, 0, 5, + nullptr, stack, _visited); + if (target == nullptr) { + return false; + } target->setFormalCharge(0); target->calcExplicitValence(false); while (!stack.empty()) { - if (stack.top()->getBondType() == Bond::DOUBLE) + if (stack.top()->getBondType() == Bond::DOUBLE) { stack.top()->setBondType(Bond::SINGLE); - else + } else { stack.top()->setBondType(Bond::DOUBLE); + } stack.pop(); } atom->setFormalCharge(1); @@ -400,8 +422,10 @@ bool _Valence5NCleanUp2(RWMol& mol, Atom* atom) { std::set _visited; Atom* target = findAlternatingBonds(mol, atom, 7, -1, Bond::TRIPLE, Bond::SINGLE, 0, 2, - NULL, stack, _visited); - if (target == NULL) return false; + nullptr, stack, _visited); + if (target == nullptr) { + return false; + } Bond* bond = stack.top(); bond->setBondType(Bond::SINGLE); @@ -422,9 +446,12 @@ bool _Valence5NCleanUp2(RWMol& mol, Atom* atom) { bool _Valence5NCleanUp3(RWMol& mol, Atom* atom) { std::stack stack; std::set _visited; - Atom* target = findAlternatingBonds( - mol, atom, 7, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 1, NULL, stack, _visited); - if (target == NULL) return false; + Atom* target = + findAlternatingBonds(mol, atom, 7, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 1, + nullptr, stack, _visited); + if (target == nullptr) { + return false; + } // we are double bonded to a neighboring N. Check to see if we are also // double bonded to an O. If so, we don't want to mess with the other N @@ -437,8 +464,8 @@ bool _Valence5NCleanUp3(RWMol& mol, Atom* atom) { std::set _visited2; Atom* target2 = findAlternatingBonds(mol, atom, 8, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 1, - NULL, stack2, _visited2); - if (target2 == NULL) { + nullptr, stack2, _visited2); + if (target2 == nullptr) { target->setFormalCharge(-1); target->calcExplicitValence(false); stack.top()->setBondType(Bond::SINGLE); @@ -463,14 +490,18 @@ bool _Valence5NCleanUp4(RWMol& mol, Atom* atom) { Bond* bond = mol.getBondBetweenAtoms(*nid1, thisId); if (nbr->getAtomicNum() == 14 && nbr->getFormalCharge() == -1 && bond->getBondType() == Bond::DOUBLE) { - if (nSi >= 2) return false; + if (nSi >= 2) { + return false; + } nbrs[nSi] = nbr; bonds[nSi] = bond; nSi++; } ++nid1; } - if (nSi != 2) return false; + if (nSi != 2) { + return false; + } nbrs[0]->setFormalCharge(0); nbrs[1]->setFormalCharge(0); bonds[0]->setBondType(Bond::SINGLE); @@ -532,14 +563,16 @@ bool _Valence5NCleanUp5(RWMol& mol, Atom* atom, int atomicNum) { std::set _visited; unchargedOxygen = findAlternatingBonds(mol, atom, atomicNum, 0, Bond::DOUBLE, Bond::DOUBLE, - 0, 7, NULL, stackUncharged, _visited); + 0, 7, nullptr, stackUncharged, _visited); chargedOxygen = findAlternatingBonds(mol, atom, atomicNum, 1, Bond::DOUBLE, Bond::DOUBLE, - 0, 7, NULL, stackCharged, _visited); - if (unchargedOxygen == NULL && chargedOxygen == NULL) return false; + 0, 7, nullptr, stackCharged, _visited); + if (unchargedOxygen == nullptr && chargedOxygen == nullptr) { + return false; + } stack = &stackUncharged; - if (unchargedOxygen == NULL) { + if (unchargedOxygen == nullptr) { stack = &stackCharged; } if (unchargedOxygen && chargedOxygen) { @@ -559,10 +592,11 @@ bool _Valence5NCleanUp5(RWMol& mol, Atom* atom, int atomicNum) { Bond* b; while (!stack->empty()) { b = stack->top(); - if (b->getBondType() == Bond::DOUBLE) + if (b->getBondType() == Bond::DOUBLE) { b->setBondType(Bond::SINGLE); - else + } else { b->setBondType(Bond::DOUBLE); + } stack->pop(); } if (unchargedOxygen && chargedOxygen) { @@ -579,8 +613,12 @@ bool _Valence5NCleanUp5(RWMol& mol, Atom* atom, int atomicNum) { // keeps its hydrogen) chargedOxygen->setFormalCharge(0); } - if (chargedOxygen) chargedOxygen->calcExplicitValence(false); - if (unchargedOxygen) unchargedOxygen->calcExplicitValence(false); + if (chargedOxygen) { + chargedOxygen->calcExplicitValence(false); + } + if (unchargedOxygen) { + unchargedOxygen->calcExplicitValence(false); + } } return true; } @@ -590,12 +628,13 @@ bool _Valence5NCleanUp5(RWMol& mol, Atom* atom, int atomicNum) { bool _Valence5NCleanUp6(RWMol& mol, Atom* atom) { // replace the N with Sn if (atom->getAtomicNum() != 7 || atom->getFormalCharge() != 0 || - atom->calcExplicitValence(false) != 5) + atom->calcExplicitValence(false) != 5) { return false; + } atom->setAtomicNum(50); // substructure matching - RWMol* query = new RWMol(); + auto* query = new RWMol(); query->addAtom(new Atom(6), false, true); // 0 query->addAtom(new Atom(6), false, true); // 1 query->addAtom(new Atom(50), false, true); // 2 @@ -644,17 +683,21 @@ bool _Valence5NCleanUp7(RWMol& mol, Atom* atom) { // is it connected to O via alternating bonds? std::stack stack; std::set _visited; - Atom* target = findAlternatingBonds( - mol, atom, 8, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 5, NULL, stack, _visited); - if (target == NULL) return false; + Atom* target = + findAlternatingBonds(mol, atom, 8, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 5, + nullptr, stack, _visited); + if (target == nullptr) { + return false; + } // replace the N with Sn if (atom->getAtomicNum() != 7 || atom->getFormalCharge() != 0 || - atom->calcExplicitValence(false) != 5) + atom->calcExplicitValence(false) != 5) { return false; + } atom->setAtomicNum(50); // substructure matching - RWMol* query = new RWMol(); + auto* query = new RWMol(); query->addAtom(new Atom(6), false, true); // 0 query->addAtom(new Atom(6), false, true); // 1 query->addAtom(new Atom(50), false, true); // 2 @@ -691,10 +734,11 @@ bool _Valence5NCleanUp7(RWMol& mol, Atom* atom) { Bond* b; while (!stack.empty()) { b = stack.top(); - if (b->getBondType() == Bond::DOUBLE) + if (b->getBondType() == Bond::DOUBLE) { b->setBondType(Bond::SINGLE); - else + } else { b->setBondType(Bond::DOUBLE); + } stack.pop(); } // set charge on oxygen @@ -709,12 +753,13 @@ bool _Valence5NCleanUp7(RWMol& mol, Atom* atom) { bool _Valence5NCleanUp8(RWMol& mol, Atom* atom) { // replace the N with Sn if (atom->getAtomicNum() != 7 || atom->getFormalCharge() != 0 || - atom->calcExplicitValence(false) != 5) + atom->calcExplicitValence(false) != 5) { return false; + } atom->setAtomicNum(50); // substructure matching - RWMol* query = new RWMol(); + auto* query = new RWMol(); query->addAtom(new Atom(6), false, true); // 0 query->addAtom(new Atom(7), false, true); // 1 query->addAtom(new Atom(6), false, true); // 2 @@ -762,12 +807,13 @@ bool _Valence5NCleanUp8(RWMol& mol, Atom* atom) { bool _Valence5NCleanUp9(RWMol& mol, Atom* atom) { // replace the N with Sn if (atom->getAtomicNum() != 7 || atom->getFormalCharge() != 0 || - atom->calcExplicitValence(false) != 5) + atom->calcExplicitValence(false) != 5) { return false; + } atom->setAtomicNum(50); // substructure matching - RWMol* query = new RWMol(); + auto* query = new RWMol(); query->addAtom(new Atom(6), false, true); // 0 query->addAtom(new Atom(7), false, true); // 1 query->addAtom(new Atom(7), false, true); // 2 @@ -812,10 +858,11 @@ bool _Valence5NCleanUp9(RWMol& mol, Atom* atom) { bool _Valence5NCleanUpA(RWMol& mol, Atom* atom) { // replace the N with Sn if (atom->getAtomicNum() != 7 || atom->getFormalCharge() != 0 || - atom->calcExplicitValence(false) != 5) + atom->calcExplicitValence(false) != 5) { return false; + } // first find the N=N - RWMol* query = new RWMol(); + auto* query = new RWMol(); query->addAtom(new Atom(7), false, true); // 0 query->addAtom(new Atom(7), false, true); // 1 query->addBond(0, 1, Bond::DOUBLE); @@ -824,15 +871,18 @@ bool _Valence5NCleanUpA(RWMol& mol, Atom* atom) { SubstructMatch(mol, *query, fgpMatches); delete query; - if (fgpMatches.size() == 0) return false; + if (fgpMatches.size() == 0) { + return false; + } MatchVectType match; std::stack bestPath; BOOST_FOREACH (match, fgpMatches) { // does the match contains the current atom? if (match[0].second == static_cast(atom->getIdx()) || - match[1].second == static_cast(atom->getIdx())) + match[1].second == static_cast(atom->getIdx())) { continue; + } // set both matched N to Sn mol.getAtomWithIdx(match[0].second)->setAtomicNum(50); mol.getAtomWithIdx(match[1].second)->setAtomicNum(50); @@ -841,9 +891,10 @@ bool _Valence5NCleanUpA(RWMol& mol, Atom* atom) { std::set _visited; Atom* target = findAlternatingBonds(mol, atom, 50, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 9, - NULL, stack, _visited); - if (target && (bestPath.empty() || stack.size() < bestPath.size())) + nullptr, stack, _visited); + if (target && (bestPath.empty() || stack.size() < bestPath.size())) { bestPath = stack; + } mol.getAtomWithIdx(match[0].second)->setAtomicNum(7); mol.getAtomWithIdx(match[1].second)->setAtomicNum(7); } @@ -851,10 +902,11 @@ bool _Valence5NCleanUpA(RWMol& mol, Atom* atom) { if (!bestPath.empty()) { while (!bestPath.empty()) { Bond* bond = bestPath.top(); - if (bond->getBondType() == Bond::SINGLE) + if (bond->getBondType() == Bond::SINGLE) { bond->setBondType(Bond::DOUBLE); - else + } else { bond->setBondType(Bond::SINGLE); + } bestPath.pop(); } atom->setFormalCharge(1); @@ -868,9 +920,12 @@ bool _Valence5NCleanUpA(RWMol& mol, Atom* atom) { bool _Valence5NCleanUpB(RWMol& mol, Atom* atom) { std::stack stack; std::set _visited; - Atom* target = findAlternatingBonds( - mol, atom, 6, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 1, NULL, stack, _visited); - if (target == NULL) return false; + Atom* target = + findAlternatingBonds(mol, atom, 6, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 1, + nullptr, stack, _visited); + if (target == nullptr) { + return false; + } target->setFormalCharge(-1); target->calcExplicitValence(false); @@ -889,8 +944,9 @@ bool _Valence5NCleanUpB(RWMol& mol, Atom* atom) { // CC(C)(C1=CC(S[O-](=O)=O)=[N+](F)C=C1)C bool _Valence7SCleanUp1(RWMol& mol, Atom* atom) { if (atom->getAtomicNum() != 16 || atom->getFormalCharge() != -1 || - atom->calcExplicitValence(false) != 7) + atom->calcExplicitValence(false) != 7) { return false; + } int aid = atom->getIdx(); int neighborsC = 0; int neighborsO = 0; @@ -906,14 +962,14 @@ bool _Valence7SCleanUp1(RWMol& mol, Atom* atom) { nid = nid1; neighborsO++; } - } else if (otherAtom->getAtomicNum() == 6) + } else if (otherAtom->getAtomicNum() == 6) { if (mol.getBondBetweenAtoms(*nid1, aid)->getBondType() != Bond::SINGLE) { neighborsC = 100; break; } else { neighborsC++; } - else { + } else { neighborsC = 100; break; } @@ -935,22 +991,25 @@ bool _Valence7SCleanUp1(RWMol& mol, Atom* atom) { // [S-]=CC#N bool _Valence7SCleanUp2(RWMol& mol, Atom* atom) { if (atom->getAtomicNum() != 16 || atom->getFormalCharge() != -1 || - atom->calcExplicitValence(false) != 7) + atom->calcExplicitValence(false) != 7) { return false; + } std::stack stack; std::set _visited; - Atom* target = findAlternatingBonds( - mol, atom, 7, 0, Bond::DOUBLE, Bond::TRIPLE, 0, 3, NULL, stack, _visited); + Atom* target = + findAlternatingBonds(mol, atom, 7, 0, Bond::DOUBLE, Bond::TRIPLE, 0, 3, + nullptr, stack, _visited); if (target) { while (!stack.empty()) { Bond* bond = stack.top(); - if (bond->getBondType() == Bond::SINGLE) + if (bond->getBondType() == Bond::SINGLE) { bond->setBondType(Bond::DOUBLE); - else if (bond->getBondType() == Bond::DOUBLE) + } else if (bond->getBondType() == Bond::DOUBLE) { bond->setBondType(Bond::SINGLE); - else if (bond->getBondType() == Bond::TRIPLE) + } else if (bond->getBondType() == Bond::TRIPLE) { bond->setBondType(Bond::DOUBLE); + } stack.pop(); } atom->setFormalCharge(0); @@ -964,13 +1023,15 @@ bool _Valence7SCleanUp2(RWMol& mol, Atom* atom) { // S- connected to a N via double bond bool _Valence7SCleanUp3(RWMol& mol, Atom* atom) { if (atom->getAtomicNum() != 16 || atom->getFormalCharge() != -1 || - atom->calcExplicitValence(false) != 7) + atom->calcExplicitValence(false) != 7) { return false; + } std::stack stack; std::set _visited; - Atom* target = findAlternatingBonds( - mol, atom, 7, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 1, NULL, stack, _visited); + Atom* target = + findAlternatingBonds(mol, atom, 7, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 1, + nullptr, stack, _visited); if (target) { stack.top()->setBondType(Bond::SINGLE); target->setFormalCharge(-1); @@ -985,21 +1046,26 @@ bool _Valence7SCleanUp3(RWMol& mol, Atom* atom) { // S- connected to a N via alternating bond bool _Valence8SCleanUp1(RWMol& mol, Atom* atom) { if (atom->getAtomicNum() != 16 || atom->getFormalCharge() != -1 || - atom->calcExplicitValence(false) != 7) + atom->calcExplicitValence(false) != 7) { return false; + } std::stack stack; std::set _visited; - Atom* target = findAlternatingBonds( - mol, atom, 7, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 9, NULL, stack, _visited); + Atom* target = + findAlternatingBonds(mol, atom, 7, 0, Bond::DOUBLE, Bond::DOUBLE, 0, 9, + nullptr, stack, _visited); - if (!target) return false; + if (!target) { + return false; + } while (!stack.empty()) { - if (stack.top()->getBondType() == Bond::DOUBLE) + if (stack.top()->getBondType() == Bond::DOUBLE) { stack.top()->setBondType(Bond::SINGLE); - else + } else { stack.top()->setBondType(Bond::DOUBLE); + } stack.pop(); } target->setFormalCharge(-1); @@ -1014,8 +1080,9 @@ bool _Valence8SCleanUp1(RWMol& mol, Atom* atom) { // to: // [Cl+3]([O-])([O-])([O-])[O-] bool _Valence8ClCleanUp1(RWMol& mol, Atom* atom) { - if (atom->calcExplicitValence(false) != 8 || atom->getFormalCharge() != -1) + if (atom->calcExplicitValence(false) != 8 || atom->getFormalCharge() != -1) { return false; + } int aid = atom->getIdx(); bool neighborsAllO = true; RWMol::ADJ_ITER nid1, end1; @@ -1048,14 +1115,17 @@ bool _Valence8ClCleanUp1(RWMol& mol, Atom* atom) { // [Cl+][O-] to Cl=O bool _Valence5ClCleanUp1(RWMol& mol, Atom* atom) { - if (atom->calcExplicitValence(false) != 6 || atom->getFormalCharge() != 1) + if (atom->calcExplicitValence(false) != 6 || atom->getFormalCharge() != 1) { return false; + } std::stack stack; std::set _visited; Atom* target = findAlternatingBonds(mol, atom, 8, -1, Bond::SINGLE, Bond::SINGLE, 0, 1, - NULL, stack, _visited); - if (!target) return false; + nullptr, stack, _visited); + if (!target) { + return false; + } stack.top()->setBondType(Bond::DOUBLE); atom->setFormalCharge(0); target->setFormalCharge(0); @@ -1065,14 +1135,17 @@ bool _Valence5ClCleanUp1(RWMol& mol, Atom* atom) { // // Cl#S to ClS bool _Valence3ClCleanUp1(RWMol& mol, Atom* atom) { - if (atom->calcExplicitValence(false) != 3 || atom->getFormalCharge() != 0) + if (atom->calcExplicitValence(false) != 3 || atom->getFormalCharge() != 0) { return false; + } std::stack stack; std::set _visited; Atom* target = findAlternatingBonds(mol, atom, 16, 0, Bond::TRIPLE, Bond::TRIPLE, 0, 1, - NULL, stack, _visited); - if (!target) return false; + nullptr, stack, _visited); + if (!target) { + return false; + } stack.top()->setBondType(Bond::SINGLE); atom->calcExplicitValence(false); return true; @@ -1085,9 +1158,13 @@ void cleanUp(RWMol& mol) { switch ((*ai)->getAtomicNum()) { case 7: if ((*ai)->calcExplicitValence(false) == 4) { - if (_Valence4NCleanUp1(mol, *ai)) continue; + if (_Valence4NCleanUp1(mol, *ai)) { + continue; + } if ((*ai)->getFormalCharge() == -1) { - if (_Valence4NCleanUp2(mol, *ai)) continue; + if (_Valence4NCleanUp2(mol, *ai)) { + continue; + } } continue; } @@ -1123,24 +1200,35 @@ void cleanUp(RWMol& mol) { // last resort (_Valence5NCleanUpB(mol, *ai)); } - if (aromHolder) (*ai)->setIsAromatic(1); + if (aromHolder) { + (*ai)->setIsAromatic(1); + } break; case 17: if ((*ai)->calcExplicitValence(false) == 8 && - _Valence8ClCleanUp1(mol, *ai)) + _Valence8ClCleanUp1(mol, *ai)) { continue; + } if ((*ai)->calcExplicitValence(false) == 5 && - _Valence5ClCleanUp1(mol, *ai)) + _Valence5ClCleanUp1(mol, *ai)) { continue; + } if ((*ai)->calcExplicitValence(false) == 3 && - _Valence3ClCleanUp1(mol, *ai)) + _Valence3ClCleanUp1(mol, *ai)) { continue; + } break; case 16: if ((*ai)->calcExplicitValence(false) == 7) { - if (_Valence7SCleanUp1(mol, *ai)) continue; - if (_Valence7SCleanUp2(mol, *ai)) continue; - if (_Valence7SCleanUp3(mol, *ai)) continue; + if (_Valence7SCleanUp1(mol, *ai)) { + continue; + } + if (_Valence7SCleanUp2(mol, *ai)) { + continue; + } + if (_Valence7SCleanUp3(mol, *ai)) { + continue; + } _Valence8SCleanUp1(mol, *ai); } else if ((*ai)->calcExplicitValence(false) == 8) { _Valence8SCleanUp1(mol, *ai); @@ -1181,7 +1269,7 @@ RWMol* InchiToMol(const std::string& inchi, ExtraInchiReturnValues& rv, inchiInput.szOptions = options; // creating RWMol for return - RWMol* m = NULL; + RWMol* m = nullptr; { // output structure inchi_OutputStruct inchiOutput; @@ -1193,9 +1281,12 @@ RWMol* InchiToMol(const std::string& inchi, ExtraInchiReturnValues& rv, // prepare output rv.returnCode = retcode; - if (inchiOutput.szMessage) + if (inchiOutput.szMessage) { rv.messagePtr = std::string(inchiOutput.szMessage); - if (inchiOutput.szLog) rv.logPtr = std::string(inchiOutput.szLog); + } + if (inchiOutput.szLog) { + rv.logPtr = std::string(inchiOutput.szLog); + } // for isotopes of H typedef std::vector> @@ -1217,7 +1308,9 @@ RWMol* InchiToMol(const std::string& inchi, ExtraInchiReturnValues& rv, if (inchiAtom->isotopic_mass) { isotope = inchiAtom->isotopic_mass - ISOTOPIC_SHIFT_FLAG; } - if (isotope) atom->setIsotope(isotope + refWeight); + if (isotope) { + atom->setIsotope(isotope + refWeight); + } // set charge atom->setFormalCharge(inchiAtom->charge); // set radical @@ -1267,11 +1360,11 @@ RWMol* InchiToMol(const std::string& inchi, ExtraInchiReturnValues& rv, continue; } bondRegister.insert(std::make_pair(i, nbr)); - Bond* bond = NULL; + Bond* bond = nullptr; // bond type - if (inchiAtom->bond_type[b] <= INCHI_BOND_TYPE_TRIPLE) + if (inchiAtom->bond_type[b] <= INCHI_BOND_TYPE_TRIPLE) { bond = new Bond((Bond::BondType)inchiAtom->bond_type[b]); - else { + } else { BOOST_LOG(rdWarningLog) << "receive ALTERN bond type which should be avoided. " << "This is treated as aromatic." << std::endl; @@ -1315,10 +1408,9 @@ RWMol* InchiToMol(const std::string& inchi, ExtraInchiReturnValues& rv, } // adding isotopes at the end - for (ISOTOPES_t::iterator ii = isotopes.begin(); ii != isotopes.end(); - ii++) { + for (auto& ii : isotopes) { unsigned int isotope, aid, repeat; - boost::tie(isotope, aid, repeat) = *ii; + boost::tie(isotope, aid, repeat) = ii; aid = indexToAtomIndexMapping[aid]; for (unsigned int i = 0; i < repeat; i++) { // create atom @@ -1350,8 +1442,9 @@ RWMol* InchiToMol(const std::string& inchi, ExtraInchiReturnValues& rv, for (unsigned int i = 0; i < numStereo0D; i++) { inchi_Stereo0D* stereo0DPtr = inchiOutput.stereo0D + i; if (stereo0DPtr->parity == INCHI_PARITY_NONE || - stereo0DPtr->parity == INCHI_PARITY_UNDEFINED) + stereo0DPtr->parity == INCHI_PARITY_UNDEFINED) { continue; + } switch (stereo0DPtr->type) { case INCHI_StereoType_None: break; @@ -1395,7 +1488,9 @@ RWMol* InchiToMol(const std::string& inchi, ExtraInchiReturnValues& rv, while (begin != end) { if (*begin != right) { if ((_cip = ranks[*begin]) > cip) { - if (leftNbr >= 0) extraLeftNbr = leftNbr; + if (leftNbr >= 0) { + extraLeftNbr = leftNbr; + } leftNbr = *begin; cip = _cip; } else { @@ -1410,7 +1505,9 @@ RWMol* InchiToMol(const std::string& inchi, ExtraInchiReturnValues& rv, while (begin != end) { if (*begin != left) { if ((_cip = ranks[*begin]) > cip) { - if (rightNbr >= 0) extraRightNbr = rightNbr; + if (rightNbr >= 0) { + extraRightNbr = rightNbr; + } rightNbr = *begin; cip = _cip; } else { @@ -1422,65 +1519,84 @@ RWMol* InchiToMol(const std::string& inchi, ExtraInchiReturnValues& rv, bool switchEZ = false; if ((originalLeftNbr == leftNbr && originalRightNbr != rightNbr) || - (originalLeftNbr != leftNbr && originalRightNbr == rightNbr)) + (originalLeftNbr != leftNbr && + originalRightNbr == rightNbr)) { switchEZ = true; + } char parity = stereo0DPtr->parity; - if (parity == INCHI_PARITY_ODD && switchEZ) + if (parity == INCHI_PARITY_ODD && switchEZ) { parity = INCHI_PARITY_EVEN; - else if (parity == INCHI_PARITY_EVEN && switchEZ) + } else if (parity == INCHI_PARITY_EVEN && switchEZ) { parity = INCHI_PARITY_ODD; + } Bond* leftBond = m->getBondBetweenAtoms(left, leftNbr); Bond* rightBond = m->getBondBetweenAtoms(right, rightNbr); if (extraLeftNbr >= 0) { int modifier = -1; // modifier to track whether bond is reversed - if (leftBond->getBeginAtomIdx() != left) modifier *= -1; + if (leftBond->getBeginAtomIdx() != left) { + modifier *= -1; + } Bond* extraLeftBond = m->getBondBetweenAtoms(left, extraLeftNbr); - if (extraLeftBond->getBeginAtomIdx() != left) modifier *= -1; - if (modifier == 1) + if (extraLeftBond->getBeginAtomIdx() != left) { + modifier *= -1; + } + if (modifier == 1) { zBondPairs.push_back(std::make_pair(leftBond->getIdx(), extraLeftBond->getIdx())); - else + } else { eBondPairs.push_back(std::make_pair(leftBond->getIdx(), extraLeftBond->getIdx())); + } } if (extraRightNbr >= 0) { int modifier = -1; // modifier to track whether bond is reversed Bond* extraRightBond = m->getBondBetweenAtoms(right, extraRightNbr); - if (rightBond->getBeginAtomIdx() != right) modifier *= -1; - if (extraRightBond->getBeginAtomIdx() != right) modifier *= -1; - if (modifier == 1) + if (rightBond->getBeginAtomIdx() != right) { + modifier *= -1; + } + if (extraRightBond->getBeginAtomIdx() != right) { + modifier *= -1; + } + if (modifier == 1) { zBondPairs.push_back(std::make_pair( rightBond->getIdx(), extraRightBond->getIdx())); - else + } else { eBondPairs.push_back(std::make_pair( rightBond->getIdx(), extraRightBond->getIdx())); + } } int modifier = -1; // modifier to track whether bond is reversed - if (leftBond->getBeginAtomIdx() != left) modifier *= -1; - if (rightBond->getBeginAtomIdx() != right) modifier *= -1; + if (leftBond->getBeginAtomIdx() != left) { + modifier *= -1; + } + if (rightBond->getBeginAtomIdx() != right) { + modifier *= -1; + } if (parity == INCHI_PARITY_ODD) { bond->setStereo(Bond::STEREOZ); - if (modifier == 1) + if (modifier == 1) { eBondPairs.push_back( std::make_pair(leftBond->getIdx(), rightBond->getIdx())); - else + } else { zBondPairs.push_back( std::make_pair(leftBond->getIdx(), rightBond->getIdx())); + } } else if (parity == INCHI_PARITY_EVEN) { bond->setStereo(Bond::STEREOE); - if (modifier == 1) + if (modifier == 1) { zBondPairs.push_back( std::make_pair(leftBond->getIdx(), rightBond->getIdx())); - else + } else { eBondPairs.push_back( std::make_pair(leftBond->getIdx(), rightBond->getIdx())); + } } else if (parity == INCHI_PARITY_NONE) { bond->setStereo(Bond::STEREONONE); } else { @@ -1578,12 +1694,17 @@ void fixOptionSymbol(const char* in, char* out) { unsigned int i; for (i = 0; i < strlen(in); i++) { #ifdef _WIN32 - if (in[i] == '-') out[i] = '/'; + if (in[i] == '-') { + out[i] = '/'; + #else - if (in[i] == '/') out[i] = '-'; + if (in[i] == '/') { + out[i] = '-'; + #endif - else + } else { out[i] = in[i]; + } } out[i] = '\0'; } @@ -1595,32 +1716,40 @@ void rCleanUp(RWMol& mol) { SubstructMatch(mol, *q, fgpMatches); delete q; // replace all matches - for (unsigned int match_id = 0; match_id < fgpMatches.size(); match_id++) { + for (auto match : fgpMatches) { // collect matching atoms int map[5]; - MatchVectType match = fgpMatches[match_id]; for (MatchVectType::const_iterator mi = match.begin(); mi != match.end(); mi++) { map[mi->first] = mi->second; } // check charges - if (mol.getAtomWithIdx(map[1])->getFormalCharge() != 3) return; + if (mol.getAtomWithIdx(map[1])->getFormalCharge() != 3) { + return; + } int unchargedFound = -1; for (int i = 0; i < 5; i++) { - if (i == 1) continue; + if (i == 1) { + continue; + } Atom* o = mol.getAtomWithIdx(map[i]); if (o->getFormalCharge() == 0) { - if (unchargedFound != -1) + if (unchargedFound != -1) { return; // too many uncharged oxygen - else + } else { unchargedFound = i; + } } } // flip bonds and remove charges for (int i = 0; i < 5; i++) { - if (i == 1) continue; - if (i == unchargedFound) continue; + if (i == 1) { + continue; + } + if (i == unchargedFound) { + continue; + } if (unchargedFound == -1 && i == 0) { mol.getBondBetweenAtoms(map[1], map[i])->setBondType(Bond::SINGLE); mol.getAtomWithIdx(map[i])->setFormalCharge(-1); @@ -1636,7 +1765,7 @@ void rCleanUp(RWMol& mol) { std::string MolToInchi(const ROMol& mol, ExtraInchiReturnValues& rv, const char* options) { - RWMol* m = new RWMol(mol); + auto* m = new RWMol(mol); // assign stereochem: if (mol.needsUpdatePropertyCache()) { @@ -1652,7 +1781,7 @@ std::string MolToInchi(const ROMol& mol, ExtraInchiReturnValues& rv, unsigned int nBonds = m->getNumBonds(); // Make array of inchi_atom (storage space) - inchi_Atom* inchiAtoms = new inchi_Atom[nAtoms]; + auto* inchiAtoms = new inchi_Atom[nAtoms]; // and a vector for stereo0D std::vector stereo0DEntries; @@ -1668,7 +1797,7 @@ std::string MolToInchi(const ROMol& mol, ExtraInchiReturnValues& rv, inchiAtoms[i].y = 0; inchiAtoms[i].z = 0; } else { - ROMol::ConformerIterator conformerIter = m->beginConformers(); + auto conformerIter = m->beginConformers(); RDGeom::Point3D coord = (*conformerIter)->getAtomPos(i); inchiAtoms[i].x = coord[0]; inchiAtoms[i].y = coord[1]; @@ -1682,11 +1811,11 @@ std::string MolToInchi(const ROMol& mol, ExtraInchiReturnValues& rv, // isotopes int isotope = atom->getIsotope(); - if (isotope) + if (isotope) { inchiAtoms[i].isotopic_mass = ISOTOPIC_SHIFT_FLAG + isotope - static_cast(periodicTable->getAtomicWeight(atomicNumber) + 0.5); - else { + } else { // check explicit iso property. If this is set, we have a 0 offset // Example: CHEMBL220875 // if (atom->getIsotope()){ @@ -1700,10 +1829,11 @@ std::string MolToInchi(const ROMol& mol, ExtraInchiReturnValues& rv, inchiAtoms[i].charge = atom->getFormalCharge(); // radical - if (atom->getNumRadicalElectrons()) + if (atom->getNumRadicalElectrons()) { inchiAtoms[i].radical = atom->getNumRadicalElectrons() + 1; - else + } else { inchiAtoms[i].radical = 0; + } // number of iso H inchiAtoms[i].num_iso_H[0] = -1; @@ -1716,7 +1846,9 @@ std::string MolToInchi(const ROMol& mol, ExtraInchiReturnValues& rv, atom->hasProp("molParity")) { // we ignore the molParity if the number of neighbors are below 3 atom->calcImplicitValence(); - if (atom->getNumImplicitHs() + atom->getDegree() < 3) continue; + if (atom->getNumImplicitHs() + atom->getDegree() < 3) { + continue; + } inchi_Stereo0D stereo0D; stereo0D.central_atom = i; stereo0D.type = INCHI_StereoType_Tetrahedral; @@ -1878,16 +2010,18 @@ std::string MolToInchi(const ROMol& mol, ExtraInchiReturnValues& rv, bond->getStereoAtoms().size() >= 2) { inchi_Stereo0D stereo0D; if (bond->getStereo() == Bond::STEREOZ || - bond->getStereo() == Bond::STEREOCIS) + bond->getStereo() == Bond::STEREOCIS) { stereo0D.parity = INCHI_PARITY_ODD; - else + } else { stereo0D.parity = INCHI_PARITY_EVEN; + } stereo0D.neighbor[0] = bond->getStereoAtoms()[0]; stereo0D.neighbor[3] = bond->getStereoAtoms()[1]; stereo0D.neighbor[1] = atomIndex1; stereo0D.neighbor[2] = atomIndex2; - if (!m->getBondBetweenAtoms(stereo0D.neighbor[0], stereo0D.neighbor[1])) + if (!m->getBondBetweenAtoms(stereo0D.neighbor[0], stereo0D.neighbor[1])) { std::swap(stereo0D.neighbor[0], stereo0D.neighbor[3]); + } stereo0D.central_atom = NO_ATOM; stereo0D.type = INCHI_StereoType_DoubleBond; stereo0DEntries.push_back(stereo0D); @@ -1914,7 +2048,7 @@ std::string MolToInchi(const ROMol& mol, ExtraInchiReturnValues& rv, stereo0Ds[i] = stereo0DEntries[i]; } } else { - stereo0Ds = NULL; + stereo0Ds = nullptr; } // create input @@ -1926,7 +2060,7 @@ std::string MolToInchi(const ROMol& mol, ExtraInchiReturnValues& rv, fixOptionSymbol(options, _options); input.szOptions = _options; } else { - input.szOptions = NULL; + input.szOptions = nullptr; } input.num_atoms = nAtoms; input.num_stereo0D = stereo0DEntries.size(); @@ -1944,18 +2078,30 @@ std::string MolToInchi(const ROMol& mol, ExtraInchiReturnValues& rv, // generate output rv.returnCode = retcode; - if (output.szInChI) inchi = std::string(output.szInChI); - if (output.szMessage) rv.messagePtr = std::string(output.szMessage); - if (output.szLog) rv.logPtr = std::string(output.szLog); - if (output.szAuxInfo) rv.auxInfoPtr = std::string(output.szAuxInfo); + if (output.szInChI) { + inchi = std::string(output.szInChI); + } + if (output.szMessage) { + rv.messagePtr = std::string(output.szMessage); + } + if (output.szLog) { + rv.logPtr = std::string(output.szLog); + } + if (output.szAuxInfo) { + rv.auxInfoPtr = std::string(output.szAuxInfo); + } // clean up FreeINCHI(&output); } - if (input.szOptions) delete[] input.szOptions; + if (input.szOptions) { + delete[] input.szOptions; + } delete[] inchiAtoms; - if (stereo0Ds) delete[] stereo0Ds; + if (stereo0Ds) { + delete[] stereo0Ds; + } delete m; return inchi; } @@ -1982,10 +2128,18 @@ std::string MolBlockToInchi(const std::string& molBlock, // generate output rv.returnCode = retcode; - if (output.szInChI) inchi = std::string(output.szInChI); - if (output.szMessage) rv.messagePtr = std::string(output.szMessage); - if (output.szLog) rv.logPtr = std::string(output.szLog); - if (output.szAuxInfo) rv.auxInfoPtr = std::string(output.szAuxInfo); + if (output.szInChI) { + inchi = std::string(output.szInChI); + } + if (output.szMessage) { + rv.messagePtr = std::string(output.szMessage); + } + if (output.szLog) { + rv.logPtr = std::string(output.szLog); + } + if (output.szAuxInfo) { + rv.auxInfoPtr = std::string(output.szAuxInfo); + } // clean up FreeINCHI(&output); diff --git a/External/INCHI-API/test.cpp b/External/INCHI-API/test.cpp index 8895449fb..79d443253 100644 --- a/External/INCHI-API/test.cpp +++ b/External/INCHI-API/test.cpp @@ -33,7 +33,9 @@ void runblock(const std::vector &mols, unsigned int count, const std::vector &keys) { for (unsigned int j = 0; j < 200; j++) { for (unsigned int i = 0; i < mols.size(); ++i) { - if (i % count != idx) continue; + if (i % count != idx) { + continue; + } ROMol *mol = mols[i]; ExtraInchiReturnValues tmp; std::string inchi = MolToInchi(*mol, tmp); @@ -65,13 +67,15 @@ void testMultiThread() { std::cerr << "reading molecules" << std::endl; std::vector mols; while (!suppl.atEnd() && mols.size() < 100) { - ROMol *mol = 0; + ROMol *mol = nullptr; try { mol = suppl.next(); } catch (...) { continue; } - if (!mol) continue; + if (!mol) { + continue; + } mols.push_back(mol); } std::cerr << "generating reference data" << std::endl; @@ -98,7 +102,9 @@ void testMultiThread() { fut.get(); } - for (unsigned int i = 0; i < mols.size(); ++i) delete mols[i]; + for (auto &mol : mols) { + delete mol; + } BOOST_LOG(rdErrorLog) << " done" << std::endl; } @@ -116,7 +122,7 @@ void testGithubIssue3() { { std::string fName = getenv("RDBASE"); fName += "/External/INCHI-API/test_data/github3.mol"; - ROMol *m = static_cast(MolFileToMol(fName)); + auto *m = static_cast(MolFileToMol(fName)); TEST_ASSERT(m); std::string smi = MolToSmiles(*m, true); TEST_ASSERT(smi == "CNC[C@H](O)[C@@H](O)[C@H](O)[C@H](O)CO"); @@ -128,7 +134,7 @@ void testGithubIssue3() { "h4-13H,2-3H2,1H3/t4-,5+,6+,7+/m0/s1"); // blow out the stereo information with a copy: - RWMol *m2 = new RWMol(*m); + auto *m2 = new RWMol(*m); m2->clearComputedProps(); MolOps::sanitizeMol(*m2); @@ -151,7 +157,7 @@ void testGithubIssue8() { { std::string fName = getenv("RDBASE"); fName += "/External/INCHI-API/test_data/github8_extra.mol"; - ROMol *m = static_cast(MolFileToMol(fName, true, false)); + auto *m = static_cast(MolFileToMol(fName, true, false)); TEST_ASSERT(m); ExtraInchiReturnValues tmp; @@ -270,7 +276,7 @@ void testGithubIssue296() { { std::string fName = getenv("RDBASE"); fName += "/External/INCHI-API/test_data/github296.mol"; - ROMol *m = static_cast(MolFileToMol(fName)); + auto *m = static_cast(MolFileToMol(fName)); TEST_ASSERT(m); ExtraInchiReturnValues tmp; std::string inchi = MolToInchi(*m, tmp); diff --git a/External/YAeHMOP/EHTTools.cpp b/External/YAeHMOP/EHTTools.cpp index 5e3ff9ce3..fcaea63a7 100644 --- a/External/YAeHMOP/EHTTools.cpp +++ b/External/YAeHMOP/EHTTools.cpp @@ -95,7 +95,7 @@ bool runMol(const ROMol &mol, EHTResults &results, int confId) { } } - fill_atomic_parms(unit_cell->atoms, unit_cell->num_atoms, NULL, + fill_atomic_parms(unit_cell->atoms, unit_cell->num_atoms, nullptr, const_cast(parmFilePtr)); unit_cell->num_raw_atoms = unit_cell->num_atoms; charge_to_num_electrons(unit_cell); diff --git a/External/YAeHMOP/Wrap/rdEHTTools.cpp b/External/YAeHMOP/Wrap/rdEHTTools.cpp index e0a048a31..c90a99b31 100644 --- a/External/YAeHMOP/Wrap/rdEHTTools.cpp +++ b/External/YAeHMOP/Wrap/rdEHTTools.cpp @@ -47,12 +47,14 @@ boost::python::object transfer_to_python(T *t) { } PyObject *getMatrixProp(const double *mat, unsigned int dim1, unsigned int dim2) { - if (!mat) throw_value_error("matrix has not be initialized"); + if (!mat) { + throw_value_error("matrix has not be initialized"); + } npy_intp dims[2]; dims[0] = dim1; dims[1] = dim2; - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); + auto *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE); memcpy(PyArray_DATA(res), static_cast(mat), dim1 * dim2 * sizeof(double)); @@ -60,11 +62,13 @@ PyObject *getMatrixProp(const double *mat, unsigned int dim1, unsigned int dim2) return PyArray_Return(res); } PyObject *getSymmMatrixProp(const double *mat, unsigned int sz) { - if (!mat) throw_value_error("matrix has not be initialized"); + if (!mat) { + throw_value_error("matrix has not be initialized"); + } npy_intp dims[1]; dims[0] = sz * (sz + 1) / 2; - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(1, dims, NPY_DOUBLE); + auto *res = (PyArrayObject *)PyArray_SimpleNew(1, dims, NPY_DOUBLE); memcpy(PyArray_DATA(res), static_cast(mat), dims[0] * sizeof(double)); @@ -72,11 +76,13 @@ PyObject *getSymmMatrixProp(const double *mat, unsigned int sz) { return PyArray_Return(res); } PyObject *getVectorProp(const double *mat, unsigned int sz) { - if (!mat) throw_value_error("vector has not be initialized"); + if (!mat) { + throw_value_error("vector has not be initialized"); + } npy_intp dims[1]; dims[0] = sz; - PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(1, dims, NPY_DOUBLE); + auto *res = (PyArrayObject *)PyArray_SimpleNew(1, dims, NPY_DOUBLE); memcpy(PyArray_DATA(res), static_cast(mat), sz * sizeof(double));