| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 
 | // $Id$
//
//  Copyright (C) 2003-2006 Rational Discovery LLC
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
#define PY_ARRAY_UNIQUE_SYMBOL rdchem_array_API
#include <RDBoost/Wrap.h>
#include "rdchem.h"
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SanitException.h>
#include <RDBoost/import_array.h>
#ifdef RDK_THREADSAFE_SSS
// Thread local storage for output buffer for RDKit Logging
#include <thread>
#endif
#include <sstream>
#include <utility>
#include "seqs.hpp"
namespace python = boost::python;
using namespace RDKit;
namespace RDKit {
void tossit() { throw IndexErrorException(1); }
}  // namespace RDKit
void rdExceptionTranslator(RDKit::ConformerException const &x) {
  RDUNUSED_PARAM(x);
  PyErr_SetString(PyExc_ValueError, "Bad Conformer Id");
}
void wrap_table();
void wrap_atom();
void wrap_conformer();
void wrap_bond();
void wrap_stereogroup();
void wrap_mol();
void wrap_ringinfo();
void wrap_EditableMol();
void wrap_monomerinfo();
void wrap_resmolsupplier();
void wrap_molbundle();
void wrap_sgroup();
void wrap_chirality();
struct PySysErrWrite : std::ostream, std::streambuf {
  std::string prefix;
  PySysErrWrite(std::string prefix)
      : std::ostream(this), prefix(std::move(prefix)) {}
  int overflow(int c) override {
    write(c);
    return 0;
  }
#ifdef RDK_THREADSAFE_SSS
  void write(char c) {  // enable thread safe logging
    static thread_local std::string buffer = "";
    buffer += c;
    if (c == '\n') {
      // Python IO is not thread safe, so grab the GIL
      {
        PyGILStateHolder h;
        PySys_WriteStderr("%s", (prefix + buffer).c_str());
      }
      buffer.clear();
    }
  }
#else
  std::string buffer;  // unlimited! flushes in endl
  void write(char c) {
    buffer += c;
    if (c == '\n') {
      PySys_WriteStderr("%s", (prefix + buffer).c_str());
      buffer.clear();
    }
  }
#endif
};
void RDLogError(const std::string &msg) {
  NOGIL gil;
  BOOST_LOG(rdErrorLog) << msg.c_str() << std::endl;
}
void RDLogWarning(const std::string &msg) {
  NOGIL gil;
  BOOST_LOG(rdWarningLog) << msg.c_str() << std::endl;
}
void WrapLogs() {
  static PySysErrWrite debug("RDKit DEBUG: ");
  static PySysErrWrite error("RDKit ERROR: ");
  static PySysErrWrite info("RDKit INFO: ");
  static PySysErrWrite warning("RDKit WARNING: ");
  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);
  }
}
python::tuple getAtomIndicesHelper(const KekulizeException &self) {
  python::list res;
  for (auto idx : self.getAtomIndices()) {
    res.append(idx);
  }
  return python::tuple(res);
}
PyObject *molSanitizeExceptionType = nullptr;
PyObject *atomSanitizeExceptionType = nullptr;
PyObject *atomValenceExceptionType = nullptr;
PyObject *atomKekulizeExceptionType = nullptr;
PyObject *kekulizeExceptionType = nullptr;
// pattern from here:
// https://stackoverflow.com/questions/11448735/boostpython-export-custom-exception-and-inherit-from-pythons-exception
template <typename EXC_TYPE>
void sanitExceptionTranslator(const EXC_TYPE &x, PyObject *pyExcType) {
  PRECONDITION(pyExcType != nullptr, "global type not initialized");
  python::object pyExcInstance(python::handle<>(python::borrowed(pyExcType)));
  pyExcInstance.attr("cause") = x;
  PyErr_SetString(pyExcType, x.what());
}
// pattern from here:
// https://stackoverflow.com/questions/9620268/boost-python-custom-exception-class
PyObject *createExceptionClass(const char *name,
                               PyObject *baseTypeObj = PyExc_ValueError) {
  std::string scopeName =
      python::extract<std::string>(python::scope().attr("__name__"));
  std::string qualifiedName0 = scopeName + "." + name;
  char *qualifiedName1 = const_cast<char *>(qualifiedName0.c_str());
  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;
}
template <typename O, typename T>
T *get_item_ptr(O &self, int i) {
  return self.get_item(i).get();
}
template <typename O, typename T>
T *next_ptr(O &self) {
  return self.next().get();
}
BOOST_PYTHON_MODULE(rdchem) {
  python::scope().attr("__doc__") =
      "Module containing the core chemistry functionality of the RDKit";
  RegisterListConverter<RDKit::Atom *>();
  RegisterListConverter<RDKit::Bond *>();
  RegisterListConverter<RDKit::CONFORMER_SPTR>();
  rdkit_import_array();
  // this is one of those parts where I think I wish that I knew how to do
  // template meta-programming
  python::class_<MolSanitizeException>("_cppMolSanitizeException",
                                       "exception arising from sanitization",
                                       python::no_init)
      .def("Message", &MolSanitizeException::what)
      .def("GetType", &MolSanitizeException::getType);
  python::register_ptr_to_python<boost::shared_ptr<MolSanitizeException>>();
  molSanitizeExceptionType = createExceptionClass("MolSanitizeException");
  python::register_exception_translator<RDKit::MolSanitizeException>(
      [&](const MolSanitizeException &exc) {
        sanitExceptionTranslator(exc, molSanitizeExceptionType);
      });
  python::class_<AtomSanitizeException, python::bases<MolSanitizeException>>(
      "_cppAtomSanitizeException", "exception arising from sanitization",
      python::no_init)
      .def("GetAtomIdx", &AtomSanitizeException::getAtomIdx);
  python::register_ptr_to_python<boost::shared_ptr<AtomSanitizeException>>();
  atomSanitizeExceptionType =
      createExceptionClass("AtomSanitizeException", molSanitizeExceptionType);
  python::register_exception_translator<RDKit::AtomSanitizeException>(
      [&](const AtomSanitizeException &exc) {
        sanitExceptionTranslator(exc, atomSanitizeExceptionType);
      });
  python::class_<AtomValenceException, python::bases<AtomSanitizeException>>(
      "_cppAtomValenceException", "exception arising from sanitization",
      python::no_init);
  python::register_ptr_to_python<boost::shared_ptr<AtomValenceException>>();
  atomValenceExceptionType =
      createExceptionClass("AtomValenceException", atomSanitizeExceptionType);
  python::register_exception_translator<RDKit::AtomValenceException>(
      [&](const AtomValenceException &exc) {
        sanitExceptionTranslator(exc, atomValenceExceptionType);
      });
  python::class_<AtomKekulizeException, python::bases<AtomSanitizeException>>(
      "_cppAtomKekulizeException", "exception arising from sanitization",
      python::no_init);
  python::register_ptr_to_python<boost::shared_ptr<AtomKekulizeException>>();
  atomKekulizeExceptionType =
      createExceptionClass("AtomKekulizeException", atomSanitizeExceptionType);
  python::register_exception_translator<RDKit::AtomKekulizeException>(
      [&](const AtomKekulizeException &exc) {
        sanitExceptionTranslator(exc, atomKekulizeExceptionType);
      });
  python::class_<KekulizeException, python::bases<MolSanitizeException>>(
      "_cppAtomKekulizeException", "exception arising from sanitization",
      python::no_init)
      .def("GetAtomIndices", &getAtomIndicesHelper);
  python::register_ptr_to_python<boost::shared_ptr<KekulizeException>>();
  kekulizeExceptionType =
      createExceptionClass("KekulizeException", molSanitizeExceptionType);
  python::register_exception_translator<RDKit::KekulizeException>(
      [&](const KekulizeException &exc) {
        sanitExceptionTranslator(exc, kekulizeExceptionType);
      });
  python::def("WrapLogs", WrapLogs,
              "Wrap the internal RDKit streams so they go to python's "
              "SysStdErr");
  python::def("LogWarningMsg", RDLogWarning,
              "Log a warning message to the RDKit warning logs");
  python::def("LogErrorMsg", RDLogError,
              "Log a warning message to the RDKit error logs");
  //*********************************************
  //
  //  Utility Classes
  //
  //*********************************************
  python::class_<AtomIterSeq>(
      "_ROAtomSeq",
      "Read-only sequence of atoms, not constructible from Python.",
      python::no_init)
      .def("__iter__", &AtomIterSeq::__iter__,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>())
      .def("__next__", &AtomIterSeq::next,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>())
      .def("__len__", &AtomIterSeq::len)
      .def("__getitem__", &AtomIterSeq::get_item,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>());
  python::class_<QueryAtomIterSeq>("_ROQAtomSeq",
                                   "Read-only sequence of atoms matching a "
                                   "query, not constructible from Python.",
                                   python::no_init)
      .def("__iter__", &QueryAtomIterSeq::__iter__,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>())
      .def("__next__", &QueryAtomIterSeq::next,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>())
      .def("__len__", &QueryAtomIterSeq::len)
      .def("__getitem__", &QueryAtomIterSeq::get_item,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>());
  python::class_<BondIterSeq>(
      "_ROBondSeq",
      "Read-only sequence of bonds, not constructible from Python.",
      python::no_init)
      .def("__iter__", &BondIterSeq::__iter__,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>())
      .def("__next__", &BondIterSeq::next,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>())
      .def("__len__", &BondIterSeq::len)
      .def("__getitem__", &BondIterSeq::get_item,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>());
  python::class_<ConformerIterSeq>(
      "_ROConformerSeq",
      "Read-only sequence of conformers, not constructible from Python.",
      python::no_init)
      .def("__iter__", &ConformerIterSeq::__iter__,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>())
      .def("__next__", next_ptr<ConformerIterSeq, Conformer>,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>())
      .def("__len__", &ConformerIterSeq::len)
      .def("__getitem__", get_item_ptr<ConformerIterSeq, Conformer>,
           python::return_internal_reference<
               1, python::with_custodian_and_ward_postcall<0, 1>>());
  //*********************************************
  //
  //  Classes
  //
  //*********************************************
  wrap_table();
  wrap_atom();
  wrap_conformer();
  wrap_bond();
  wrap_stereogroup();
  wrap_mol();
  wrap_EditableMol();
  wrap_ringinfo();
  wrap_monomerinfo();
  wrap_resmolsupplier();
  wrap_molbundle();
  wrap_sgroup();
  wrap_chirality();
  //*********************************************
  //
  //  Functions
  //
  //*********************************************
  std::string docString;
  python::def("tossit", tossit);
}
 |