diff --git a/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp b/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp index ba1c0e76c..a61652679 100644 --- a/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp +++ b/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp @@ -168,8 +168,7 @@ PyObject *getEuclideanDistMat(python::object descripMat) { // we have probably have a list or a tuple unsigned int ncols = 0; - unsigned int nrows = - python::extract(descripMat.attr("__len__")()); + unsigned int nrows = boost::python::len(descripMat); CHECK_INVARIANT(nrows > 0, "Empty list passed in"); npy_intp dMatLen = nrows * (nrows - 1) / 2; @@ -204,7 +203,7 @@ PyObject *getEuclideanDistMat(python::object descripMat) { PyObject *getTanimotoDistMat(python::object bitVectList) { // we will assume here that we have a either a list of ExplicitBitVectors or // SparseBitVects - int nrows = python::extract(bitVectList.attr("__len__")()); + unsigned int nrows = boost::python::len(bitVectList); CHECK_INVARIANT(nrows > 1, ""); // First check what type of vector we have @@ -239,7 +238,7 @@ PyObject *getTanimotoDistMat(python::object bitVectList) { PyObject *getTanimotoSimMat(python::object bitVectList) { // we will assume here that we have a either a list of ExplicitBitVectors or // SparseBitVects - int nrows = python::extract(bitVectList.attr("__len__")()); + unsigned int nrows = boost::python::len(bitVectList); CHECK_INVARIANT(nrows > 1, ""); // First check what type of vector we have diff --git a/Code/DataStructs/Wrap/SparseIntVect.cpp b/Code/DataStructs/Wrap/SparseIntVect.cpp index 718a16b5e..c08423339 100644 --- a/Code/DataStructs/Wrap/SparseIntVect.cpp +++ b/Code/DataStructs/Wrap/SparseIntVect.cpp @@ -71,7 +71,7 @@ python::list pyToList(SparseIntVect &vect) { template python::list BulkDice(const T &siv1, python::list sivs, bool returnDistance) { python::list res; - unsigned int nsivs = python::extract(sivs.attr("__len__")()); + unsigned int nsivs = python::len(sivs); for (unsigned int i = 0; i < nsivs; ++i) { double simVal; const T *siv2 = python::extract(sivs[i])(); @@ -84,7 +84,7 @@ template python::list BulkTanimoto(const T &siv1, python::list sivs, bool returnDistance) { python::list res; - unsigned int nsivs = python::extract(sivs.attr("__len__")()); + unsigned int nsivs = python::len(sivs); for (unsigned int i = 0; i < nsivs; ++i) { double simVal; const T *siv2 = python::extract(sivs[i])(); @@ -98,7 +98,7 @@ template python::list BulkTversky(const T &siv1, python::list sivs, double a, double b, bool returnDistance) { python::list res; - unsigned int nsivs = python::extract(sivs.attr("__len__")()); + unsigned int nsivs = python::len(sivs); for (unsigned int i = 0; i < nsivs; ++i) { double simVal; const T *siv2 = python::extract(sivs[i])(); diff --git a/Code/DataStructs/Wrap/wrap_BitOps.cpp b/Code/DataStructs/Wrap/wrap_BitOps.cpp index a87bdbeae..cd1280597 100644 --- a/Code/DataStructs/Wrap/wrap_BitOps.cpp +++ b/Code/DataStructs/Wrap/wrap_BitOps.cpp @@ -44,8 +44,8 @@ template python::list NeighborWrapper(python::object queries, python::object bvs, double (*metric)(const T &, const T &)) { python::list res; - unsigned int nbvs = python::extract(bvs.attr("__len__")()); - unsigned int nqs = python::extract(queries.attr("__len__")()); + unsigned int nbvs = python::len(bvs); + unsigned int nqs = python::len(queries); for (unsigned int i = 0; i < nqs; ++i) { const T *bv1 = python::extract(queries[i])(); double closest = -1; @@ -68,7 +68,7 @@ python::list BulkWrapper(const T *bv1, python::object bvs, double (*metric)(const T &, const T &), bool returnDistance) { python::list res; - unsigned int nbvs = python::extract(bvs.attr("__len__")()); + unsigned int nbvs = python::len(bvs); for (unsigned int i = 0; i < nbvs; ++i) { const T *bv2 = python::extract(bvs[i])(); auto sim = metric(*bv1, *bv2); @@ -85,7 +85,7 @@ python::list BulkWrapper(const T *bv1, python::object bvs, double a, double b, double (*metric)(const T &, const T &, double, double), bool returnDistance) { python::list res; - unsigned int nbvs = python::extract(bvs.attr("__len__")()); + unsigned int nbvs = python::len(bvs); for (unsigned int i = 0; i < nbvs; ++i) { const T *bv2 = python::extract(bvs[i])(); auto sim = metric(*bv1, *bv2, a, b); @@ -156,12 +156,12 @@ python::list BulkTverskySimilarity(const T *bv1, python::object bvs, double a, (python::args("v1"), python::args("v2")), _help_); \ python::def( \ #_bulkname_, \ - (python::list(*)(const EBV *, python::object, bool))_bulkname_, \ + (python::list (*)(const EBV *, python::object, bool))_bulkname_, \ (python::args("v1"), python::args("v2"), \ python::args("returnDistance") = 0)); \ python::def( \ #_bulkname_, \ - (python::list(*)(const EBV *, python::object, bool))_bulkname_, \ + (python::list (*)(const EBV *, python::object, bool))_bulkname_, \ (python::args("v1"), python::args("v2"), \ python::args("returnDistance") = 0), \ _help_); \ @@ -189,21 +189,21 @@ python::list BulkTverskySimilarity(const T *bv1, python::object bvs, double a, _help_); \ python::def( \ #_bulkname_, \ - (python::list(*)(const SBV *, python::object, bool))_bulkname_, \ + (python::list (*)(const SBV *, python::object, bool))_bulkname_, \ (python::args("bv1"), python::args("bvList"), \ python::args("returnDistance") = 0)); \ python::def( \ #_bulkname_, \ - (python::list(*)(const EBV *, python::object, bool))_bulkname_, \ + (python::list (*)(const EBV *, python::object, bool))_bulkname_, \ (python::args("bv1"), python::args("bvList"), \ python::args("returnDistance") = 0), \ _help_); \ python::def(#_funcname_ "Neighbors", \ - (python::list(*)(python::object, python::object)) \ + (python::list (*)(python::object, python::object)) \ _funcname_##Neighbors, \ (python::args("bvqueries"), python::args("bvList")), _help_); \ python::def(#_funcname_ "Neighbors_sparse", \ - (python::list(*)(python::object, python::object)) \ + (python::list (*)(python::object, python::object)) \ _funcname_##Neighbors, \ (python::args("bvqueries"), python::args("bvList")), _help_); \ } @@ -261,14 +261,14 @@ struct BitOps_wrapper { help.c_str()); python::def( "BulkTverskySimilarity", - (python::list(*)(const SBV *, python::object, double, double, - bool))BulkTverskySimilarity, + (python::list (*)(const SBV *, python::object, double, double, + bool))BulkTverskySimilarity, (python::args("bv1"), python::args("bvList"), python::args("a"), python::args("b"), python::args("returnDistance") = 0)); python::def( "BulkTverskySimilarity", - (python::list(*)(const EBV *, python::object, double, double, - bool))BulkTverskySimilarity, + (python::list (*)(const EBV *, python::object, double, double, + bool))BulkTverskySimilarity, (python::args("bv1"), python::args("bvList"), python::args("a"), python::args("b"), python::args("returnDistance") = 0), help.c_str()); @@ -279,18 +279,18 @@ struct BitOps_wrapper { "(B(bv1) - B(bv1^bv2)) / B(bv1)"); python::def("OnBitProjSimilarity", - (DoubleVect(*)(const SBV &, const SBV &))OnBitProjSimilarity, + (DoubleVect (*)(const SBV &, const SBV &))OnBitProjSimilarity, python::args("bv1", "bv2")); python::def( "OnBitProjSimilarity", - (DoubleVect(*)(const EBV &, const EBV &))OnBitProjSimilarity, + (DoubleVect (*)(const EBV &, const EBV &))OnBitProjSimilarity, python::args("bv1", "bv2"), "Returns a 2-tuple: (B(bv1&bv2) / B(bv1), B(bv1&bv2) / B(bv2))"); python::def("OffBitProjSimilarity", - (DoubleVect(*)(const SBV &, const SBV &))OffBitProjSimilarity, + (DoubleVect (*)(const SBV &, const SBV &))OffBitProjSimilarity, python::args("bv1", "bv2")); python::def("OffBitProjSimilarity", - (DoubleVect(*)(const EBV &, const EBV &))OffBitProjSimilarity, + (DoubleVect (*)(const EBV &, const EBV &))OffBitProjSimilarity, python::args("bv1", "bv2")); python::def("NumBitsInCommon", @@ -302,18 +302,18 @@ struct BitOps_wrapper { "Returns the total number of bits in common between the two " "bit vectors"); python::def("OnBitsInCommon", - (IntVect(*)(const SBV &, const SBV &))OnBitsInCommon, + (IntVect (*)(const SBV &, const SBV &))OnBitsInCommon, python::args("bv1", "bv2")); python::def( - "OnBitsInCommon", (IntVect(*)(const EBV &, const EBV &))OnBitsInCommon, + "OnBitsInCommon", (IntVect (*)(const EBV &, const EBV &))OnBitsInCommon, python::args("bv1", "bv2"), "Returns the number of on bits in common between the two bit vectors"); python::def("OffBitsInCommon", - (IntVect(*)(const SBV &, const SBV &))OffBitsInCommon, + (IntVect (*)(const SBV &, const SBV &))OffBitsInCommon, python::args("bv1", "bv2")); python::def( "OffBitsInCommon", - (IntVect(*)(const EBV &, const EBV &))OffBitsInCommon, + (IntVect (*)(const EBV &, const EBV &))OffBitsInCommon, python::args("bv1", "bv2"), "Returns the number of off bits in common between the two bit vectors"); @@ -345,24 +345,24 @@ struct BitOps_wrapper { "Returns True if all bits in the first argument match all bits in the \n\ vector defined by the pickle in the second argument.\n"); - python::def("BitVectToText", (std::string(*)(const SBV &))BitVectToText, + python::def("BitVectToText", (std::string (*)(const SBV &))BitVectToText, python::args("bv1")); python::def( - "BitVectToText", (std::string(*)(const EBV &))BitVectToText, + "BitVectToText", (std::string (*)(const EBV &))BitVectToText, python::args("bv1"), "Returns a string of zeros and ones representing the bit vector."); python::def("BitVectToFPSText", - (std::string(*)(const SBV &))BitVectToFPSText, + (std::string (*)(const SBV &))BitVectToFPSText, python::args("bv1")); python::def("BitVectToFPSText", - (std::string(*)(const EBV &))BitVectToFPSText, + (std::string (*)(const EBV &))BitVectToFPSText, python::args("bv1"), "Returns an FPS string representing the bit vector."); python::def("BitVectToBinaryText", - (python::object(*)(const SBV &))BVToBinaryText, + (python::object (*)(const SBV &))BVToBinaryText, python::args("bv")); python::def( - "BitVectToBinaryText", (python::object(*)(const EBV &))BVToBinaryText, + "BitVectToBinaryText", (python::object (*)(const EBV &))BVToBinaryText, python::args("bv"), "Returns a binary string (byte array) representing the bit vector."); } diff --git a/Code/ForceField/Wrap/ForceField.cpp b/Code/ForceField/Wrap/ForceField.cpp index 1136b6b00..0710f3742 100644 --- a/Code/ForceField/Wrap/ForceField.cpp +++ b/Code/ForceField/Wrap/ForceField.cpp @@ -127,7 +127,7 @@ double PyForceField::calcEnergyWithPos(const python::object &pos) { PRECONDITION(this->field, "no force field"); if (pos != python::object()) { size_t s = this->field->dimension() * this->field->numPoints(); - size_t numElements = python::extract(pos.attr("__len__")()); + unsigned int numElements = python::len(pos); if (s != numElements) { throw ValueErrorException( "The Python container must have length equal to Dimension() * " @@ -165,7 +165,7 @@ PyObject *PyForceField::calcGradWithPos(const python::object &pos) { std::vector g(s, 0.0); PyObject *gradTuple = PyTuple_New(s); if (pos != python::object()) { - size_t numElements = python::extract(pos.attr("__len__")()); + unsigned int numElements = python::len(pos); if (s != numElements) { throw ValueErrorException( "The Python container must have length equal to Dimension() * " @@ -309,7 +309,7 @@ BOOST_PYTHON_MODULE(rdForceField) { python::class_("ForceField", "A force field", python::no_init) .def("CalcEnergy", - (double(PyForceField::*)(const python::object &) const) & + (double (PyForceField::*)(const python::object &) const) & PyForceField::calcEnergyWithPos, ((python::arg("self"), python::arg("pos") = python::object())), "Returns the energy (in kcal/mol) of the current arrangement\n" diff --git a/Code/Geometry/Wrap/Point.cpp b/Code/Geometry/Wrap/Point.cpp index 721e20bfb..328d3f5a4 100644 --- a/Code/Geometry/Wrap/Point.cpp +++ b/Code/Geometry/Wrap/Point.cpp @@ -37,7 +37,7 @@ struct PointND_pickle_suite : rdkit_pickle_suite { return python::tuple(res); } static void setstate(RDGeom::PointND &pt, python::tuple state) { - unsigned int sz = python::extract(state.attr("__len__")()); + unsigned int sz = python::len(state); for (unsigned int i = 0; i < sz; ++i) { pt[i] = python::extract(state[i]); } diff --git a/Code/GraphMol/ChemReactions/Wrap/Enumerate.cpp b/Code/GraphMol/ChemReactions/Wrap/Enumerate.cpp index 30035ca65..abaec63f3 100644 --- a/Code/GraphMol/ChemReactions/Wrap/Enumerate.cpp +++ b/Code/GraphMol/ChemReactions/Wrap/Enumerate.cpp @@ -45,10 +45,10 @@ namespace RDKit { template std::vector ConvertToVect(T bbs) { std::vector vect; - size_t num_bbs = python::extract(bbs.attr("__len__")()); + unsigned int num_bbs = python::len(bbs); vect.resize(num_bbs); - for (size_t i = 0; i < num_bbs; ++i) { - unsigned int len1 = python::extract(bbs[i].attr("__len__")()); + for (unsigned int i = 0; i < num_bbs; ++i) { + unsigned int len1 = python::len(bbs[i]); RDKit::MOL_SPTR_VECT &reacts = vect[i]; reacts.reserve(len1); for (unsigned int j = 0; j < len1; ++j) { diff --git a/Code/GraphMol/ChemReactions/Wrap/rdChemReactions.cpp b/Code/GraphMol/ChemReactions/Wrap/rdChemReactions.cpp index dbbc51740..d6bf65cc0 100644 --- a/Code/GraphMol/ChemReactions/Wrap/rdChemReactions.cpp +++ b/Code/GraphMol/ChemReactions/Wrap/rdChemReactions.cpp @@ -106,8 +106,7 @@ PyObject *RunReactants(ChemicalReaction *self, T reactants, self->initReactantMatchers(); } MOL_SPTR_VECT reacts; - unsigned int len1 = - python::extract(reactants.attr("__len__")()); + unsigned int len1 = python::len(reactants); reacts.resize(len1); for (unsigned int i = 0; i < len1; ++i) { reacts[i] = python::extract(reactants[i]); @@ -301,11 +300,11 @@ ChemicalReaction *ReactionFromSmarts(const char *smarts, python::dict replDict, bool useSmiles) { PRECONDITION(smarts, "null SMARTS string"); std::map replacements; - for (unsigned int i = 0; - i < python::extract(replDict.keys().attr("__len__")()); - ++i) { - replacements[python::extract(replDict.keys()[i])] = - python::extract(replDict.values()[i]); + const auto items = replDict.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + replacements[python::extract(item[0])] = + python::extract(item[1]); } ChemicalReaction *res; res = RxnSmartsToChemicalReaction(smarts, &replacements, useSmiles); @@ -394,12 +393,12 @@ python::object AddRecursiveQueriesToReaction(ChemicalReaction &self, bool getLabels = false) { // transform dictionary into map std::map queries; - for (unsigned int i = 0; - i < python::extract(queryDict.keys().attr("__len__")()); - ++i) { - ROMol *m = python::extract(queryDict.values()[i]); + const auto items = queryDict.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + ROMol *m = python::extract(item[1]); ROMOL_SPTR nm(new ROMol(*m)); - std::string k = python::extract(queryDict.keys()[i]); + std::string k = python::extract(item[0]); queries[k] = nm; } @@ -431,16 +430,17 @@ python::object PreprocessReaction(ChemicalReaction &reaction, std::string propName) { // transform dictionary into map std::map queries; - unsigned int size = - python::extract(queryDict.keys().attr("__len__")()); + const auto items = queryDict.items(); + unsigned int size = python::len(items); if (!size) { const bool normalized = true; queries = GetFlattenedFunctionalGroupHierarchy(normalized); } else { for (unsigned int i = 0; i < size; ++i) { - ROMol *m = python::extract(queryDict.values()[i]); + const auto item = items[i]; + ROMol *m = python::extract(item[1]); ROMOL_SPTR nm(new ROMol(*m)); - std::string k = python::extract(queryDict.keys()[i]); + std::string k = python::extract(item[0]); queries[k] = nm; } } @@ -885,52 +885,54 @@ see the documentation for rdkit.Chem.MolFromSmiles for an explanation\n\ of the replacements argument.", python::return_value_policy()); python::def("ReactionToSmarts", - (std::string(*)(const RDKit::ChemicalReaction &)) + (std::string (*)(const RDKit::ChemicalReaction &)) RDKit::ChemicalReactionToRxnSmarts, (python::arg("reaction")), "construct a reaction SMARTS string for a ChemicalReaction"); python::def("ReactionToSmiles", - (std::string(*)(const RDKit::ChemicalReaction &, - bool))RDKit::ChemicalReactionToRxnSmiles, + (std::string (*)(const RDKit::ChemicalReaction &, + bool))RDKit::ChemicalReactionToRxnSmiles, (python::arg("reaction"), python::arg("canonical") = true), "construct a reaction SMILES string for a ChemicalReaction"); python::def("ReactionToSmarts", - (std::string(*)(const RDKit::ChemicalReaction &, - const RDKit::SmilesWriteParams &)) + (std::string (*)(const RDKit::ChemicalReaction &, + const RDKit::SmilesWriteParams &)) RDKit::ChemicalReactionToRxnSmarts, (python::arg("reaction"), python::arg("params")), "construct a reaction SMARTS string for a ChemicalReaction"); python::def("ReactionToSmiles", - (std::string(*)(const RDKit::ChemicalReaction &, - const RDKit::SmilesWriteParams &)) + (std::string (*)(const RDKit::ChemicalReaction &, + const RDKit::SmilesWriteParams &)) RDKit::ChemicalReactionToRxnSmiles, (python::arg("reaction"), python::arg("params")), "construct a reaction SMILES string for a ChemicalReaction"); python::def("ReactionToCXSmarts", - (std::string(*)(const RDKit::ChemicalReaction &)) + (std::string (*)(const RDKit::ChemicalReaction &)) RDKit::ChemicalReactionToCXRxnSmarts, (python::arg("reaction")), "construct a reaction SMARTS string for a ChemicalReaction"); python::def("ReactionToCXSmiles", - (std::string(*)(const RDKit::ChemicalReaction &, - bool))RDKit::ChemicalReactionToCXRxnSmiles, + (std::string (*)(const RDKit::ChemicalReaction &, + bool))RDKit::ChemicalReactionToCXRxnSmiles, (python::arg("reaction"), python::arg("canonical") = true), "construct a reaction SMILES string for a ChemicalReaction"); - python::def("ReactionToCXSmarts", - (std::string(*)(const RDKit::ChemicalReaction &, - const RDKit::SmilesWriteParams &, - std::uint32_t)) - RDKit::ChemicalReactionToCXRxnSmarts, - (python::arg("reaction"), python::arg("params"), python::arg("flags") = RDKit::SmilesWrite::CXSmilesFields::CX_ALL), - "construct a reaction CXSMARTS string for a ChemicalReaction"); - python::def("ReactionToCXSmiles", - (std::string(*)(const RDKit::ChemicalReaction &, - const RDKit::SmilesWriteParams &, - std::uint32_t)) - RDKit::ChemicalReactionToCXRxnSmiles, - (python::arg("reaction"), python::arg("params"), python::arg("flags") = RDKit::SmilesWrite::CXSmilesFields::CX_ALL), - "construct a reaction CXSMILES string for a ChemicalReaction"); + python::def( + "ReactionToCXSmarts", + (std::string (*)(const RDKit::ChemicalReaction &, + const RDKit::SmilesWriteParams &, + std::uint32_t))RDKit::ChemicalReactionToCXRxnSmarts, + (python::arg("reaction"), python::arg("params"), + python::arg("flags") = RDKit::SmilesWrite::CXSmilesFields::CX_ALL), + "construct a reaction CXSMARTS string for a ChemicalReaction"); + python::def( + "ReactionToCXSmiles", + (std::string (*)(const RDKit::ChemicalReaction &, + const RDKit::SmilesWriteParams &, + std::uint32_t))RDKit::ChemicalReactionToCXRxnSmiles, + (python::arg("reaction"), python::arg("params"), + python::arg("flags") = RDKit::SmilesWrite::CXSmilesFields::CX_ALL), + "construct a reaction CXSMILES string for a ChemicalReaction"); python::def( "ReactionFromRxnFile", RDKit::RxnFileToChemicalReaction, diff --git a/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp b/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp index 782afa064..8d96893cc 100644 --- a/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp +++ b/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp @@ -40,8 +40,7 @@ unsigned int Compute2DCoords(RDKit::ROMol &mol, bool canonOrient, RDGeom::INT_POINT2D_MAP cMap; cMap.clear(); python::list ks = coordMap.keys(); - for (unsigned int i = 0; - i < python::extract(ks.attr("__len__")()); i++) { + for (unsigned int i = 0; i < python::len(ks); ++i) { unsigned int id = python::extract(ks[i]); if (id >= mol.getNumAtoms()) { throw_value_error("atom index out of range"); diff --git a/Code/GraphMol/Descriptors/Wrap/rdMolDescriptors.cpp b/Code/GraphMol/Descriptors/Wrap/rdMolDescriptors.cpp index 78b069755..d509f7d60 100644 --- a/Code/GraphMol/Descriptors/Wrap/rdMolDescriptors.cpp +++ b/Code/GraphMol/Descriptors/Wrap/rdMolDescriptors.cpp @@ -68,9 +68,9 @@ python::list computeCrippenContribs( python::list atomTypeLabels = python::list()) { std::vector *tAtomTypes = nullptr; std::vector *tAtomTypeLabels = nullptr; - if (python::extract(atomTypes.attr("__len__")()) != 0) { - if (python::extract(atomTypes.attr("__len__")()) != - mol.getNumAtoms()) { + unsigned int numAtomTypes = python::len(atomTypes); + if (numAtomTypes != 0) { + if (numAtomTypes != mol.getNumAtoms()) { throw_value_error( "if atomTypes vector is provided, it must be as long as the number " "of atoms"); @@ -78,9 +78,9 @@ python::list computeCrippenContribs( tAtomTypes = new std::vector(mol.getNumAtoms(), 0); } } - if (python::extract(atomTypeLabels.attr("__len__")()) != 0) { - if (python::extract(atomTypeLabels.attr("__len__")()) != - mol.getNumAtoms()) { + unsigned int numAtomTypeLabels = python::len(atomTypeLabels); + if (numAtomTypeLabels != 0) { + if (numAtomTypeLabels != mol.getNumAtoms()) { throw_value_error( "if atomTypeLabels vector is provided, it must be as long as the " "number of atoms"); @@ -336,8 +336,7 @@ double kappaHelper(double (*fn)(const RDKit::ROMol &, std::vector *), // make sure the optional argument actually was a list python::list typecheck = python::extract(atomContribs); - if (python::extract(typecheck.attr("__len__")()) != - mol.getNumAtoms()) { + if (python::len(typecheck) != mol.getNumAtoms()) { throw_value_error("length of atomContribs list != number of atoms"); } @@ -367,8 +366,7 @@ MorganFingerprintHelper(const RDKit::ROMol &mol, unsigned int radius, int nBits, RDLog::deprecationWarning("please use MorganGenerator"); std::vector *invars = nullptr; if (invariants) { - unsigned int nInvar = - python::extract(invariants.attr("__len__")()); + unsigned int nInvar = python::len(invariants); if (nInvar) { if (nInvar != mol.getNumAtoms()) { throw_value_error("length of invariant vector != number of atoms"); @@ -384,8 +382,7 @@ MorganFingerprintHelper(const RDKit::ROMol &mol, unsigned int radius, int nBits, } std::vector *froms = nullptr; if (fromAtoms) { - unsigned int nFrom = - python::extract(fromAtoms.attr("__len__")()); + unsigned int nFrom = python::len(fromAtoms); if (nFrom) { froms = new std::vector(); for (unsigned int i = 0; i < nFrom; ++i) { @@ -510,8 +507,7 @@ GetMorganFingerprintBV(const RDKit::ROMol &mol, unsigned int radius, RDLog::deprecationWarning("please use MorganGenerator"); std::vector *invars = nullptr; if (invariants) { - unsigned int nInvar = - python::extract(invariants.attr("__len__")()); + unsigned int nInvar = python::len(invariants); if (nInvar) { if (nInvar != mol.getNumAtoms()) { throw_value_error("length of invariant vector != number of atoms"); @@ -606,8 +602,7 @@ python::list GetUSR(const RDKit::ROMol &mol, int confId) { } python::list GetUSRDistributions(python::object coords, python::object points) { - unsigned int numCoords = - python::extract(coords.attr("__len__")()); + unsigned int numCoords = python::len(coords); if (numCoords == 0) { throw_value_error("no coordinates"); } @@ -644,9 +639,8 @@ python::list GetUSRDistributions(python::object coords, python::object points) { python::list GetUSRDistributionsFromPoints(python::object coords, python::object points) { - unsigned int numCoords = - python::extract(coords.attr("__len__")()); - unsigned int numPts = python::extract(points.attr("__len__")()); + unsigned int numCoords = python::len(coords); + unsigned int numPts = python::len(points); if (numCoords == 0) { throw_value_error("no coordinates"); } @@ -676,15 +670,13 @@ python::list GetUSRDistributionsFromPoints(python::object coords, } python::list GetUSRFromDistributions(python::object distances) { - unsigned int numDist = - python::extract(distances.attr("__len__")()); + unsigned int numDist = python::len(distances); if (numDist == 0) { throw_value_error("no distances"); } std::vector> dist(numDist); for (unsigned int i = 0; i < numDist; ++i) { - unsigned int numPts = - python::extract(distances[i].attr("__len__")()); + unsigned int numPts = python::len(distances[i]); if (numPts == 0) { throw_value_error("distances missing"); } @@ -705,15 +697,12 @@ python::list GetUSRFromDistributions(python::object distances) { double GetUSRScore(python::object descriptor1, python::object descriptor2, python::object weights) { - unsigned int numElements = - python::extract(descriptor1.attr("__len__")()); - if (numElements != - python::extract(descriptor2.attr("__len__")())) { + unsigned int numElements = python::len(descriptor1); + if (numElements != python::len(descriptor2)) { throw_value_error("descriptors must have the same length"); } unsigned int numWeights = numElements / 12; - unsigned int numPyWeights = - python::extract(weights.attr("__len__")()); + unsigned int numPyWeights = python::len(weights); std::vector w(numWeights, 1.0); // default weights: all to 1.0 if ((numPyWeights > 0) && (numPyWeights != numWeights)) { throw_value_error("number of weights is not correct"); @@ -747,15 +736,13 @@ python::list GetUSRCAT(const RDKit::ROMol &mol, python::object atomSelections, if (atomSelections != python::object()) { // make sure the optional argument actually was a list python::list typecheck = python::extract(atomSelections); - unsigned int numSel = - python::extract(atomSelections.attr("__len__")()); + unsigned int numSel = python::len(atomSelections); if (numSel == 0) { throw_value_error("empty atom selections"); } atomIds.resize(numSel); for (unsigned int i = 0; i < numSel; ++i) { - unsigned int numPts = - python::extract(atomSelections[i].attr("__len__")()); + unsigned int numPts = python::len(atomSelections[i]); std::vector tmpIds(numPts); for (unsigned int j = 0; j < numPts; ++j) { tmpIds[j] = python::extract(atomSelections[i][j]) - 1; @@ -777,7 +764,7 @@ python::list CalcSlogPVSA(const RDKit::ROMol &mol, python::object bins, bool force) { std::vector *lbins = nullptr; if (bins) { - unsigned int nBins = python::extract(bins.attr("__len__")()); + unsigned int nBins = python::len(bins); if (nBins) { lbins = new std::vector(nBins, 0.0); for (unsigned int i = 0; i < nBins; ++i) { @@ -798,7 +785,7 @@ python::list CalcSMRVSA(const RDKit::ROMol &mol, python::object bins, bool force) { std::vector *lbins = nullptr; if (bins) { - unsigned int nBins = python::extract(bins.attr("__len__")()); + unsigned int nBins = python::len(bins); if (nBins) { lbins = new std::vector(nBins, 0.0); for (unsigned int i = 0; i < nBins; ++i) { @@ -819,7 +806,7 @@ python::list CalcPEOEVSA(const RDKit::ROMol &mol, python::object bins, bool force) { std::vector *lbins = nullptr; if (bins) { - unsigned int nBins = python::extract(bins.attr("__len__")()); + unsigned int nBins = python::len(bins); if (nBins) { lbins = new std::vector(nBins, 0.0); for (unsigned int i = 0; i < nBins; ++i) { @@ -839,7 +826,7 @@ python::list CalcPEOEVSA(const RDKit::ROMol &mol, python::object bins, python::list CalcCustomPropVSA(const RDKit::ROMol &mol, const std::string customPropName, python::object bins, bool force) { - unsigned int nBins = python::extract(bins.attr("__len__")()); + unsigned int nBins = python::len(bins); std::vector lbins = std::vector(nBins, 0.0); for (unsigned int i = 0; i < nBins; ++i) { lbins[i] = python::extract(bins[i]); @@ -918,23 +905,22 @@ int registerPropertyHelper(python::object o) { } boost::shared_ptr -getDoubleCubicLatticeVolume(const RDKit::ROMol &mol, - const python::list &radii, - bool isProtein = false, - bool includeLigand = true, - double probeRadius = 1.4, - int confId = -1) { +getDoubleCubicLatticeVolume(const RDKit::ROMol &mol, const python::list &radii, + bool isProtein = false, bool includeLigand = true, + double probeRadius = 1.4, int confId = -1) { std::vector radiiAsVector; radiiAsVector.reserve(mol.getNumAtoms()); pythonObjectToVect(radii, radiiAsVector); - return boost::make_shared(mol, std::move(radiiAsVector), isProtein, includeLigand, probeRadius, confId); + return boost::make_shared( + mol, std::move(radiiAsVector), isProtein, includeLigand, probeRadius, + confId); } -double getPartialSurfaceAreaHelper(RDKit::Descriptors::DoubleCubicLatticeVolume &self, - const python::object &atomIdxs) { - - unsigned int numAtoms = self.mol.getNumAtoms(); +double getPartialSurfaceAreaHelper( + RDKit::Descriptors::DoubleCubicLatticeVolume &self, + const python::object &atomIdxs) { + unsigned int numAtoms = self.mol.getNumAtoms(); auto atoms = pythonObjectToDynBitset(atomIdxs, numAtoms); if (atoms.empty()) { @@ -942,30 +928,29 @@ double getPartialSurfaceAreaHelper(RDKit::Descriptors::DoubleCubicLatticeVolume } return self.getPartialSurfaceArea(atoms); - } -double getPartialVolumeHelper(RDKit::Descriptors::DoubleCubicLatticeVolume &self, - const python::object &atomIdxs) { - - - unsigned int numAtoms = self.mol.getNumAtoms(); +double getPartialVolumeHelper( + RDKit::Descriptors::DoubleCubicLatticeVolume &self, + const python::object &atomIdxs) { + unsigned int numAtoms = self.mol.getNumAtoms(); auto atoms = pythonObjectToDynBitset(atomIdxs, numAtoms); if (atoms.empty()) { throw_value_error("No atom indices supplied for Partial Surface Area"); } return self.getPartialVolume(atoms); - } -python::dict getSurfacePointsHelper(RDKit::Descriptors::DoubleCubicLatticeVolume &self) { - const std::map> &points = self.getSurfacePoints(); +python::dict getSurfacePointsHelper( + RDKit::Descriptors::DoubleCubicLatticeVolume &self) { + const std::map> &points = + self.getSurfacePoints(); python::dict surfacePoints; - + for (const auto &it : points) { python::list points3D; - for (const auto &p : it.second){ + for (const auto &p : it.second) { points3D.append(p); } surfacePoints[it.first] = points3D; @@ -1712,7 +1697,7 @@ BOOST_PYTHON_MODULE(rdMolDescriptors) { docString.c_str(), python::return_value_policy()); - docString = + docString = R"DOC(ARGUMENTS: " - mol: molecule or protein under consideration " - radii: radii for atoms of input mol (get using GetPeriodicTable or provide custom list) @@ -1722,64 +1707,63 @@ BOOST_PYTHON_MODULE(rdMolDescriptors) { " - confId: conformer ID to consider (default=-1) ")DOC"; -python::class_>( - "DoubleCubicLatticeVolume", - "Class for the Double Cubic Lattice Volume method", - python::no_init) - .def("__init__", - python::make_constructor( - &getDoubleCubicLatticeVolume, - python::default_call_policies(), - (python::arg("mol"), - python::arg("radii"), - python::arg("isProtein") = false, - python::arg("includeLigand") = true, - python::arg("probeRadius") = 1.4, - python::arg("confId") = -1)), - docString.c_str()) - .def("GetSurfaceArea", - &RDKit::Descriptors::DoubleCubicLatticeVolume::getSurfaceArea, - (python::args("self")), - "Get the Surface Area of the Molecule or Protein") - .def("GetAtomSurfaceArea", - &RDKit::Descriptors::DoubleCubicLatticeVolume::getAtomSurfaceArea, - (python::arg("atom_idx")), "Get the surface area of atom with atom_idx") - .def("GetPolarSurfaceArea", - &RDKit::Descriptors::DoubleCubicLatticeVolume::getPolarSurfaceArea, - (python::arg("includeSandP")=false, python::arg("includeHs")=false), - "Get the Polar Surface Area of the Molecule or Protein") - .def("GetPartialSurfaceArea", - &getPartialSurfaceAreaHelper, - (python::arg("atomIndices")), - "Get the Partial Surface Area of the Molecule or Protein for specified subset of atoms") - .def("GetSurfacePoints", - &getSurfacePointsHelper, - "Get the set of points representing the surface") - .def("GetVolume", - &RDKit::Descriptors::DoubleCubicLatticeVolume::getVolume, - "Get the Total Volume of the Molecule or Protein") - .def("GetVDWVolume", - &RDKit::Descriptors::DoubleCubicLatticeVolume::getVDWVolume, - "Get the van der Waals Volume of the Molecule or Protein") - .def("GetAtomVolume", - &RDKit::Descriptors::DoubleCubicLatticeVolume::getAtomVolume, - (python::arg("atomIdx"), python::arg("solventRadius")), - "Get the volume atom of atom_idx with volume for specified Probe Radius") - .def("GetPolarVolume", - &RDKit::Descriptors::DoubleCubicLatticeVolume::getPolarVolume, - (python::arg("includeSandP")=false, python::arg("includeHs")=false), - "Get the Polar Volume of the Molecule or Protein") - .def("GetPartialVolume", - &getPartialVolumeHelper, - python::arg("atomIdx"), - "Get the Partial Volume of the Molecule or Protein for specified subset of atoms") - .def("GetCompactness", - &RDKit::Descriptors::DoubleCubicLatticeVolume::getCompactness, - "Get the Compactness of the Protein") - .def("GetPackingDensity", - &RDKit::Descriptors::DoubleCubicLatticeVolume::getPackingDensity, - "Get the PackingDensity of the Protein"); + python::class_< + RDKit::Descriptors::DoubleCubicLatticeVolume, + boost::shared_ptr>( + "DoubleCubicLatticeVolume", + "Class for the Double Cubic Lattice Volume method", python::no_init) + .def("__init__", + python::make_constructor( + &getDoubleCubicLatticeVolume, python::default_call_policies(), + (python::arg("mol"), python::arg("radii"), + python::arg("isProtein") = false, + python::arg("includeLigand") = true, + python::arg("probeRadius") = 1.4, python::arg("confId") = -1)), + docString.c_str()) + .def("GetSurfaceArea", + &RDKit::Descriptors::DoubleCubicLatticeVolume::getSurfaceArea, + (python::args("self")), + "Get the Surface Area of the Molecule or Protein") + .def("GetAtomSurfaceArea", + &RDKit::Descriptors::DoubleCubicLatticeVolume::getAtomSurfaceArea, + (python::arg("atom_idx")), + "Get the surface area of atom with atom_idx") + .def("GetPolarSurfaceArea", + &RDKit::Descriptors::DoubleCubicLatticeVolume::getPolarSurfaceArea, + (python::arg("includeSandP") = false, + python::arg("includeHs") = false), + "Get the Polar Surface Area of the Molecule or Protein") + .def( + "GetPartialSurfaceArea", &getPartialSurfaceAreaHelper, + (python::arg("atomIndices")), + "Get the Partial Surface Area of the Molecule or Protein for specified subset of atoms") + .def("GetSurfacePoints", &getSurfacePointsHelper, + "Get the set of points representing the surface") + .def("GetVolume", + &RDKit::Descriptors::DoubleCubicLatticeVolume::getVolume, + "Get the Total Volume of the Molecule or Protein") + .def("GetVDWVolume", + &RDKit::Descriptors::DoubleCubicLatticeVolume::getVDWVolume, + "Get the van der Waals Volume of the Molecule or Protein") + .def( + "GetAtomVolume", + &RDKit::Descriptors::DoubleCubicLatticeVolume::getAtomVolume, + (python::arg("atomIdx"), python::arg("solventRadius")), + "Get the volume atom of atom_idx with volume for specified Probe Radius") + .def("GetPolarVolume", + &RDKit::Descriptors::DoubleCubicLatticeVolume::getPolarVolume, + (python::arg("includeSandP") = false, + python::arg("includeHs") = false), + "Get the Polar Volume of the Molecule or Protein") + .def( + "GetPartialVolume", &getPartialVolumeHelper, python::arg("atomIdx"), + "Get the Partial Volume of the Molecule or Protein for specified subset of atoms") + .def("GetCompactness", + &RDKit::Descriptors::DoubleCubicLatticeVolume::getCompactness, + "Get the Compactness of the Protein") + .def("GetPackingDensity", + &RDKit::Descriptors::DoubleCubicLatticeVolume::getPackingDensity, + "Get the PackingDensity of the Protein"); #ifdef RDK_BUILD_DESCRIPTORS3D python::scope().attr("_CalcCoulombMat_version") = diff --git a/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp b/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp index a7b255813..a7c01a523 100644 --- a/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp +++ b/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp @@ -36,11 +36,11 @@ struct PyEmbedParameters // the EmbedParameters object doesn't own the memory for the coordMap, so we // have to take ownership here. d_coordMap.reset(new std::map()); - for (unsigned int i = 0; - i < python::extract(cmap.keys().attr("__len__")()); - ++i) { - (*d_coordMap)[python::extract(cmap.keys()[i])] = - python::extract(cmap.values()[i]); + const auto items = cmap.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + (*d_coordMap)[python::extract(item[0])] = + python::extract(item[1]); } coordMap = d_coordMap.get(); } @@ -58,7 +58,7 @@ struct PyEmbedParameters new std::map, double>); python::list ks = CPCIdict.keys(); - unsigned int nKeys = python::extract(ks.attr("__len__")()); + unsigned int nKeys = python::len(ks); for (unsigned int i = 0; i < nKeys; ++i) { python::tuple id = python::extract(ks[i]); @@ -115,7 +115,7 @@ int EmbedMolecule(ROMol &mol, unsigned int maxAttempts, int seed, bool useMacrocycle14config) { std::map pMap; python::list ks = coordMap.keys(); - unsigned int nKeys = python::extract(ks.attr("__len__")()); + unsigned int nKeys = python::len(ks); for (unsigned int i = 0; i < nKeys; ++i) { unsigned int id = python::extract(ks[i]); pMap[id] = python::extract(coordMap[id]); @@ -173,7 +173,7 @@ INT_VECT EmbedMultipleConfs( bool useMacrocycle14config) { std::map pMap; python::list ks = coordMap.keys(); - unsigned int nKeys = python::extract(ks.attr("__len__")()); + unsigned int nKeys = python::len(ks); for (unsigned int i = 0; i < nKeys; ++i) { unsigned int id = python::extract(ks[i]); pMap[id] = python::extract(coordMap[id]); diff --git a/Code/GraphMol/FMCS/Wrap/rdFMCS.cpp b/Code/GraphMol/FMCS/Wrap/rdFMCS.cpp index 75c272d7a..5fa9341af 100644 --- a/Code/GraphMol/FMCS/Wrap/rdFMCS.cpp +++ b/Code/GraphMol/FMCS/Wrap/rdFMCS.cpp @@ -586,7 +586,7 @@ MCSResult *FindMCSWrapper(python::object mols, bool maximizeBonds, AtomComparator atomComp, BondComparator bondComp, RingComparator ringComp, std::string seedSmarts) { std::vector ms; - unsigned int nElems = python::extract(mols.attr("__len__")()); + unsigned int nElems = python::len(mols); ms.resize(nElems); for (unsigned int i = 0; i < nElems; ++i) { if (!mols[i]) { @@ -621,7 +621,7 @@ MCSResult *FindMCSWrapper(python::object mols, bool maximizeBonds, MCSResult *FindMCSWrapper2(python::object mols, PyMCSParameters &pyMcsParams) { std::vector ms; - unsigned int nElems = python::extract(mols.attr("__len__")()); + unsigned int nElems = python::len(mols); ms.resize(nElems); for (unsigned int i = 0; i < nElems; ++i) { if (!mols[i]) { diff --git a/Code/GraphMol/FilterCatalog/Wrap/FilterCatalog.cpp b/Code/GraphMol/FilterCatalog/Wrap/FilterCatalog.cpp index 0ab97f38d..0d46b3501 100644 --- a/Code/GraphMol/FilterCatalog/Wrap/FilterCatalog.cpp +++ b/Code/GraphMol/FilterCatalog/Wrap/FilterCatalog.cpp @@ -367,14 +367,13 @@ struct filtercat_wrapper { .def("IsValid", &SmartsMatcher::isValid, python::args("self"), "Returns True if the SmartsMatcher is valid") - .def( - "SetPattern", - (void(SmartsMatcher::*)(const ROMol &)) & SmartsMatcher::setPattern, - python::args("self", "pat"), - "Set the pattern molecule for the SmartsMatcher") .def("SetPattern", - (void(SmartsMatcher::*)(const std::string &)) & - SmartsMatcher::setPattern, + (void (SmartsMatcher::*)(const ROMol &))&SmartsMatcher::setPattern, + python::args("self", "pat"), + "Set the pattern molecule for the SmartsMatcher") + .def("SetPattern", + (void (SmartsMatcher::*)( + const std::string &))&SmartsMatcher::setPattern, python::args("self", "pat"), "Set the smarts pattern for the Smarts Matcher (warning: " "MinimumCount is not reset)") @@ -424,7 +423,7 @@ struct filtercat_wrapper { if (!is_python_converter_registered< boost::shared_ptr>()) { python::register_ptr_to_python< - boost::shared_ptr>(); + boost::shared_ptr>(); } bool noproxy = true; @@ -455,16 +454,17 @@ struct filtercat_wrapper { .def("GetPropList", &FilterCatalogEntry::getPropList, python::args("self")) .def("SetProp", - (void(FilterCatalogEntry::*)(const std::string &, std::string)) & - FilterCatalogEntry::setProp, + (void (FilterCatalogEntry::*)( + const std::string &, + std::string))&FilterCatalogEntry::setProp, python::args("self", "key", "val")) .def("GetProp", - (std::string(FilterCatalogEntry::*)(const std::string &) const) & + (std::string (FilterCatalogEntry::*)(const std::string &) const) & FilterCatalogEntry::getProp, python::args("self", "key")) .def("ClearProp", - (void(FilterCatalogEntry::*)(const std::string &)) & - FilterCatalogEntry::clearProp, + (void (FilterCatalogEntry::*)( + const std::string &))&FilterCatalogEntry::clearProp, python::args("self", "key")); python::def( @@ -583,8 +583,9 @@ struct filtercat_wrapper { "If a smiles string can't be parsed, a 'Bad smiles' entry is " "returned."); + auto scope = python::scope(); std::string nested_name = python::extract( - python::scope().attr("__name__") + ".FilterMatchOps"); + scope.attr("__name__") + ".FilterMatchOps"); python::object nested_module(python::handle<>( python::borrowed(PyImport_AddModule(nested_name.c_str())))); python::scope().attr("FilterMatchOps") = nested_module; diff --git a/Code/GraphMol/Fingerprints/Wrap/FingerprintGeneratorWrapper.cpp b/Code/GraphMol/Fingerprints/Wrap/FingerprintGeneratorWrapper.cpp index 2f83f0887..94961661c 100644 --- a/Code/GraphMol/Fingerprints/Wrap/FingerprintGeneratorWrapper.cpp +++ b/Code/GraphMol/Fingerprints/Wrap/FingerprintGeneratorWrapper.cpp @@ -44,8 +44,7 @@ void convertPyArguments( std::unique_ptr> &customAtomInvariants, std::unique_ptr> &customBondInvariants) { if (!py_fromAtoms.is_none()) { - unsigned int len = - python::extract(py_fromAtoms.attr("__len__")()); + unsigned int len = python::len(py_fromAtoms); if (len) { fromAtoms.reset(new std::vector()); fromAtoms->reserve(len); @@ -56,8 +55,7 @@ void convertPyArguments( } if (!py_ignoreAtoms.is_none()) { - unsigned int len = - python::extract(py_ignoreAtoms.attr("__len__")()); + unsigned int len = python::len(py_ignoreAtoms); if (len) { ignoreAtoms.reset(new std::vector()); ignoreAtoms->reserve(len); @@ -69,8 +67,7 @@ void convertPyArguments( } if (!py_atomInvs.is_none()) { - unsigned int len = - python::extract(py_atomInvs.attr("__len__")()); + unsigned int len = python::len(py_atomInvs); if (len) { customAtomInvariants.reset(new std::vector()); customAtomInvariants->reserve(len); @@ -82,8 +79,7 @@ void convertPyArguments( } if (!py_bondInvs.is_none()) { - unsigned int len = - python::extract(py_bondInvs.attr("__len__")()); + unsigned int len = python::len(py_bondInvs); if (len) { customBondInvariants.reset(new std::vector()); customBondInvariants->reserve(len); @@ -206,7 +202,7 @@ ExplicitBitVect *getFingerprint(const FingerprintGenerator *fpGen, template python::tuple mtgetFingerprints(FuncType func, python::object mols, int numThreads) { - unsigned int nmols = python::extract(mols.attr("__len__")()); + unsigned int nmols = python::len(mols); std::vector tmols; for (auto i = 0u; i < nmols; ++i) { tmols.push_back(python::extract(mols[i])()); @@ -333,10 +329,9 @@ const std::vector convertPyArgumentsForBulk( const python::list &py_molVect) { std::vector molVect; if (!py_molVect.is_none()) { - unsigned int len = - python::extract(py_molVect.attr("__len__")()); + unsigned int len = python::len(py_molVect); if (len) { - for (unsigned int i = 0; i < len; i++) { + for (unsigned int i = 0; i < len; ++i) { molVect.push_back(python::extract(py_molVect[i])); } } @@ -345,8 +340,7 @@ const std::vector convertPyArgumentsForBulk( } python::list getSparseCountFPBulkPy(python::list &py_molVect, FPType fPType) { - const std::vector molVect = - convertPyArgumentsForBulk(py_molVect); + const auto molVect = convertPyArgumentsForBulk(py_molVect); auto tempResult = getSparseCountFPBulk(molVect, fPType); python::list result; diff --git a/Code/GraphMol/MolChemicalFeatures/Wrap/ChemicalFeatureUtils.cpp b/Code/GraphMol/MolChemicalFeatures/Wrap/ChemicalFeatureUtils.cpp index 3395fd183..84a82df90 100644 --- a/Code/GraphMol/MolChemicalFeatures/Wrap/ChemicalFeatureUtils.cpp +++ b/Code/GraphMol/MolChemicalFeatures/Wrap/ChemicalFeatureUtils.cpp @@ -21,8 +21,7 @@ namespace python = boost::python; namespace RDKit { python::object GetAtomMatch(python::object featMatch, int maxAts = 1024) { python::list res; - unsigned int nEntries = - python::extract(featMatch.attr("__len__")()); + unsigned int nEntries = python::len(featMatch); boost::dynamic_bitset<> indices(maxAts); for (unsigned int i = 0; i < nEntries; ++i) { diff --git a/Code/GraphMol/MolDraw2D/Wrap/rdMolDraw2D.cpp b/Code/GraphMol/MolDraw2D/Wrap/rdMolDraw2D.cpp index e91fc1333..73fcb5aea 100644 --- a/Code/GraphMol/MolDraw2D/Wrap/rdMolDraw2D.cpp +++ b/Code/GraphMol/MolDraw2D/Wrap/rdMolDraw2D.cpp @@ -39,21 +39,21 @@ void tagAtomHelper(MolDraw2DSVG &self, const ROMol &mol, double radius, std::map events; if (pyo) { python::dict tDict = python::extract(pyo); - python::list keys = tDict.keys(); - python::list vals = tDict.values(); - for (unsigned int i = 0; - i < python::extract(keys.attr("__len__")()); ++i) { - events[python::extract(keys[i])] = - python::extract(vals[i]); + const auto items = tDict.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + events[python::extract(item[0])] = + python::extract(item[1]); } } self.tagAtoms(mol, radius, events); } void pyDictToColourMap(python::object pyo, ColourPalette &res) { python::dict tDict = python::extract(pyo); - for (unsigned int i = 0; - i < python::extract(tDict.keys().attr("__len__")()); ++i) { - python::tuple tpl = python::extract(tDict.values()[i]); + const auto items = tDict.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + python::tuple tpl = python::extract(item[1]); float r = python::extract(tpl[0]); float g = python::extract(tpl[1]); float b = python::extract(tpl[2]); @@ -62,7 +62,7 @@ void pyDictToColourMap(python::object pyo, ColourPalette &res) { a = python::extract(tpl[3]); } DrawColour clr(r, g, b, a); - res[python::extract(tDict.keys()[i])] = clr; + res[python::extract(item[0])] = clr; } } ColourPalette *pyDictToColourMap(python::object pyo) { @@ -75,10 +75,11 @@ ColourPalette *pyDictToColourMap(python::object pyo) { } void pyDictToDoubleMap(python::object pyo, std::map &res) { python::dict tDict = python::extract(pyo); - for (unsigned int i = 0; - i < python::extract(tDict.keys().attr("__len__")()); ++i) { - double r = python::extract(tDict.values()[i]); - res[python::extract(tDict.keys()[i])] = r; + const auto items = tDict.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + double r = python::extract(item[1]); + res[python::extract(item[0])] = r; } } std::map *pyDictToDoubleMap(python::object pyo) { @@ -91,10 +92,11 @@ std::map *pyDictToDoubleMap(python::object pyo) { } void pyDictToIntMap(python::object pyo, std::map &res) { python::dict tDict = python::extract(pyo); - for (unsigned int i = 0; - i < python::extract(tDict.keys().attr("__len__")()); ++i) { - int r = python::extract(tDict.values()[i]); - res[python::extract(tDict.keys()[i])] = r; + const auto items = tDict.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + int r = python::extract(item[1]); + res[python::extract(item[0])] = r; } } std::map *pyDictToIntMap(python::object pyo) { @@ -133,8 +135,7 @@ DrawColour pyTupleToDrawColour(const python::tuple tpl) { void pyListToColourVec(python::object pyo, std::vector &res) { res.clear(); python::list tList = python::extract(pyo); - for (unsigned int i = 0; - i < python::extract(tList.attr("__len__")()); ++i) { + for (unsigned int i = 0; i < python::len(tList); ++i) { python::tuple tpl = python::extract(tList[i]); res.push_back(pyTupleToDrawColour(tpl)); } @@ -144,12 +145,13 @@ void pyListToColourVec(python::object pyo, std::vector &res) { void pyDictToMapColourVec(python::object pyo, std::map> &res) { python::dict tDict = python::extract(pyo); - for (unsigned int i = 0; - i < python::extract(tDict.keys().attr("__len__")()); ++i) { - python::list pl = python::extract(tDict.values()[i]); + const auto items = tDict.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + python::list pl = python::extract(item[1]); std::vector v; pyListToColourVec(pl, v); - res[python::extract(tDict.keys()[i])] = v; + res[python::extract(item[0])] = v; } } @@ -321,8 +323,7 @@ void drawMoleculesHelper2(MolDraw2D &self, python::object pmols, unsigned int nThere = mols->size(); std::unique_ptr>> highlightAtoms; if (highlight_atoms) { - if (python::extract(highlight_atoms.attr("__len__")()) != - nThere) { + if (python::len(highlight_atoms) != nThere) { throw ValueErrorException( "If highlightAtoms is provided it must be the same length as the " "molecule list."); @@ -334,8 +335,7 @@ void drawMoleculesHelper2(MolDraw2D &self, python::object pmols, } std::unique_ptr>> highlightBonds; if (highlight_bonds) { - if (python::extract(highlight_bonds.attr("__len__")()) != - nThere) { + if (python::len(highlight_bonds) != nThere) { throw ValueErrorException( "If highlightBonds is provided it must be the same length as the " "molecule list."); @@ -348,8 +348,7 @@ void drawMoleculesHelper2(MolDraw2D &self, python::object pmols, std::unique_ptr> highlightAtomMap; if (highlight_atom_map) { - if (python::extract(highlight_atom_map.attr("__len__")()) != - nThere) { + if (python::len(highlight_atom_map) != nThere) { throw ValueErrorException( "If highlightAtomMap is provided it must be the same length as the " "molecule list."); @@ -361,8 +360,7 @@ void drawMoleculesHelper2(MolDraw2D &self, python::object pmols, } std::unique_ptr> highlightBondMap; if (highlight_bond_map) { - if (python::extract(highlight_bond_map.attr("__len__")()) != - nThere) { + if (python::len(highlight_bond_map) != nThere) { throw ValueErrorException( "If highlightBondMap is provided it must be the same length as the " "molecule list."); @@ -374,8 +372,7 @@ void drawMoleculesHelper2(MolDraw2D &self, python::object pmols, } std::unique_ptr>> highlightRadii; if (highlight_atom_radii) { - if (python::extract(highlight_atom_radii.attr("__len__")()) != - nThere) { + if (python::len(highlight_atom_radii) != nThere) { throw ValueErrorException( "If highlightAtomRadii is provided it must be the same length as the " "molecule list."); @@ -626,8 +623,7 @@ void contourAndDrawGridHelper(RDKit::MolDraw2D &drawer, python::object &data, void setColoursHelper(RDKit::MolDraw2DUtils::ContourParams ¶ms, python::object pycolors) { std::vector cs; - for (size_t i = 0; i < python::extract(pycolors.attr("__len__")()); - ++i) { + for (unsigned int i = 0; i < python::len(pycolors); ++i) { cs.push_back( pyTupleToDrawColour(python::extract(pycolors[i]))); } @@ -1139,28 +1135,29 @@ BOOST_PYTHON_MODULE(rdMolDraw2D) { .def("FillPolys", &RDKit::MolDraw2D::fillPolys, python::args("self"), "returns whether or not polygons are being filled") .def("DrawLine", - (void(RDKit::MolDraw2D::*)(const Point2D &, const Point2D &, bool)) & - RDKit::MolDraw2D::drawLine, + (void (RDKit::MolDraw2D::*)(const Point2D &, const Point2D &, + bool))&RDKit::MolDraw2D::drawLine, (python::arg("self"), python::arg("cds1"), python::arg("cds2"), python::arg("rawCoords") = false), "draws a line with the current drawing style. The coordinates " "are in the molecule frame unless rawCoords is true, " "in which case the coordinates are in pixels.") - .def("DrawArrow", RDKit::drawArrowHelper, - (python::arg("self"), python::arg("cds1"), python::arg("cds2"), - python::arg("asPolygon") = false, python::arg("frac") = 0.05, - python::arg("angle") = M_PI / 6, - python::arg("color") = python::object(), - python::arg("rawCoords") = false), - "draws an arrow with the current drawing style. The coordinates " - "are in the molecule frame unless rawCoords is true, " - "in which case the coordinates are in pixels. " - "If asPolygon is true the head of the " - "arrow will be drawn as a triangle, otherwise two lines are used. " - "The fraction of the arrow length to use for the head is given by " - "frac. The angle of the arrowhead " - "(the angle between the main line and each arrowhead line) is given by angle. " - "The color is a tuple of 3 floats (0-1) in red, green, blue (RGB) order.") + .def( + "DrawArrow", RDKit::drawArrowHelper, + (python::arg("self"), python::arg("cds1"), python::arg("cds2"), + python::arg("asPolygon") = false, python::arg("frac") = 0.05, + python::arg("angle") = M_PI / 6, + python::arg("color") = python::object(), + python::arg("rawCoords") = false), + "draws an arrow with the current drawing style. The coordinates " + "are in the molecule frame unless rawCoords is true, " + "in which case the coordinates are in pixels. " + "If asPolygon is true the head of the " + "arrow will be drawn as a triangle, otherwise two lines are used. " + "The fraction of the arrow length to use for the head is given by " + "frac. The angle of the arrowhead " + "(the angle between the main line and each arrowhead line) is given by angle. " + "The color is a tuple of 3 floats (0-1) in red, green, blue (RGB) order.") .def("DrawTriangle", &RDKit::MolDraw2D::drawTriangle, (python::arg("self"), python::arg("cds1"), python::arg("cds2"), python::arg("cds3"), python::arg("rawCoords") = false), @@ -1188,9 +1185,8 @@ BOOST_PYTHON_MODULE(rdMolDraw2D) { "are in the molecule frame unless rawCoords is true, " "in which case the coordinates are in pixels.") .def("DrawArc", - (void(RDKit::MolDraw2D::*)(const Point2D &, double, double, double, - bool)) & - RDKit::MolDraw2D::drawArc, + (void (RDKit::MolDraw2D::*)(const Point2D &, double, double, double, + bool))&RDKit::MolDraw2D::drawArc, (python::arg("self"), python::arg("center"), python::arg("radius"), python::arg("angle1"), python::arg("angle2"), python::arg("rawCoords") = false), @@ -1219,9 +1215,9 @@ BOOST_PYTHON_MODULE(rdMolDraw2D) { "are in the molecule frame unless rawCoords is true, " "in which case the coordinates are in pixels.") .def("DrawString", - (void(RDKit::MolDraw2D::*)(const std::string &, - const RDGeom::Point2D &, bool)) & - RDKit::MolDraw2D::drawString, + (void (RDKit::MolDraw2D::*)(const std::string &, + const RDGeom::Point2D &, + bool))&RDKit::MolDraw2D::drawString, (python::arg("self"), python::arg("string"), python::arg("pos"), python::arg("rawCoords") = false), "add text to the canvas. The coordinates " @@ -1236,14 +1232,14 @@ BOOST_PYTHON_MODULE(rdMolDraw2D) { "are in the molecule frame unless rawCoords is true, " "in which case the coordinates are in pixels.") .def("GetDrawCoords", - (RDGeom::Point2D(RDKit::MolDraw2D::*)(const RDGeom::Point2D &) + (RDGeom::Point2D (RDKit::MolDraw2D::*)(const RDGeom::Point2D &) const) & RDKit::MolDraw2D::getDrawCoords, (python::arg("self"), python::arg("point")), "get the coordinates in drawing space for a particular point in " "molecule space") .def("GetDrawCoords", - (RDGeom::Point2D(RDKit::MolDraw2D::*)(int) const) & + (RDGeom::Point2D (RDKit::MolDraw2D::*)(int) const) & RDKit::MolDraw2D::getDrawCoords, (python::arg("self"), python::arg("atomIndex")), "get the coordinates in drawing space for a particular atom") @@ -1273,7 +1269,7 @@ BOOST_PYTHON_MODULE(rdMolDraw2D) { python::args("self"), "add the last bits of SVG to finish the drawing") .def("AddMoleculeMetadata", - (void(RDKit::MolDraw2DSVG::*)(const RDKit::ROMol &, int) const) & + (void (RDKit::MolDraw2DSVG::*)(const RDKit::ROMol &, int) const) & RDKit::MolDraw2DSVG::addMoleculeMetadata, ((python::arg("self"), python::arg("mol")), python::arg("confId") = -1), @@ -1471,8 +1467,7 @@ BOOST_PYTHON_MODULE(rdMolDraw2D) { python::arg("height") = 300, python::arg("highlightAtoms") = python::object(), python::arg("kekulize") = true, python::arg("lineWidthMult") = 1, - python::arg("includeAtomCircles") = true, - python::arg("confId") = -1), + python::arg("includeAtomCircles") = true, python::arg("confId") = -1), docString.c_str()); docString = "Returns ACS 1996 mode svg for a molecule"; python::def("MolToACS1996SVG", &RDKit::molToACS1996SVG, diff --git a/Code/GraphMol/MolStandardize/Wrap/rdMolStandardize.cpp b/Code/GraphMol/MolStandardize/Wrap/rdMolStandardize.cpp index dddfe26c2..c24890788 100644 --- a/Code/GraphMol/MolStandardize/Wrap/rdMolStandardize.cpp +++ b/Code/GraphMol/MolStandardize/Wrap/rdMolStandardize.cpp @@ -179,7 +179,7 @@ void mtinPlaceHelper(python::object pymols, int numThreads, if (params) { ps = python::extract(params); } - unsigned int nmols = python::extract(pymols.attr("__len__")()); + unsigned int nmols = python::len(pymols); std::vector mols(nmols); for (auto i = 0u; i < nmols; ++i) { auto mol = static_cast( @@ -199,7 +199,7 @@ void mtinPlaceHelper2(python::object pymols, int numThreads, if (params) { ps = python::extract(params); } - unsigned int nmols = python::extract(pymols.attr("__len__")()); + unsigned int nmols = python::len(pymols); std::vector mols(nmols); for (auto i = 0u; i < nmols; ++i) { auto mol = static_cast( diff --git a/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp b/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp index c699cd8af..26d0cab4c 100644 --- a/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp +++ b/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp @@ -51,7 +51,7 @@ PyObject *computePrincAxesMomentsHelper( std::vector weightsVec; size_t i; if (weights != python::object()) { - size_t numElements = python::extract(weights.attr("__len__")()); + size_t numElements = python::len(weights); if (numElements != conf.getNumAtoms()) { throw ValueErrorException( "The Python container must have length equal to conf.GetNumAtoms()"); diff --git a/Code/GraphMol/RascalMCES/Wrap/rdRascalMCES.cpp b/Code/GraphMol/RascalMCES/Wrap/rdRascalMCES.cpp index 1d2d7a888..55cad4285 100644 --- a/Code/GraphMol/RascalMCES/Wrap/rdRascalMCES.cpp +++ b/Code/GraphMol/RascalMCES/Wrap/rdRascalMCES.cpp @@ -99,7 +99,7 @@ python::list findMCESWrapper(const ROMol &mol1, const ROMol &mol2, std::vector> extractMols(python::object mols) { std::vector> cmols; - unsigned int nElems = python::extract(mols.attr("__len__")()); + unsigned int nElems = python::len(mols); cmols.resize(nElems); for (unsigned int i = 0; i < nElems; ++i) { if (!mols[i]) { diff --git a/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp b/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp index 01e539cdd..94da5a6c6 100644 --- a/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp +++ b/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp @@ -80,22 +80,18 @@ python::tuple getConfBox(const Conformer &conf, } python::tuple getUnionOfTwoBox(python::tuple box1, python::tuple box2) { - unsigned int len1 = python::extract(box1.attr("__len__")()); - unsigned int len2 = python::extract(box2.attr("__len__")()); + unsigned int len1 = python::len(box1); + unsigned int len2 = python::len(box2); if ((len1 != 2) || (len2 != 2)) { throw_value_error( "In correct format for one of the box: expecting a tuple of two " "Point3D"); } - RDGeom::Point3D lC1 = - python::extract(box1.attr("__getitem__")(0)); - RDGeom::Point3D uC1 = - python::extract(box1.attr("__getitem__")(1)); + RDGeom::Point3D lC1 = python::extract(box1[0]); + RDGeom::Point3D uC1 = python::extract(box1[1]); - RDGeom::Point3D lC2 = - python::extract(box2.attr("__getitem__")(0)); - RDGeom::Point3D uC2 = - python::extract(box2.attr("__getitem__")(1)); + RDGeom::Point3D lC2 = python::extract(box2[0]); + RDGeom::Point3D uC2 = python::extract(box2[1]); RDGeom::Point3D lowerCorner, upperCorner; MolShapes::computeUnionBox(lC1, uC1, lC2, uC2, lowerCorner, upperCorner); diff --git a/Code/GraphMol/Wrap/Conformer.cpp b/Code/GraphMol/Wrap/Conformer.cpp index 5d939d321..83a5c7422 100644 --- a/Code/GraphMol/Wrap/Conformer.cpp +++ b/Code/GraphMol/Wrap/Conformer.cpp @@ -95,21 +95,24 @@ void SetPos(Conformer *conf, np::ndarray const &array) { RDGeom::POINT3D_VECT &pos = conf->getPositions(); if (array.shape(1) == 2) { for (size_t i = 0; i < conf->getNumAtoms(); ++i) { - pos[i].x = * reinterpret_cast(dataptr + i * stride_atom); - pos[i].y = * reinterpret_cast(dataptr + i * stride_atom + stride_dim); + pos[i].x = *reinterpret_cast(dataptr + i * stride_atom); + pos[i].y = *reinterpret_cast(dataptr + i * stride_atom + + stride_dim); pos[i].z = 0.0; } } else { for (size_t i = 0; i < conf->getNumAtoms(); ++i) { - pos[i].x = * reinterpret_cast(dataptr + i * stride_atom); - pos[i].y = * reinterpret_cast(dataptr + i * stride_atom + stride_dim); - pos[i].z = * reinterpret_cast(dataptr + i * stride_atom + 2 * stride_dim); + pos[i].x = *reinterpret_cast(dataptr + i * stride_atom); + pos[i].y = *reinterpret_cast(dataptr + i * stride_atom + + stride_dim); + pos[i].z = *reinterpret_cast(dataptr + i * stride_atom + + 2 * stride_dim); } } } void SetAtomPos(Conformer *conf, unsigned int aid, python::object loc) { // const std::vector &loc) { - int dim = python::extract(loc.attr("__len__")()); + unsigned int dim = python::len(loc); CHECK_INVARIANT(dim == 3, ""); PySequenceHolder pdata(loc); RDGeom::Point3D pt(pdata[0], pdata[1], pdata[2]); @@ -154,8 +157,8 @@ struct conformer_wrapper { .def("SetAtomPosition", SetAtomPos, python::args("self", "aid", "loc"), "Set the position of the specified atom\n") .def("SetAtomPosition", - (void(Conformer::*)(unsigned int, const RDGeom::Point3D &)) & - Conformer::setAtomPos, + (void (Conformer::*)( + unsigned int, const RDGeom::Point3D &))&Conformer::setAtomPos, python::args("self", "atomId", "position"), "Set the position of the specified atom\n") @@ -294,7 +297,7 @@ struct conformer_wrapper { (python::arg("self"), python::arg("includePrivate") = false, python::arg("includeComputed") = false, python::arg("autoConvertStrings") = true), - getPropsAsDictDocString.c_str()); + getPropsAsDictDocString.c_str()); }; }; } // namespace RDKit diff --git a/Code/GraphMol/Wrap/MolOps.cpp b/Code/GraphMol/Wrap/MolOps.cpp index 1ae925577..e873eb5fc 100644 --- a/Code/GraphMol/Wrap/MolOps.cpp +++ b/Code/GraphMol/Wrap/MolOps.cpp @@ -56,8 +56,7 @@ python::tuple fragmentOnSomeBondsHelper(const ROMol &mol, std::vector> *dummyLabels = nullptr; if (pyDummyLabels) { - unsigned int nVs = - python::extract(pyDummyLabels.attr("__len__")()); + unsigned int nVs = python::len(pyDummyLabels); dummyLabels = new std::vector>(nVs); for (unsigned int i = 0; i < nVs; ++i) { unsigned int v1 = python::extract(pyDummyLabels[i][0]); @@ -67,8 +66,7 @@ python::tuple fragmentOnSomeBondsHelper(const ROMol &mol, } std::vector *bondTypes = nullptr; if (pyBondTypes) { - unsigned int nVs = - python::extract(pyBondTypes.attr("__len__")()); + unsigned int nVs = python::len(pyBondTypes); if (nVs != bondIndices->size()) { throw_value_error("bondTypes shorter than bondIndices"); } @@ -129,8 +127,7 @@ ROMol *fragmentOnBondsHelper(const ROMol &mol, python::object pyBondIndices, } std::vector> *dummyLabels = nullptr; if (pyDummyLabels) { - unsigned int nVs = - python::extract(pyDummyLabels.attr("__len__")()); + unsigned int nVs = python::len(pyDummyLabels); dummyLabels = new std::vector>(nVs); for (unsigned int i = 0; i < nVs; ++i) { unsigned int v1 = python::extract(pyDummyLabels[i][0]); @@ -140,8 +137,7 @@ ROMol *fragmentOnBondsHelper(const ROMol &mol, python::object pyBondIndices, } std::vector *bondTypes = nullptr; if (pyBondTypes) { - unsigned int nVs = - python::extract(pyBondTypes.attr("__len__")()); + unsigned int nVs = python::len(pyBondTypes); if (nVs != bondIndices->size()) { throw_value_error("bondTypes shorter than bondIndices"); } @@ -153,8 +149,7 @@ ROMol *fragmentOnBondsHelper(const ROMol &mol, python::object pyBondIndices, std::vector *cutsPerAtom = nullptr; if (pyCutsPerAtom) { cutsPerAtom = new std::vector; - unsigned int nAts = - python::extract(pyCutsPerAtom.attr("__len__")()); + unsigned int nAts = python::len(pyCutsPerAtom); if (nAts < mol.getNumAtoms()) { throw_value_error("cutsPerAtom shorter than the number of atoms"); } @@ -176,8 +171,7 @@ ROMol *fragmentOnBondsHelper(const ROMol &mol, python::object pyBondIndices, } ROMol *renumberAtomsHelper(const ROMol &mol, python::object &pyNewOrder) { - if (python::extract(pyNewOrder.attr("__len__")()) < - mol.getNumAtoms()) { + if (python::len(pyNewOrder) < mol.getNumAtoms()) { throw_value_error("atomCounts shorter than the number of atoms"); } auto newOrder = pythonObjectToVect(pyNewOrder, mol.getNumAtoms()); @@ -210,8 +204,7 @@ python::dict splitMolByPDBResidues(const ROMol &mol, python::object pyWhiteList, bool negateList) { std::vector *whiteList = nullptr; if (pyWhiteList) { - unsigned int nVs = - python::extract(pyWhiteList.attr("__len__")()); + unsigned int nVs = python::len(pyWhiteList); whiteList = new std::vector(nVs); for (unsigned int i = 0; i < nVs; ++i) { (*whiteList)[i] = python::extract(pyWhiteList[i]); @@ -234,8 +227,7 @@ python::dict splitMolByPDBChainId(const ROMol &mol, python::object pyWhiteList, bool negateList) { std::vector *whiteList = nullptr; if (pyWhiteList) { - unsigned int nVs = - python::extract(pyWhiteList.attr("__len__")()); + unsigned int nVs = python::len(pyWhiteList); whiteList = new std::vector(nVs); for (unsigned int i = 0; i < nVs; ++i) { (*whiteList)[i] = python::extract(pyWhiteList[i]); @@ -285,12 +277,12 @@ python::dict parseQueryDefFileHelper(python::object &input, bool standardize, void addRecursiveQueriesHelper(ROMol &mol, python::dict replDict, std::string propName) { std::map replacements; - for (unsigned int i = 0; - i < python::extract(replDict.keys().attr("__len__")()); - ++i) { - ROMol *m = python::extract(replDict.values()[i]); + const auto items = replDict.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + ROMol *m = python::extract(item[1]); ROMOL_SPTR nm(new ROMol(*m)); - std::string k = python::extract(replDict.keys()[i]); + std::string k = python::extract(item[0]); replacements[k] = nm; } addRecursiveQueries(mol, replacements, propName); @@ -628,8 +620,7 @@ ExplicitBitVect *wrapLayeredFingerprint( std::unique_ptr> atomCountsV; if (atomCounts) { atomCountsV.reset(new std::vector); - unsigned int nAts = - python::extract(atomCounts.attr("__len__")()); + unsigned int nAts = python::len(atomCounts); if (nAts < mol.getNumAtoms()) { throw_value_error("atomCounts shorter than the number of atoms"); } @@ -659,8 +650,7 @@ ExplicitBitVect *wrapPatternFingerprint(const ROMol &mol, unsigned int fpSize, std::vector *atomCountsV = nullptr; if (atomCounts) { atomCountsV = new std::vector; - unsigned int nAts = - python::extract(atomCounts.attr("__len__")()); + unsigned int nAts = python::len(atomCounts); if (nAts < mol.getNumAtoms()) { throw_value_error("atomCounts shorter than the number of atoms"); } @@ -859,8 +849,7 @@ ROMol *pathToSubmolHelper(const ROMol &mol, python::object &path, bool useQuery, python::object atomMap) { ROMol *result; PATH_TYPE pth; - for (unsigned int i = 0; - i < python::extract(path.attr("__len__")()); ++i) { + for (unsigned int i = 0; i < python::len(path); ++i) { pth.push_back(python::extract(path[i])); } std::map mapping; @@ -921,13 +910,14 @@ ROMol *replaceCoreHelper(const ROMol &mol, const ROMol &core, // convert input to MatchVect MatchVectType matchVect; - unsigned int length = python::extract(match.attr("__len__")()); - + unsigned int length = python::len(match); for (unsigned int i = 0; i < length; ++i) { - int sz = 1; - if (PyObject_HasAttrString(static_cast(match[i]).ptr(), - "__len__")) { - sz = python::extract(match[i].attr("__len__")()); + // This is what boost::python::len() does internally + auto pyObj = static_cast(match[i]).ptr(); + unsigned int sz = PyObject_Length(pyObj); + if (PyErr_Occurred()) { + PyErr_Clear(); + sz = 1; } int v1, v2; @@ -973,7 +963,7 @@ void setDoubleBondNeighborDirectionsHelper(ROMol &mol, python::object confObj) { void setAtomSymbols(MolzipParams &p, python::object symbols) { p.atomSymbols.clear(); if (symbols) { - unsigned int nVs = python::extract(symbols.attr("__len__")()); + unsigned int nVs = python::len(symbols); for (unsigned int i = 0; i < nVs; ++i) { p.atomSymbols.push_back(python::extract(symbols[i])); } diff --git a/Code/GraphMol/Wrap/RingInfo.cpp b/Code/GraphMol/Wrap/RingInfo.cpp index d2eab2302..6df70e992 100644 --- a/Code/GraphMol/Wrap/RingInfo.cpp +++ b/Code/GraphMol/Wrap/RingInfo.cpp @@ -64,9 +64,8 @@ python::object bondRingFamilies(const RingInfo *self) { #endif 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__")()); + unsigned int nAts = boost::python::len(atomRing); + unsigned int nBnds = boost::python::len(bondRing); if (nAts != nBnds) { throw_value_error("list sizes must match"); } diff --git a/Code/GraphMol/Wrap/SubstanceGroup.cpp b/Code/GraphMol/Wrap/SubstanceGroup.cpp index ef89abbe0..62f013e34 100644 --- a/Code/GraphMol/Wrap/SubstanceGroup.cpp +++ b/Code/GraphMol/Wrap/SubstanceGroup.cpp @@ -62,7 +62,7 @@ SubstanceGroup *addMolSubstanceGroup(ROMol &mol, const SubstanceGroup &sgroup) { } void addBracketHelper(SubstanceGroup &self, python::object pts) { - unsigned int sz = python::extract(pts.attr("__len__")()); + unsigned int sz = boost::python::len(pts); if (sz != 2 && sz != 3) { throw_value_error("pts object have a length of 2 or 3"); } @@ -211,37 +211,38 @@ struct sgroup_wrap { python::args("self")) .def("SetProp", - (void(RDProps::*)(const std::string &, std::string, bool) const) & + (void (RDProps::*)(const std::string &, std::string, bool) const) & SubstanceGroup::setProp, (python::arg("self"), python::arg("key"), python::arg("val"), python::arg("computed") = false), "sets the value of a particular property") .def("SetDoubleProp", - (void(RDProps::*)(const std::string &, double, bool) const) & + (void (RDProps::*)(const std::string &, double, bool) const) & SubstanceGroup::setProp, (python::arg("self"), python::arg("key"), python::arg("val"), python::arg("computed") = false), "sets the value of a particular property") .def("SetIntProp", - (void(RDProps::*)(const std::string &, int, bool) const) & + (void (RDProps::*)(const std::string &, int, bool) const) & SubstanceGroup::setProp, (python::arg("self"), python::arg("key"), python::arg("val"), python::arg("computed") = false), "sets the value of a particular property") - .def("SetUnsignedProp", - (void(RDProps::*)(const std::string &, unsigned int, bool) const) & - SubstanceGroup::setProp, - (python::arg("self"), python::arg("key"), python::arg("val"), - python::arg("computed") = false), - "sets the value of a particular property") + .def( + "SetUnsignedProp", + (void (RDProps::*)(const std::string &, unsigned int, bool) const) & + SubstanceGroup::setProp, + (python::arg("self"), python::arg("key"), python::arg("val"), + python::arg("computed") = false), + "sets the value of a particular property") .def("SetBoolProp", - (void(RDProps::*)(const std::string &, bool, bool) const) & + (void (RDProps::*)(const std::string &, bool, bool) const) & SubstanceGroup::setProp, (python::arg("self"), python::arg("key"), python::arg("val"), python::arg("computed") = false), "sets the value of a particular property") .def("HasProp", - (bool(RDProps::*)(const std::string &) const) & + (bool (RDProps::*)(const std::string &) const) & SubstanceGroup::hasProp, python::args("self", "key"), "returns whether or not a particular property exists") @@ -259,7 +260,7 @@ struct sgroup_wrap { "will be raised.\n", boost::python::return_value_policy()) .def("GetIntProp", - (int(RDProps::*)(const std::string &) const) & + (int (RDProps::*)(const std::string &) const) & SubstanceGroup::getProp, python::args("self", "key"), "returns the value of a particular property") @@ -269,26 +270,27 @@ struct sgroup_wrap { python::args("self", "key"), "returns the value of a particular property") .def("GetDoubleProp", - (double(RDProps::*)(const std::string &) const) & + (double (RDProps::*)(const std::string &) const) & SubstanceGroup::getProp, python::args("self", "key"), "returns the value of a particular property") .def("GetBoolProp", - (bool(RDProps::*)(const std::string &) const) & + (bool (RDProps::*)(const std::string &) const) & SubstanceGroup::getProp, python::args("self", "key"), "returns the value of a particular property") - .def( - "GetUnsignedVectProp", - (std::vector(RDProps::*)(const std::string &) const) & - SubstanceGroup::getProp>, - python::args("self", "key"), - "returns the value of a particular property") - .def("GetStringVectProp", - (std::vector(RDProps::*)(const std::string &) const) & - SubstanceGroup::getProp>, + .def("GetUnsignedVectProp", + (std::vector (RDProps::*)(const std::string &) + const) & + SubstanceGroup::getProp>, python::args("self", "key"), "returns the value of a particular property") + .def( + "GetStringVectProp", + (std::vector (RDProps::*)(const std::string &) const) & + SubstanceGroup::getProp>, + python::args("self", "key"), + "returns the value of a particular property") .def("GetPropNames", &SubstanceGroup::getPropList, (python::arg("self"), python::arg("includePrivate") = false, python::arg("includeComputed") = false), @@ -302,7 +304,7 @@ struct sgroup_wrap { "SubstanceGroup.\n" " n.b. some properties cannot be converted to python types.\n") .def("ClearProp", - (void(RDProps::*)(const std::string &) const) & + (void (RDProps::*)(const std::string &) const) & SubstanceGroup::clearProp, python::args("self", "key"), "Removes a particular property (does nothing if not set).\n\n"); diff --git a/Code/GraphMol/Wrap/rdmolfiles.cpp b/Code/GraphMol/Wrap/rdmolfiles.cpp index a04f68206..a1b961911 100644 --- a/Code/GraphMol/Wrap/rdmolfiles.cpp +++ b/Code/GraphMol/Wrap/rdmolfiles.cpp @@ -64,11 +64,11 @@ std::string pyObjectToString(python::object input) { ROMol *MolFromSmiles(python::object ismiles, bool sanitize, python::dict replDict) { std::map replacements; - for (unsigned int i = 0; - i < python::extract(replDict.keys().attr("__len__")()); - ++i) { - replacements[python::extract(replDict.keys()[i])] = - python::extract(replDict.values()[i]); + const auto items = replDict.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + replacements[python::extract(item[0])] = + python::extract(item[1]); } RWMol *newM; std::string smiles = pyObjectToString(ismiles); @@ -83,11 +83,11 @@ ROMol *MolFromSmiles(python::object ismiles, bool sanitize, ROMol *MolFromSmarts(python::object ismarts, bool mergeHs, python::dict replDict) { std::map replacements; - for (unsigned int i = 0; - i < python::extract(replDict.keys().attr("__len__")()); - ++i) { - replacements[python::extract(replDict.keys()[i])] = - python::extract(replDict.values()[i]); + const auto items = replDict.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + replacements[python::extract(item[0])] = + python::extract(item[1]); } std::string smarts = pyObjectToString(ismarts); @@ -642,11 +642,12 @@ python::object addMetadataToPNGFileHelper(python::dict pymetadata, std::string cstr = python::extract(fname); std::vector> metadata; - for (unsigned int i = 0; - i < python::extract(pymetadata.keys().attr("__len__")()); - ++i) { - std::string key = python::extract(pymetadata.keys()[i]); - std::string val = python::extract(pymetadata.values()[i]); + + const auto items = pymetadata.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + std::string key = python::extract(item[0]); + std::string val = python::extract(item[1]); metadata.push_back(std::make_pair(key, val)); } @@ -662,11 +663,11 @@ python::object addMetadataToPNGStringHelper(python::dict pymetadata, std::string cstr = python::extract(png); std::vector> metadata; - for (unsigned int i = 0; - i < python::extract(pymetadata.keys().attr("__len__")()); - ++i) { - std::string key = python::extract(pymetadata.keys()[i]); - std::string val = python::extract(pymetadata.values()[i]); + const auto items = pymetadata.items(); + for (unsigned int i = 0; i < python::len(items); ++i) { + const auto item = items[i]; + std::string key = python::extract(item[0]); + std::string val = python::extract(item[1]); metadata.push_back(std::make_pair(key, val)); } diff --git a/Code/RDBoost/PySequenceHolder.h b/Code/RDBoost/PySequenceHolder.h index 208a64b29..9642ad79c 100644 --- a/Code/RDBoost/PySequenceHolder.h +++ b/Code/RDBoost/PySequenceHolder.h @@ -41,7 +41,7 @@ class PySequenceHolder { unsigned int size() const { unsigned int res = 0; try { - res = python::extract(d_seq.attr("__len__")()); + res = boost::python::len(d_seq); } catch (...) { throw_value_error("sequence does not support length query"); } diff --git a/Code/SimDivPickers/Wrap/LeaderPicker.cpp b/Code/SimDivPickers/Wrap/LeaderPicker.cpp index 983c853b9..87a12ef98 100644 --- a/Code/SimDivPickers/Wrap/LeaderPicker.cpp +++ b/Code/SimDivPickers/Wrap/LeaderPicker.cpp @@ -34,8 +34,7 @@ void LazyLeaderHelper(LeaderPicker *picker, T functor, unsigned int poolSize, python::object firstPicks, RDKit::INT_VECT &res, int nThreads) { RDKit::INT_VECT firstPickVect; - for (unsigned int i = 0; - i < python::extract(firstPicks.attr("__len__")()); ++i) { + for (unsigned int i = 0; i < boost::python::len(firstPicks); ++i) { firstPickVect.push_back(python::extract(firstPicks[i])); } res = picker->lazyPick(functor, poolSize, pickSize, firstPickVect, threshold, diff --git a/Code/SimDivPickers/Wrap/MaxMinPicker.cpp b/Code/SimDivPickers/Wrap/MaxMinPicker.cpp index 546028a46..976a600e7 100644 --- a/Code/SimDivPickers/Wrap/MaxMinPicker.cpp +++ b/Code/SimDivPickers/Wrap/MaxMinPicker.cpp @@ -47,8 +47,7 @@ RDKit::INT_VECT MaxMinPicks(MaxMinPicker *picker, python::object distMat, auto *dMat = (double *)PyArray_DATA(copy); RDKit::INT_VECT firstPickVect; - for (unsigned int i = 0; - i < python::extract(firstPicks.attr("__len__")()); ++i) { + for (unsigned int i = 0; i < boost::python::len(firstPicks); ++i) { firstPickVect.push_back(python::extract(firstPicks[i])); } RDKit::INT_VECT res; @@ -68,8 +67,7 @@ void LazyMaxMinHelper(MaxMinPicker *picker, T functor, unsigned int poolSize, unsigned int pickSize, python::object firstPicks, int seed, RDKit::INT_VECT &res, double &threshold) { RDKit::INT_VECT firstPickVect; - for (unsigned int i = 0; - i < python::extract(firstPicks.attr("__len__")()); ++i) { + for (unsigned int i = 0; i < boost::python::len(firstPicks); ++i) { firstPickVect.push_back(python::extract(firstPicks[i])); } res = picker->lazyPick(functor, poolSize, pickSize, firstPickVect, seed, diff --git a/External/CoordGen/Wrap/rdCoordGen.cpp b/External/CoordGen/Wrap/rdCoordGen.cpp index 0166a4703..1c8722b90 100644 --- a/External/CoordGen/Wrap/rdCoordGen.cpp +++ b/External/CoordGen/Wrap/rdCoordGen.cpp @@ -25,8 +25,7 @@ namespace { void SetCoordMap(CoordGen::CoordGenParams *self, python::dict &coordMap) { self->coordMap.clear(); python::list ks = coordMap.keys(); - for (unsigned int i = 0; - i < python::extract(ks.attr("__len__")()); i++) { + for (unsigned int i = 0; i < boost::python::len(ks); ++i) { unsigned int id = python::extract(ks[i]); self->coordMap[id] = python::extract(coordMap[id]); } diff --git a/External/FreeSASA/Wrap/rdFreeSASA.cpp b/External/FreeSASA/Wrap/rdFreeSASA.cpp index e339585c9..1aeb01db9 100644 --- a/External/FreeSASA/Wrap/rdFreeSASA.cpp +++ b/External/FreeSASA/Wrap/rdFreeSASA.cpp @@ -71,7 +71,7 @@ double calcSASAHelper(const RDKit::ROMol &mol, python::object radii, std::vector vradii; - unsigned int sz = python::extract(radii.attr("__len__")()); + unsigned int sz = boost::python::len(radii); for (unsigned int i = 0; i < sz; ++i) { vradii.push_back(python::extract(radii[i])()); }