1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
|
//
//
// Copyright (C) 2023 Schrödinger, LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include "MolWriters.h"
#include <fstream>
#include <functional>
#include <memory>
#include <regex>
#include <sstream>
#include <string>
#include <vector>
#include <maeparser/MaeBlock.hpp>
#include <maeparser/MaeConstants.hpp>
#include <maeparser/Writer.hpp>
#include <GraphMol/Depictor/RDDepictor.h>
#include <GraphMol/FileParsers/MaestroProperties.h>
#include <GraphMol/MolOps.h>
#include <GraphMol/MonomerInfo.h>
#include <GraphMol/RDKitBase.h>
#include <RDGeneral/BadFileException.h>
#include <RDGeneral/FileParseException.h>
#include <RDGeneral/RDLog.h>
using namespace schrodinger;
using namespace RDKit::FileParsers::schrodinger;
namespace RDKit {
namespace {
static const std::regex MMCT_PROP_REGEX("[birs]_[^_ ]+_.+");
template <typename T>
std::shared_ptr<mae::IndexedProperty<T>> getIndexedProperty(
mae::IndexedBlock &indexedBlock, const std::string &propName,
size_t numAtoms,
std::shared_ptr<mae::IndexedProperty<T>> (mae::IndexedBlock::*getterFunc)(
const std::string &) const,
void (mae::IndexedBlock::*setterFunc)(
const std::string &, std::shared_ptr<mae::IndexedProperty<T>>)) {
auto prop = (indexedBlock.*getterFunc)(propName);
if (prop != nullptr) {
return prop;
}
std::vector<T> values(numAtoms);
auto nullsBitset = new boost::dynamic_bitset<>(numAtoms);
nullsBitset->set();
auto newProp = std::make_shared<mae::IndexedProperty<T>>(values, nullsBitset);
(indexedBlock.*setterFunc)(propName, newProp);
return newProp;
}
template <typename T>
std::shared_ptr<mae::IndexedProperty<T>> getIndexedProperty(
mae::IndexedBlock &indexedBlock, const std::string &propName,
size_t numAtoms);
template <>
std::shared_ptr<mae::IndexedProperty<mae::BoolProperty>>
getIndexedProperty<mae::BoolProperty>(mae::IndexedBlock &indexedBlock,
const std::string &propName,
size_t numAtoms) {
if (propName[0] != 'b') {
auto msg =
std::string("Property '") + propName + "' is not a boolean value";
throw std::runtime_error(msg);
}
return getIndexedProperty<mae::BoolProperty>(
indexedBlock, propName, numAtoms, &mae::IndexedBlock::getBoolProperty,
&mae::IndexedBlock::setBoolProperty);
}
template <>
std::shared_ptr<mae::IndexedProperty<int>> getIndexedProperty<int>(
mae::IndexedBlock &indexedBlock, const std::string &propName,
size_t numAtoms) {
if (propName[0] != 'i') {
auto msg =
std::string("Property '") + propName + "' is not an integer value";
throw std::runtime_error(msg);
}
return getIndexedProperty<int>(indexedBlock, propName, numAtoms,
&mae::IndexedBlock::getIntProperty,
&mae::IndexedBlock::setIntProperty);
}
template <>
std::shared_ptr<mae::IndexedProperty<double>> getIndexedProperty<double>(
mae::IndexedBlock &indexedBlock, const std::string &propName,
size_t numAtoms) {
if (propName[0] != 'r') {
auto msg = std::string("Property '") + propName + "' is not a real value";
throw std::runtime_error(msg);
}
return getIndexedProperty<double>(indexedBlock, propName, numAtoms,
&mae::IndexedBlock::getRealProperty,
&mae::IndexedBlock::setRealProperty);
}
template <>
std::shared_ptr<mae::IndexedProperty<std::string>>
getIndexedProperty<std::string>(mae::IndexedBlock &indexedBlock,
const std::string &propName, size_t numAtoms) {
if (propName[0] != 's') {
auto msg = std::string("Property '") + propName + "' is not a string value";
throw std::runtime_error(msg);
}
return getIndexedProperty<std::string>(indexedBlock, propName, numAtoms,
&mae::IndexedBlock::getStringProperty,
&mae::IndexedBlock::setStringProperty);
}
void copyProperties(
const RDProps &origin, const STR_VECT &propNames, unsigned idx,
std::function<void(const std::string &, unsigned, bool)> boolSetter,
std::function<void(const std::string &, unsigned, int)> intSetter,
std::function<void(const std::string &, unsigned, double)> realSetter,
std::function<void(const std::string &, unsigned, const std::string &)>
stringSetter) {
// Map other properties, but first clear out the computed ones,
// since we don't want to export these.
origin.clearComputedProps();
for (const auto &prop : origin.getDict().getData()) {
// Skip the property holding the names of the computed properties
if (prop.key == detail::computedPropName) {
continue;
}
// Also skip the property if we have a list of properties we want to export
// and this one is not one of them.
if (!propNames.empty() && (std::find(propNames.begin(), propNames.end(),
prop.key) == propNames.end())) {
continue;
}
switch (prop.val.getTag()) {
case RDTypeTag::BoolTag: {
auto propName = prop.key;
if (!std::regex_match(prop.key, MMCT_PROP_REGEX)) {
propName.insert(0, "b_rdkit_");
}
boolSetter(propName, idx, rdvalue_cast<bool>(prop.val));
break;
}
case RDTypeTag::IntTag:
case RDTypeTag::UnsignedIntTag: {
auto propName = prop.key;
if (prop.key == common_properties::_MolFileRLabel) {
propName = MAE_RGROUP_LABEL;
} else if (!std::regex_match(prop.key, MMCT_PROP_REGEX)) {
propName.insert(0, "i_rdkit_");
}
intSetter(propName, idx, rdvalue_cast<int>(prop.val));
break;
}
case RDTypeTag::DoubleTag:
case RDTypeTag::FloatTag: {
auto propName = prop.key;
if (!std::regex_match(prop.key, MMCT_PROP_REGEX)) {
propName.insert(0, "r_rdkit_");
}
realSetter(propName, idx, rdvalue_cast<double>(prop.val));
break;
}
case RDTypeTag::StringTag: {
auto propName = prop.key;
if (!std::regex_match(prop.key, MMCT_PROP_REGEX)) {
propName.insert(0, "s_rdkit_");
}
stringSetter(propName, idx, rdvalue_cast<std::string>(prop.val));
break;
}
default:
// AnyTag, EmptyTag, any kind of Vector.
// Should we support vectors?
BOOST_LOG(rdWarningLog)
<< "WARNING: the property " << prop.key
<< " has an unsupported type, and will not be exported.";
continue;
}
}
}
template <typename T>
void setPropertyValue(mae::IndexedBlock &block, const std::string &propName,
size_t numValues, unsigned idx, const T &value) {
auto property = getIndexedProperty<T>(block, propName, numValues);
property->set(idx, value);
}
int bondTypeToOrder(const Bond &bond) {
switch (bond.getBondType()) {
case Bond::BondType::SINGLE:
return 1;
case Bond::BondType::DOUBLE:
return 2;
case Bond::BondType::TRIPLE:
return 3;
case Bond::BondType::ZERO:
case Bond::BondType::DATIVE:
return 0;
default:
throw ValueErrorException(
"Bond " + std::to_string(bond.getIdx()) +
" has a type that is not supported by maeparser.");
}
}
static bool isDoubleAnyBond(const RDKit::Bond &b) {
if (b.getBondType() == RDKit::Bond::DOUBLE) {
if (b.getStereo() == RDKit::Bond::BondStereo::STEREOANY ||
b.getBondDir() == RDKit::Bond::EITHERDOUBLE) {
return true;
}
// Check v3000/v2000 stereo either props
auto hasPropValue = [&b](const auto &prop, const int &either_value) {
return b.hasProp(prop) && b.getProp<int>(prop) == either_value;
};
return hasPropValue(RDKit::common_properties::_MolFileBondCfg, 2) ||
hasPropValue(RDKit::common_properties::_MolFileBondStereo, 3);
}
return false;
}
static void copyAtomNumChirality(const ROMol &mol, mae::Block &stBlock) {
// This property tells Schrodinger software that the stereo and chirality in
// the mae file are valid
stBlock.setIntProperty(MAE_STEREO_STATUS, 1);
// Set atom numbering chirality
int chiralAts = 0;
for (const auto at : mol.atoms()) {
std::string atomNumChirality;
if (at->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW) {
atomNumChirality = "ANR";
} else if (at->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW) {
atomNumChirality = "ANS";
} else {
continue;
}
++chiralAts;
std::string propName =
mae::CT_CHIRALITY_PROP_PREFIX + std::to_string(chiralAts);
std::string propVal =
std::to_string(at->getIdx() + 1) + "_" + atomNumChirality;
// We don't know CIP ranks of atoms, so instead we use atom numbering
// chirality and adjacent atoms will just be sorted by index.
std::vector<int> neighbors;
for (const auto nb : mol.atomNeighbors(at)) {
neighbors.push_back(nb->getIdx());
}
std::sort(neighbors.begin(), neighbors.end());
for (const auto nb : neighbors) {
propVal += "_" + std::to_string(nb + 1);
}
stBlock.setStringProperty(propName, propVal);
}
}
void mapMolProperties(const ROMol &mol, const STR_VECT &propNames,
mae::Block &stBlock) {
// We always write a title, even if the mol doesn't have one
// (in such case, we add an empty string).
std::string molName;
mol.getPropIfPresent(common_properties::_Name, molName);
stBlock.setStringProperty(mae::CT_TITLE, molName);
mol.clearProp(common_properties::_Name);
copyAtomNumChirality(mol, stBlock);
auto boolSetter = [&stBlock](const std::string &prop, unsigned, bool value) {
stBlock.setBoolProperty(prop, value);
};
auto intSetter = [&stBlock](const std::string &prop, unsigned, int value) {
stBlock.setIntProperty(prop, value);
};
auto realSetter = [&stBlock](const std::string &prop, unsigned,
double value) {
stBlock.setRealProperty(prop, value);
};
auto stringSetter = [&stBlock](const std::string &prop, unsigned,
const std::string &value) {
stBlock.setStringProperty(prop, value);
};
int fake_idx = 0;
copyProperties(mol, propNames, fake_idx, boolSetter, intSetter, realSetter,
stringSetter);
}
void mapAtom(
const Conformer &conformer, const Atom &atom, const STR_VECT &propNames,
mae::IndexedBlock &atomBlock, size_t numAtoms,
std::function<void(const std::string &, unsigned, bool)> boolSetter,
std::function<void(const std::string &, unsigned, int)> intSetter,
std::function<void(const std::string &, unsigned, double)> realSetter,
std::function<void(const std::string &, unsigned, const std::string &)>
stringSetter) {
auto idx = atom.getIdx();
auto coordinates = conformer.getAtomPos(idx);
// Required properties
setPropertyValue(atomBlock, mae::ATOM_X_COORD, numAtoms, idx, coordinates.x);
setPropertyValue(atomBlock, mae::ATOM_Y_COORD, numAtoms, idx, coordinates.y);
setPropertyValue(atomBlock, mae::ATOM_Z_COORD, numAtoms, idx, coordinates.z);
auto atomicNum = static_cast<int>(atom.getAtomicNum());
if (atomicNum == 0) {
// Maestro files use atomic number -2 to indicate a dummy atom.
atomicNum = -2;
}
setPropertyValue(atomBlock, mae::ATOM_ATOMIC_NUM, numAtoms, idx, atomicNum);
setPropertyValue(atomBlock, mae::ATOM_FORMAL_CHARGE, numAtoms, idx,
atom.getFormalCharge());
// Residue information
auto monomerInfo =
static_cast<const AtomPDBResidueInfo *>(atom.getMonomerInfo());
if (monomerInfo != nullptr) {
setPropertyValue(atomBlock, PDB_ATOM_NAME, numAtoms, idx,
monomerInfo->getName());
setPropertyValue(atomBlock, PDB_RESIDUE_NAME, numAtoms, idx,
monomerInfo->getResidueName());
setPropertyValue(atomBlock, PDB_CHAIN_NAME, numAtoms, idx,
monomerInfo->getChainId());
setPropertyValue(atomBlock, PDB_INSERTION_CODE, numAtoms, idx,
monomerInfo->getInsertionCode());
setPropertyValue(atomBlock, PDB_RESIDUE_NUMBER, numAtoms, idx,
monomerInfo->getResidueNumber());
setPropertyValue(atomBlock, PDB_OCCUPANCY, numAtoms, idx,
monomerInfo->getOccupancy());
setPropertyValue(atomBlock, PDB_TFACTOR, numAtoms, idx,
monomerInfo->getTempFactor());
}
// Custom properties
copyProperties(atom, propNames, idx, boolSetter, intSetter, realSetter,
stringSetter);
}
void mapAtoms(const ROMol &mol, const STR_VECT &propNames, int confId,
mae::IndexedBlockMap &indexedBlockMap) {
auto atomBlock = std::make_shared<mae::IndexedBlock>(mae::ATOM_BLOCK);
auto conformer = mol.getConformer(confId);
auto numAtoms = mol.getNumAtoms();
auto boolSetter = [&atomBlock, &numAtoms](const std::string &prop,
unsigned idx,
mae::BoolProperty value) {
setPropertyValue(*atomBlock, prop, numAtoms, idx, value);
};
auto intSetter = [&atomBlock, &numAtoms](const std::string &prop,
unsigned idx, int value) {
setPropertyValue(*atomBlock, prop, numAtoms, idx, value);
};
auto realSetter = [&atomBlock, &numAtoms](const std::string &prop,
unsigned idx, double value) {
setPropertyValue(*atomBlock, prop, numAtoms, idx, value);
};
auto stringSetter = [&atomBlock, &numAtoms](const std::string &prop,
unsigned idx,
const std::string &value) {
setPropertyValue(*atomBlock, prop, numAtoms, idx, value);
};
for (auto atom : mol.atoms()) {
mapAtom(conformer, *atom, propNames, *atomBlock, numAtoms, boolSetter,
intSetter, realSetter, stringSetter);
}
indexedBlockMap.addIndexedBlock(mae::ATOM_BLOCK, atomBlock);
}
void mapBond(
const Bond &bond,
std::shared_ptr<mae::IndexedProperty<mae::BoolProperty>> &dativeBondMark,
const STR_VECT &propNames, mae::IndexedBlock &bondBlock, size_t numBonds,
std::function<void(const std::string &, unsigned, bool)> boolSetter,
std::function<void(const std::string &, unsigned, int)> intSetter,
std::function<void(const std::string &, unsigned, double)> realSetter,
std::function<void(const std::string &, unsigned, const std::string &)>
stringSetter) {
auto idx = bond.getIdx();
// Indexes in the atom block are 1-based
auto bondTo = static_cast<int>(bond.getBeginAtomIdx()) + 1;
auto bondFrom = static_cast<int>(bond.getEndAtomIdx()) + 1;
// There is no bond directionality in Maestro, and atom indexes
// in bonds are usually written in ascending order
if (bondFrom > bondTo) {
std::swap(bondFrom, bondTo);
}
setPropertyValue(bondBlock, mae::BOND_ATOM_1, numBonds, idx, bondFrom);
setPropertyValue(bondBlock, mae::BOND_ATOM_2, numBonds, idx, bondTo);
setPropertyValue(bondBlock, mae::BOND_ORDER, numBonds, idx,
bondTypeToOrder(bond));
// Only set double bond stereo if stereo is 'unspecified', otherwise
// users can calculate double bond stereo from the coordinates.
if (isDoubleAnyBond(bond)) {
setPropertyValue(bondBlock, MAE_BOND_PARITY, numBonds, idx, 2);
}
if (dativeBondMark != nullptr) {
dativeBondMark->set(idx, (bond.getBondType() == Bond::BondType::DATIVE));
}
// Custom properties
copyProperties(bond, propNames, idx, boolSetter, intSetter, realSetter,
stringSetter);
}
void mapBonds(const ROMol &mol, const STR_VECT &propNames,
mae::IndexedBlockMap &indexedBlockMap) {
auto bondBlock = std::make_shared<mae::IndexedBlock>(mae::BOND_BLOCK);
auto numBonds = mol.getNumBonds();
std::shared_ptr<mae::IndexedProperty<mae::BoolProperty>> dativeBondMark =
nullptr;
for (auto &bond : mol.bonds()) {
if (bond->getBondType() == Bond::BondType::DATIVE) {
dativeBondMark = getIndexedProperty<mae::BoolProperty>(
*bondBlock, MAE_BOND_DATIVE_MARK, numBonds);
break;
}
}
auto boolSetter = [&bondBlock, &numBonds](const std::string &prop,
unsigned idx,
mae::BoolProperty value) {
setPropertyValue(*bondBlock, prop, numBonds, idx, value);
};
auto intSetter = [&bondBlock, &numBonds](const std::string &prop,
unsigned idx, int value) {
setPropertyValue(*bondBlock, prop, numBonds, idx, value);
};
auto realSetter = [&bondBlock, &numBonds](const std::string &prop,
unsigned idx, double value) {
setPropertyValue(*bondBlock, prop, numBonds, idx, value);
};
auto stringSetter = [&bondBlock, &numBonds](const std::string &prop,
unsigned idx,
const std::string &value) {
setPropertyValue(*bondBlock, prop, numBonds, idx, value);
};
for (auto bond : mol.bonds()) {
mapBond(*bond, dativeBondMark, propNames, *bondBlock, numBonds, boolSetter,
intSetter, realSetter, stringSetter);
}
indexedBlockMap.addIndexedBlock(mae::BOND_BLOCK, bondBlock);
}
std::shared_ptr<mae::Block> _MolToMaeCtBlock(const ROMol &mol, int confId,
const STR_VECT &propNames) {
if (mol.getNumAtoms() == 0) {
throw ValueErrorException(
"molecules without atoms cannot be exported to Maestro files.\n");
}
RWMol tmpMol(mol);
MolOps::Kekulize(tmpMol);
if (mol.getNumConformers() == 0) {
// make sure there's at least one conformer we can write
RDDepict::compute2DCoords(tmpMol);
}
auto stBlock = std::make_shared<mae::Block>(mae::CT_BLOCK);
mapMolProperties(tmpMol, propNames, *stBlock);
auto indexedBlockMap = std::make_shared<mae::IndexedBlockMap>();
mapAtoms(tmpMol, propNames, confId, *indexedBlockMap);
if (mol.getNumBonds() > 0) {
mapBonds(tmpMol, propNames, *indexedBlockMap);
}
stBlock->setIndexedBlockMap(indexedBlockMap);
return stBlock;
}
} // namespace
MaeWriter::MaeWriter(const std::string &fileName) {
auto *tmpStream = new std::ofstream(fileName.c_str());
if (!(*tmpStream) || (tmpStream->bad())) {
delete tmpStream;
std::ostringstream errout;
errout << "Bad output file " << fileName;
throw BadFileException(errout.str());
}
dp_ostream.reset(static_cast<std::ostream *>(tmpStream));
}
MaeWriter::MaeWriter(std::ostream *outStream) : dp_ostream{outStream} {
PRECONDITION(outStream, "null stream");
if (outStream->bad()) {
throw FileParseException("Bad output stream");
}
}
MaeWriter::MaeWriter(std::shared_ptr<std::ostream> outStream)
: dp_ostream{std::move(outStream)} {
PRECONDITION(outStream, "null stream");
if (outStream->bad()) {
throw FileParseException("Bad output stream");
}
}
MaeWriter::~MaeWriter() { close(); };
void MaeWriter::open() { dp_writer.reset(new mae::Writer(dp_ostream)); }
void MaeWriter::setProps(const STR_VECT &propNames) {
if (d_molid > 0) {
BOOST_LOG(rdWarningLog) << "WARNING: Setting property list after a few "
"molecules have been written\n";
}
d_props = propNames;
}
void MaeWriter::flush() {
PRECONDITION(dp_ostream, "no output stream");
try {
dp_ostream->flush();
} catch (...) {
try {
if (dp_ostream->good()) {
dp_ostream->setstate(std::ios::badbit);
}
} catch (const std::runtime_error &) {
}
}
}
void MaeWriter::close() {
if (dp_ostream && dp_ostream->good()) {
flush();
}
if (dp_writer) {
dp_writer.reset();
}
dp_ostream.reset();
}
void MaeWriter::write(const ROMol &mol, int confId) {
PRECONDITION(dp_ostream, "no output stream");
auto block = _MolToMaeCtBlock(mol, confId, d_props);
if (!dp_writer) {
open();
}
block->write(*dp_ostream);
++d_molid;
}
std::string MaeWriter::getText(const ROMol &mol, int confId,
const STR_VECT &propNames) {
std::stringstream sstr;
auto block = _MolToMaeCtBlock(mol, confId, propNames);
block->write(sstr);
return sstr.str();
}
} // namespace RDKit
|