File: TDTMolSupplier.cpp

package info (click to toggle)
rdkit 201809.1%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 123,688 kB
  • sloc: cpp: 230,509; python: 70,501; java: 6,329; ansic: 5,427; sql: 1,899; yacc: 1,739; lex: 1,243; makefile: 445; xml: 229; fortran: 183; sh: 123; cs: 93
file content (427 lines) | stat: -rw-r--r-- 12,947 bytes parent folder | download
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
// $Id$
//
//  Copyright (C) 2005-2008 Greg Landrum and 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.
//
#include <RDGeneral/BoostStartInclude.h>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <RDGeneral/BoostEndInclude.h>

#include <RDGeneral/BadFileException.h>
#include <RDGeneral/FileParseException.h>
#include <RDGeneral/RDLog.h>
#include "MolSupplier.h"
#include "FileParsers.h"
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <RDGeneral/LocaleSwitcher.h>


#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

namespace RDKit {
namespace TDTParseUtils {
typedef boost::tokenizer<boost::escaped_list_separator<char> > CommaTokenizer;

/*
 * if inStream is valid, we'll allow the numbers to be broken across multiple
 * lines.
 *
 * This will throw a boost::bad_lexical_cast exception if it hits a bogus number
 *
 */
template <typename T>
void ParseNumberList(std::string inLine, std::vector<T> &res,
                     std::istream *inStream = nullptr) {
  bool foundEnd = false;
  while (!foundEnd) {
    CommaTokenizer commaTok(inLine);
    for (CommaTokenizer::const_iterator commaTokIt = commaTok.begin();
         commaTokIt != commaTok.end(); commaTokIt++) {
      std::string number = *commaTokIt;
      bool atEnd = number.find(";>") != std::string::npos;
      boost::trim_if(number, boost::is_any_of(" \r\n\t;>"));
      if (number != "" && !atEnd) {
        res.push_back(boost::lexical_cast<T>(number));
      } else if (atEnd) {
        // that's it, we're done:
        foundEnd = true;
        break;
      }
    }
    if (foundEnd || !inStream || inStream->eof()) {
      break;
    } else {
      std::getline(*inStream, inLine);
    }
  }
  if (!foundEnd) {
    throw FileParseException("no end tag found for numeric list");
  }
}

}  // end of namespace TDTParseUtils

TDTMolSupplier::TDTMolSupplier() { init(); }

TDTMolSupplier::TDTMolSupplier(const std::string &fileName,
                               const std::string &nameRecord, int confId2D,
                               int confId3D, bool sanitize) {
  init();
  d_confId2D = confId2D;
  d_confId3D = confId3D;
  d_nameProp = nameRecord;
  // FIX: this binary moe of opening file is here because of a bug in VC++ 6.0
  // the function "tellg" does not work correctly if we do not open it this way
  // Need to check if this has been fixed in VC++ 7.0
  std::istream *tmpStream = nullptr;
  tmpStream = static_cast<std::istream *>(
      new std::ifstream(fileName.c_str(), std::ios_base::binary));
  if (!tmpStream || (!(*tmpStream)) || (tmpStream->bad())) {
    std::ostringstream errout;
    errout << "Bad input file " << fileName;
    throw BadFileException(errout.str());
  }

  dp_inStream = tmpStream;
  df_owner = true;
  this->advanceToNextRecord();
  d_molpos.push_back(dp_inStream->tellg());
  df_sanitize = sanitize;
  this->checkForEnd();
}

TDTMolSupplier::TDTMolSupplier(std::istream *inStream, bool takeOwnership,
                               const std::string &nameRecord, int confId2D,
                               int confId3D, bool sanitize) {
  CHECK_INVARIANT(inStream, "bad instream");
  CHECK_INVARIANT(!(inStream->eof()), "early EOF");
  init();
  dp_inStream = inStream;
  df_owner = takeOwnership;
  d_confId2D = confId2D;
  d_confId3D = confId3D;
  d_nameProp = nameRecord;
  this->advanceToNextRecord();
  d_molpos.push_back(dp_inStream->tellg());
  df_sanitize = sanitize;
  this->checkForEnd();
}

void TDTMolSupplier::init() {
  dp_inStream = nullptr;
  df_owner = false;
  df_end = false;
  d_len = -1;
  d_last = 0;
  d_line = 0;
}
TDTMolSupplier::~TDTMolSupplier() {
  if (df_owner && dp_inStream) {
    delete dp_inStream;
  }
}

void TDTMolSupplier::setData(const std::string &text,
                             const std::string &nameRecord, int confId2D,
                             int confId3D, bool sanitize) {
  if (dp_inStream && df_owner) delete dp_inStream;
  init();
  d_confId2D = confId2D;
  d_confId3D = confId3D;
  d_nameProp = nameRecord;
  std::istream *tmpStream = nullptr;
  tmpStream = static_cast<std::istream *>(
      new std::istringstream(text, std::ios_base::binary));
  dp_inStream = tmpStream;
  df_owner = true;
  this->advanceToNextRecord();
  d_molpos.push_back(dp_inStream->tellg());
  df_sanitize = sanitize;
  this->checkForEnd();
  POSTCONDITION(dp_inStream, "bad instream");
}

bool TDTMolSupplier::advanceToNextRecord() {
  PRECONDITION(dp_inStream, "no stream");
  std::streampos pos;
  bool res = false;
  while (1) {
    if (dp_inStream->eof()) return false;
    pos = dp_inStream->tellg();
    std::string inL;
    std::getline(*dp_inStream, inL);
    if (inL.find("$SMI<") == 0) {
      res = true;
      break;
    }
  }
  dp_inStream->clear();
  dp_inStream->seekg(pos);
  return res;
}

void TDTMolSupplier::checkForEnd() {
  PRECONDITION(dp_inStream, "no stream");
  if (dp_inStream->eof()) {
    df_end = true;
    // the -1 here is because by the time we get here we've already pushed on
    // the
    // position of the next line:
    d_len = d_molpos.size() - 1;
    return;
  }

  // we are not at the end of file, but check for blank lines:
  std::string tempStr;
  std::getline(*dp_inStream, tempStr);

  boost::trim_left_if(tempStr, boost::is_any_of(std::string(" \t\r\n")));

  if (tempStr.length() == 0) {
    df_end = true;
    // the -1 here is because by the time we get here we've already pushed on
    // the
    // position of the next line:
    d_len = d_molpos.size() - 1;
  }
  return;
}

void TDTMolSupplier::reset() {
  PRECONDITION(dp_inStream, "no stream");
  dp_inStream->clear();

  dp_inStream->seekg(0, std::ios::beg);
  df_end = false;
  d_last = 0;
  d_line = 0;
}

ROMol *TDTMolSupplier::parseMol(std::string inLine) {
  PRECONDITION(dp_inStream, "no stream");
  Utils::LocaleSwitcher ls;
  std::size_t startP = inLine.find("<");
  std::size_t endP = inLine.find_last_of(">");
  std::string smiles = inLine.substr(startP + 1, endP - startP - 1);
  ROMol *res = SmilesToMol(smiles, 0, df_sanitize);

  if (res && res->getNumAtoms() > 0) {
    // -----------
    //   Process the properties:
    d_line++;
    std::getline(*dp_inStream, inLine);
    while (!dp_inStream->eof() && inLine.find("|") != 0) {
      endP = inLine.find("<");
      std::string propName = inLine.substr(0, endP);
      boost::trim_if(propName, boost::is_any_of(" \t"));
      startP = endP + 1;

      if (propName == common_properties::TWOD && d_confId2D >= 0) {
        std::string rest = inLine.substr(startP, inLine.size() - startP);
        std::vector<double> coords;
        TDTParseUtils::ParseNumberList(rest, coords, dp_inStream);
        auto *conf = new Conformer(res->getNumAtoms());
        conf->setId(d_confId2D);
        conf->set3D(false);
        for (unsigned int atIdx = 0; atIdx < res->getNumAtoms(); atIdx++) {
          if (2 * atIdx + 1 < coords.size()) {
            conf->setAtomPos(
                atIdx,
                RDGeom::Point3D(coords[2 * atIdx], coords[2 * atIdx + 1], 0.0));
          } else {
            // we're going to let this slide... but maybe we should do something
            // else?
          }
        }
        res->addConformer(conf, false);
      } else if (propName == "3D" && d_confId3D >= 0) {
        std::string rest = inLine.substr(startP, inLine.size() - startP);
        std::vector<double> coords;
        TDTParseUtils::ParseNumberList(rest, coords, dp_inStream);
        auto *conf = new Conformer(res->getNumAtoms());
        conf->setId(d_confId3D);
        conf->set3D(true);
        for (unsigned int atIdx = 0; atIdx < res->getNumAtoms(); atIdx++) {
          if (3 * atIdx + 2 < coords.size()) {
            conf->setAtomPos(
                atIdx, RDGeom::Point3D(coords[3 * atIdx], coords[3 * atIdx + 1],
                                       coords[3 * atIdx + 2]));
          } else {
            // we're going to let this slide... but maybe we should do something
            // else?
          }
        }
        res->addConformer(conf, false);
      } else {
        endP = inLine.find_last_of(">");
        if (endP == std::string::npos) {
          std::ostringstream errout;
          errout << "no end tag found for property" << propName;
          throw FileParseException(errout.str());
        } else {
          std::string propVal = inLine.substr(startP, endP - startP);
          res->setProp(propName, propVal);
          if (propName == d_nameProp)
            res->setProp(common_properties::_Name, propVal);
        }
      }
      std::getline(*dp_inStream, inLine);
    }
  }

  return res;
}

ROMol *TDTMolSupplier::next() {
  PRECONDITION(dp_inStream, "no stream");
  // set the stream to the appropriate position
  dp_inStream->seekg(d_molpos[d_last]);

  std::string tempStr;
  ROMol *res = nullptr;
  // finally if we reached the end of the file set end to be true
  if (dp_inStream->eof()) {
    // FIX: we should probably be throwing an exception here
    df_end = true;
    d_len = d_molpos.size();
    return res;
  }

  // start by finding the $SMI element (we're assuming that this starts the
  // block)
  std::string tempp;
  d_line++;
  std::getline(*dp_inStream, tempp);
  while (tempp.find("$SMI<") != 0 && !dp_inStream->eof()) {
    d_line++;
    std::getline(*dp_inStream, tempp);
  }
  if (tempp.find("$SMI<") == 0) {
    try {
      res = parseMol(tempp);
    } catch (MolSanitizeException &se) {
      // We couldn't sanitize a molecule we got - write out an error message and
      // move to
      BOOST_LOG(rdErrorLog)
          << "ERROR: Could not sanitize molecule ending on line " << d_line
          << std::endl;
      BOOST_LOG(rdErrorLog) << "ERROR: " << se.message() << "\n";
      while (!(dp_inStream->eof()) && tempStr.find("|") != 0) {
        d_line++;
        std::getline(*dp_inStream, tempStr);
      }
    }
  }
  d_last++;
  if (d_last >= static_cast<int>(d_molpos.size())) {
    d_molpos.push_back(dp_inStream->tellg());
  }
  this->checkForEnd();
  return res;
}

std::string TDTMolSupplier::getItemText(unsigned int idx) {
  PRECONDITION(dp_inStream, "no stream");
  unsigned int holder = d_last;
  moveTo(idx);
  std::streampos begP = d_molpos[idx];
  bool endHolder = df_end;
  std::streampos endP;
  try {
    moveTo(idx + 1);
    endP = d_molpos[idx + 1];
  } catch (FileParseException &) {
    dp_inStream->clear();
    dp_inStream->seekg(0, std::ios_base::end);
    endP = dp_inStream->tellg();
  }
  d_last = holder;
  df_end = endHolder;
  auto *buff = new char[endP - begP];
  dp_inStream->seekg(begP);
  dp_inStream->read(buff, endP - begP);
  std::string res(buff, endP - begP);
  delete[] buff;
  return res;
}

void TDTMolSupplier::moveTo(unsigned int idx) {
  PRECONDITION(dp_inStream, "no stream");

  // dp_inStream->seekg() is called for all idx values
  // and earlier calls to next() may have put the stream into a bad state
  dp_inStream->clear();

  // move until we hit the desired idx
  if (idx < d_molpos.size()) {
    dp_inStream->seekg(d_molpos[idx]);
    d_last = idx;
  } else {
    std::string tempStr;
    d_last = d_molpos.size() - 1;
    dp_inStream->seekg(d_molpos.back());
    while ((d_last < static_cast<int>(idx)) && (!dp_inStream->eof())) {
      d_line++;
      std::getline(*dp_inStream, tempStr);

      if (tempStr.find("|") == 0) {
        d_molpos.push_back(dp_inStream->tellg());
        d_last++;
      }
    }
    // if we reached end of file without reaching "idx" we have an index error
    if (dp_inStream->eof()) {
      d_len = d_molpos.size();
      std::ostringstream errout;
      errout << "ERROR: Index error (idx = " << idx << ") : "
             << " we do no have enough molecule blocks";
      throw FileParseException(errout.str());
    }
  }
}

ROMol *TDTMolSupplier::operator[](unsigned int idx) {
  PRECONDITION(dp_inStream, "no stream");
  // get the molecule with index idx
  moveTo(idx);
  return next();
}

unsigned int TDTMolSupplier::length() {
  PRECONDITION(dp_inStream, "no stream");
  // return the number of mol blocks in the sdfile
  if (d_len > 0) {
    return d_len;
  } else {
    std::string tempStr;
    d_len = d_molpos.size();
    dp_inStream->seekg(d_molpos.back());
    std::string inL;
    std::getline(*dp_inStream, inL);
    while (this->advanceToNextRecord()) {
      d_molpos.push_back(dp_inStream->tellg());
      d_len++;
      std::getline(*dp_inStream, inL);
    }
    // now remember to set the stream to the last postion we want to read
    dp_inStream->clear();
    dp_inStream->seekg(d_molpos[d_last]);
    return d_len;
  }
}

bool TDTMolSupplier::atEnd() {
  PRECONDITION(dp_inStream, "no stream");
  return df_end;
}
}