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
|
//
// Copyright (C) 2023 Novartis Biomedical Research
//
// @@ 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 <cmath>
#include <regex>
#include <sstream>
#include "Pipeline.h"
#include "Validate.h"
#include "Metal.h"
#include "Normalize.h"
#include "Charge.h"
#include "Fragment.h"
#include <RDGeneral/FileParseException.h>
#include <GraphMol/FileParsers/FileParsers.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/Chirality.h>
namespace RDKit {
namespace MolStandardize {
void PipelineResult::append(PipelineStatus newStatus, const std::string &info) {
status = static_cast<PipelineStatus>(status | newStatus);
log.push_back({newStatus, info});
}
PipelineResult Pipeline::run(const std::string &molblock) const {
PipelineResult result;
result.status = NO_EVENT;
result.inputMolData = molblock;
// parse the molblock into an RWMol instance
result.stage = static_cast<uint32_t>(PipelineStage::PARSING_INPUT);
RWMOL_SPTR mol = parse(molblock, result, options);
if (!mol || ((result.status & PIPELINE_ERROR) != NO_EVENT &&
!options.reportAllFailures)) {
return result;
}
RWMOL_SPTR_PAIR output;
// we try sanitization and validation on a copy, because we want to preserve
// the original input molecule for later
RWMOL_SPTR molCopy{new RWMol(*mol)};
for (const auto &[stage, operation] : validationSteps) {
result.stage = stage;
molCopy = operation(molCopy, result, options);
if (!molCopy || ((result.status & PIPELINE_ERROR) != NO_EVENT &&
!options.reportAllFailures)) {
return result;
}
}
for (const auto &[stage, operation] : standardizationSteps) {
result.stage = stage;
mol = operation(mol, result, options);
if (!mol || ((result.status & PIPELINE_ERROR) != NO_EVENT &&
!options.reportAllFailures)) {
return result;
}
}
if (makeParent) {
result.stage = static_cast<uint32_t>(PipelineStage::MAKE_PARENT);
output = makeParent(mol, result, options);
if (!output.first || !output.second ||
((result.status & PIPELINE_ERROR) != NO_EVENT &&
!options.reportAllFailures)) {
return result;
}
} else {
output = {mol, mol};
}
// serialize as MolBlocks
result.stage = static_cast<uint32_t>(PipelineStage::SERIALIZING_OUTPUT);
serialize(output, result, options);
if ((result.status & PIPELINE_ERROR) != NO_EVENT &&
!options.reportAllFailures) {
return result;
}
result.stage = static_cast<uint32_t>(PipelineStage::COMPLETED);
return result;
}
namespace Operations {
RWMOL_SPTR parse(const std::string &molblock, PipelineResult &result,
const PipelineOptions &options) {
v2::FileParsers::MolFileParserParams params;
// we don't want to sanitize the molecule at this stage
params.sanitize = false;
// Hs wouldn't be anyway removed if the mol is not sanitized
params.removeHs = false;
// strict parsing is configurable via the pipeline options
params.strictParsing = options.strictParsing;
RWMOL_SPTR mol{};
try {
mol.reset(v2::FileParsers::MolFromMolBlock(molblock, params).release());
} catch (FileParseException &e) {
result.append(INPUT_ERROR, e.what());
}
if (!mol) {
result.append(INPUT_ERROR,
"Could not instantiate a valid molecule from input");
}
return mol;
}
void serialize(RWMOL_SPTR_PAIR output, PipelineResult &result,
const PipelineOptions &options) {
const ROMol &outputMol = *output.first;
const ROMol &parentMol = *output.second;
try {
if (!options.outputV2000) {
result.outputMolData = MolToV3KMolBlock(outputMol);
result.parentMolData = MolToV3KMolBlock(parentMol);
} else {
try {
result.outputMolData = MolToV2KMolBlock(outputMol);
result.parentMolData = MolToV2KMolBlock(parentMol);
} catch (ValueErrorException &e) {
result.append(OUTPUT_ERROR,
"Can't write molecule to V2000 output format: " +
std::string(e.what()));
}
}
} catch (const std::exception &e) {
result.append(OUTPUT_ERROR, "Can't write molecule to output format: " +
std::string(e.what()));
} catch (...) {
result.append(
OUTPUT_ERROR,
"An unexpected error occurred while serializing the output structures.");
}
}
RWMOL_SPTR prepareForValidation(RWMOL_SPTR mol, PipelineResult &result,
const PipelineOptions &) {
// Prepare the mol for validation.
try {
// The general intention is about validating the original input, and
// therefore limit the sanitization to the minimum, but it's not very useful
// to record a valence validation error for issues like a badly drawn nitro
// group that would be later fixed during by the normalization step.
//
// Some sanitization also needs to be performed in order to assign the
// stereochemistry (which needs to happen prior to reapplying the wedging,
// see below), and we need to find radicals, in order to support the
// corresponding validation criterion.
constexpr unsigned int sanitizeOps =
(MolOps::SANITIZE_CLEANUP | MolOps::SANITIZE_SYMMRINGS |
MolOps::SANITIZE_CLEANUP_ORGANOMETALLICS |
MolOps::SANITIZE_FINDRADICALS);
unsigned int failedOp = 0;
MolOps::sanitizeMol(*mol, failedOp, sanitizeOps);
// We want to restore the original MolBlock wedging, but this step may in
// some cases overwrite the ENDDOWNRIGHT/ENDUPRIGHT info that describes the
// configuration of double bonds adjacent to stereocenters. We therefore
// first assign the stereochemistry, and then restore the wedging.
constexpr bool cleanIt = true;
constexpr bool force = true;
constexpr bool flagPossible = true;
MolOps::assignStereochemistry(*mol, cleanIt, force, flagPossible);
Chirality::reapplyMolBlockWedging(*mol);
} catch (MolSanitizeException &) {
result.append(
PREPARE_FOR_VALIDATION_ERROR,
"An error occurred while preparing the molecule for validation.");
}
return mol;
}
namespace {
// The error messages from the ValidationMethod classes include some metadata
// in a string prefix that are not particularly useful within the context of
// this Pipeline. The function below removes that prefix.
static const std::regex prefix("^(ERROR|INFO): \\[.+\\] ");
std::string removeErrorPrefix(const std::string &message) {
return std::regex_replace(message, prefix, "");
}
} // namespace
RWMOL_SPTR validate(RWMOL_SPTR mol, PipelineResult &result,
const PipelineOptions &options) {
auto applyValidation = [&mol, &result, &options](
const ValidationMethod &v,
PipelineStatus status) -> bool {
auto errors = v.validate(*mol, options.reportAllFailures);
for (const auto &error : errors) {
result.append(status, removeErrorPrefix(error));
}
return errors.empty();
};
// check for undesired features in the input molecule (e.g., query
// atoms/bonds)
FeaturesValidation featuresValidation(options.allowEnhancedStereo,
options.allowAromaticBondType,
options.allowDativeBondType);
if (!applyValidation(featuresValidation, FEATURES_VALIDATION_ERROR) &&
!options.reportAllFailures) {
return mol;
}
// check the number of atoms and valence status
RDKitValidation rdkitValidation(options.allowEmptyMolecules);
if (!applyValidation(rdkitValidation, BASIC_VALIDATION_ERROR) &&
!options.reportAllFailures) {
return mol;
}
// disallow radicals
DisallowedRadicalValidation radicalValidation;
if (!applyValidation(radicalValidation, BASIC_VALIDATION_ERROR) &&
!options.reportAllFailures) {
return mol;
}
// validate the isotopic numbers (if any are specified)
IsotopeValidation isotopeValidation(true);
if (!applyValidation(isotopeValidation, BASIC_VALIDATION_ERROR) &&
!options.reportAllFailures) {
return mol;
}
// verify that the input is a 2D structure
Is2DValidation is2DValidation(options.is2DZeroThreshold);
if (!applyValidation(is2DValidation, IS2D_VALIDATION_ERROR) &&
!options.reportAllFailures) {
return mol;
}
// validate the 2D layout (check for clashing atoms and abnormally long bonds)
Layout2DValidation layout2DValidation(
options.atomClashLimit, options.bondLengthLimit,
options.allowLongBondsInRings, options.allowAtomBondClashExemption,
options.minMedianBondLength);
if (!applyValidation(layout2DValidation, LAYOUT2D_VALIDATION_ERROR) &&
!options.reportAllFailures) {
return mol;
}
// verify that the specified stereochemistry is formally correct
StereoValidation stereoValidation;
if (!applyValidation(stereoValidation, STEREO_VALIDATION_ERROR) &&
!options.reportAllFailures) {
return mol;
}
return mol;
}
RWMOL_SPTR prepareForStandardization(RWMOL_SPTR mol, PipelineResult &result,
const PipelineOptions &) {
// Prepare the mol for standardization.
try {
MolOps::sanitizeMol(*mol);
} catch (MolSanitizeException &) {
result.append(
PREPARE_FOR_STANDARDIZATION_ERROR,
"An error occurred while preparing the molecule for standardization.");
}
return mol;
}
RWMOL_SPTR standardize(RWMOL_SPTR mol, PipelineResult &result,
const PipelineOptions &options) {
auto smiles = MolToSmiles(*mol);
auto reference = smiles;
// bonding to metals
try {
MetalDisconnectorOptions mdOpts;
MetalDisconnector metalDisconnector(mdOpts);
std::unique_ptr<ROMol> metalNof{SmartsToMol(options.metalNof)};
metalDisconnector.setMetalNof(*metalNof);
std::unique_ptr<ROMol> metalNon{SmartsToMol(options.metalNon)};
metalDisconnector.setMetalNon(*metalNon);
metalDisconnector.disconnectInPlace(*mol);
} catch (...) {
result.append(
METAL_STANDARDIZATION_ERROR,
"An error occurred while processing the bonding of metal species.");
return mol;
}
smiles = MolToSmiles(*mol);
if (smiles != reference) {
result.append(METALS_DISCONNECTED,
"One or more metal atoms were disconnected.");
}
reference = smiles;
// functional groups
try {
std::unique_ptr<Normalizer> normalizer{};
if (options.normalizerData.empty()) {
normalizer.reset(new Normalizer);
} else {
std::istringstream sstr(options.normalizerData);
normalizer.reset(new Normalizer(sstr, options.normalizerMaxRestarts));
}
// normalizeInPlace() may return an ill-formed molecule if
// the sanitization of a transformed structure failed
// => use normalize() instead (also see GitHub #7189)
mol.reset(static_cast<RWMol *>(normalizer->normalize(*mol)));
mol->updatePropertyCache(false);
} catch (...) {
result.append(
NORMALIZER_STANDARDIZATION_ERROR,
"An error occurred while normalizing the representation of some functional groups");
return mol;
}
smiles = MolToSmiles(*mol);
if (smiles != reference) {
result.append(NORMALIZATION_APPLIED,
"The representation of some functional groups was adjusted.");
}
reference = smiles;
// keep the largest fragment
try {
LargestFragmentChooser fragmentChooser;
fragmentChooser.chooseInPlace(*mol);
} catch (...) {
result.append(
FRAGMENT_STANDARDIZATION_ERROR,
"An error occurred while removing the disconnected fragments");
return mol;
}
smiles = MolToSmiles(*mol);
if (smiles != reference) {
result.append(
FRAGMENTS_REMOVED,
"One or more disconnected fragments (e.g., counterions) were removed.");
}
// The stereochemistry is not assigned until after we are done modifying the
// molecular graph:
constexpr bool cleanIt = true;
constexpr bool force = true;
constexpr bool flagPossible = true;
MolOps::assignStereochemistry(*mol, cleanIt, force, flagPossible);
return mol;
}
RWMOL_SPTR reapplyWedging(RWMOL_SPTR mol, PipelineResult &result,
const PipelineOptions &) {
// in general, we want to restore the bond wedging from the input molblock,
// but we prefer to not use any wavy bonds, because of their ambiguity
// in some configurations.
// we therefore proceed in two steps, we first reapply the molblock wedging
// and then revert the changes related to double bonds with undefined/unknown
// stereochemistry and change single bonds with "unknown" direction into plain
// single bonds.
// in order to do so, we need to keep track of the current bond configuration
// settings.
using BondInfo = std::tuple<Bond::BondType, Bond::BondDir, Bond::BondStereo>;
std::map<unsigned int, BondInfo> oldBonds;
for (auto bond : mol->bonds()) {
oldBonds[bond->getIdx()] = {bond->getBondType(), bond->getBondDir(),
bond->getStereo()};
}
// 1) restore the original wedging from the input MolBlock
Chirality::reapplyMolBlockWedging(*mol);
// 2) revert the changes related to double bonds with stereo type "either":
// restore the STEREOANY direction of double bonds that have a substituent
// with direction UNKNOWN and are now STEREONONE
for (auto bond : mol->bonds()) {
if (bond->getBondType() != Bond::DOUBLE) {
continue;
}
Bond::BondStereo oldStereo = std::get<2>(oldBonds[bond->getIdx()]);
Bond::BondStereo newStereo = bond->getStereo();
bool hasAdjacentWavy{false};
for (auto atom : {bond->getBeginAtom(), bond->getEndAtom()}) {
for (auto adjacentBond : mol->atomBonds(atom)) {
if (adjacentBond == bond) {
continue;
}
if (adjacentBond->getBondDir() == Bond::UNKNOWN) {
hasAdjacentWavy = true;
}
}
}
if (hasAdjacentWavy && oldStereo == Bond::STEREOANY &&
newStereo == Bond::STEREONONE) {
bond->setStereo(Bond::STEREOANY);
result.append(
NORMALIZATION_APPLIED,
"Double bond " + std::to_string(bond->getIdx()) +
" was assigned an undefined/unknown stereochemical configuration");
}
}
// 3) set the bond direction to NONE for bonds with direction UNKNOWN
for (auto bond : mol->bonds()) {
if (bond->getBondDir() != Bond::UNKNOWN) {
continue;
}
bond->setBondDir(Bond::NONE);
result.append(NORMALIZATION_APPLIED, "The \"wavy\" style of bond " +
std::to_string(bond->getIdx()) +
" was removed");
}
return mol;
}
RWMOL_SPTR cleanup2D(RWMOL_SPTR mol, PipelineResult & /*result*/,
const PipelineOptions &options) {
// scale the atoms coordinates
// and make sure that z coords are set to 0 (some z coords may be non-null
// albeit smaller than the validation threshold - these noisy coords may in
// some cases also interfere with the perception of stereochemistry by some
// tools e.g., inchi)
if (options.scaledMedianBondLength > 0. && mol->getNumConformers()) {
auto &conf = mol->getConformer();
double medianBondLength =
sqrt(Layout2DValidation::squaredMedianBondLength(*mol, conf));
if (medianBondLength > options.minMedianBondLength) {
double scaleFactor = options.scaledMedianBondLength / medianBondLength;
unsigned int natoms = conf.getNumAtoms();
for (unsigned int i = 0; i < natoms; ++i) {
auto pos = conf.getAtomPos(i) * scaleFactor;
pos.z = 0.;
conf.setAtomPos(i, pos);
}
}
}
return mol;
}
namespace {
void replaceDativeBonds(RWMOL_SPTR mol) {
bool modified{false};
for (auto bond : mol->bonds()) {
if (bond->getBondType() != Bond::BondType::DATIVE) {
continue;
}
auto donor = bond->getBeginAtom();
donor->setFormalCharge(donor->getFormalCharge() + 1);
auto acceptor = bond->getEndAtom();
acceptor->setFormalCharge(acceptor->getFormalCharge() - 1);
bond->setBondType(Bond::BondType::SINGLE);
modified = true;
}
if (modified) {
mol->updatePropertyCache(false);
}
}
void removeHsAtProtonatedSites(RWMOL_SPTR mol) {
boost::dynamic_bitset<> protons{mol->getNumAtoms(), 0};
for (auto atom : mol->atoms()) {
if (atom->getAtomicNum() != 1 || atom->getDegree() != 1) {
continue;
}
for (auto neighbor : mol->atomNeighbors(atom)) {
if (neighbor->getFormalCharge() > 0) {
protons.set(atom->getIdx());
}
}
}
if (protons.any()) {
for (int idx = mol->getNumAtoms() - 1; idx >= 0; --idx) {
if (!protons[idx]) {
continue;
}
auto atom = mol->getAtomWithIdx(idx);
for (auto bond : mol->atomBonds(atom)) {
auto neighbor = bond->getOtherAtom(atom);
neighbor->setNumExplicitHs(neighbor->getNumExplicitHs() + 1);
break; // there are no other bonds anyways
}
mol->removeAtom(atom);
}
mol->updatePropertyCache(false);
}
}
} // namespace
RWMOL_SPTR_PAIR makeParent(RWMOL_SPTR mol, PipelineResult &result,
const PipelineOptions &) {
auto reference = MolToSmiles(*mol);
RWMOL_SPTR parent{new RWMol(*mol)};
// A "parent" structure is constructed here, in order to provide a
// representation of the original input that may be more suitable for
// identification purposes even though it may not reflect the most stable
// physical state or nicest representation for the compound.
//
// The two steps that are currently implemented for this procedure consist in
// normalizing the overall charge status and replacing any explicit dative
// bonds.
//
// If the input was submitted in an unsuitable protonation status, the
// neutralized parent structure may become the actual output from the
// standardization.
// overall charge status
try {
// The Uncharger implementation wouldn't identify the positively
// charged sites with adjacent explicit Hs correctly (it's a quite
// unlikely configuration, but potentially possible considering that
// the pipeline operates on unsanitized input).
//
// If present, these Hs are therefore removed from the molecular graph
// prior to neutralization.
removeHsAtProtonatedSites(parent);
static const bool canonicalOrdering = false;
static const bool force = true;
static const bool protonationOnly = true;
Uncharger uncharger(canonicalOrdering, force, protonationOnly);
uncharger.unchargeInPlace(*parent);
} catch (...) {
result.append(
CHARGE_STANDARDIZATION_ERROR,
"An error occurred while normalizing the compound's charge status");
return {{}, {}};
}
// Check if `mol` was submitted in a suitable ionization state
int parentCharge{};
for (auto atom : parent->atoms()) {
parentCharge += atom->getFormalCharge();
}
int molCharge{};
for (auto atom : mol->atoms()) {
molCharge += atom->getFormalCharge();
}
// If mol is neutral or in a protonation state that partially or fully
// balances the non-neutralizable charged sites in the parent structure,
// then mol is accepted. Otherwise, it is replaced by its parent.
if ((molCharge > 0 && molCharge > parentCharge) ||
(molCharge < 0 && molCharge < parentCharge)) {
mol = parent;
}
auto smiles = MolToSmiles(*mol);
if (smiles != reference) {
result.append(PROTONATION_CHANGED, "The protonation state was adjusted.");
}
reference = smiles;
// normalize the dative bonds
replaceDativeBonds(parent);
return {mol, parent};
}
} // namespace Operations
} // namespace MolStandardize
} // namespace RDKit
|