File: example12.cpp

package info (click to toggle)
rdkit 202503.6-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 222,000 kB
  • sloc: cpp: 411,111; python: 78,482; ansic: 26,181; java: 8,285; javascript: 4,404; sql: 2,393; yacc: 1,626; lex: 1,267; cs: 1,090; makefile: 581; xml: 229; fortran: 183; sh: 121
file content (65 lines) | stat: -rw-r--r-- 2,260 bytes parent folder | download | duplicates (2)
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
//
// Preserving molecules - example12.cpp

#include <fstream>
#include <iostream>
#include <string>
#include <GraphMol/GraphMol.h>
#include <GraphMol/MolPickler.h>
#include <GraphMol/FileParsers/MolSupplier.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>

int main(int argc, char **argv) {
  std::shared_ptr<RDKit::ROMol> mol1(RDKit::SmilesToMol("c1ccncc1"));
  std::string pickle;
  RDKit::MolPickler::pickleMol(*mol1, pickle);
  RDKit::ROMol mol2;
  RDKit::MolPickler::molFromPickle(pickle, mol2);
  std::cout << RDKit::MolToSmiles(mol2) << std::endl;

  // writing to pickle file
  std::string smi_file = getenv("RDBASE");
  smi_file += "/Code/GraphMol/test_data/canonSmiles.long.smi";
  std::string pkl_name = "canonSmiles.long.bin";

  // tab-delimited file, SMILES in column 0, name in 1, no title line
  RDKit::SmilesMolSupplier suppl(smi_file, "\t", 0, 1, false);
  std::ofstream pickle_ostream(pkl_name.c_str(), std::ios_base::binary);
  int write_cnt = 0;
  while (!suppl.atEnd()) {
    std::shared_ptr<RDKit::ROMol> mol(suppl.next());
    // write all props (including _Name) to the pickle.  Default is not to:
    // RDKit::MolPickler::pickleMol( *mol , pickle_ostream);
    // RDKit::MolPickler::pickleMol( *mol , pickle_ostream,
    // RDKit::PicklerOps::NoProps);
    RDKit::MolPickler::pickleMol(*mol, pickle_ostream,
                                 RDKit::PicklerOps::AllProps);
    ++write_cnt;
  }
  pickle_ostream.close();
  std::cout << "Wrote " << write_cnt << " molecules" << std::endl;

  // reading from pickle file
  std::ifstream pickle_istream(pkl_name.c_str(), std::ios_base::binary);
  int read_cnt = 0;
  while (!pickle_istream.eof()) {
    RDKit::ROMol mol3;
    try {
      RDKit::MolPickler::molFromPickle(pickle_istream, mol3);
    } catch (RDKit::MolPicklerException &e) {
      break;
    }
    if (!read_cnt) {
      try {
        std::cout << "Read mol of name : " << mol3.getProp<std::string>("_Name")
                  << std::endl;
      } catch (KeyErrorException &e) {
        std::cerr << "Pickle read error : " << e.what() << std::endl;
      }
    }
    ++read_cnt;
  }
  pickle_istream.close();
  std::cout << "Read " << read_cnt << " molecules." << std::endl;
}