1 //
2 // Preserving molecules - example12.cpp
3 
4 #include <fstream>
5 #include <iostream>
6 #include <string>
7 #include <GraphMol/GraphMol.h>
8 #include <GraphMol/MolPickler.h>
9 #include <GraphMol/FileParsers/MolSupplier.h>
10 #include <GraphMol/SmilesParse/SmilesParse.h>
11 #include <GraphMol/SmilesParse/SmilesWrite.h>
12 
main(int argc,char ** argv)13 int main( int argc , char **argv ) {
14 
15   std::shared_ptr<RDKit::ROMol> mol1( RDKit::SmilesToMol( "c1ccncc1" ) );
16   std::string pickle;
17   RDKit::MolPickler::pickleMol( *mol1 , pickle );
18   RDKit::ROMol mol2;
19   RDKit::MolPickler::molFromPickle( pickle , mol2 );
20   std::cout << RDKit::MolToSmiles( mol2 ) << std::endl;
21 
22   // writing to pickle file
23   std::string smi_file = getenv("RDBASE");
24   smi_file += "/Code/GraphMol/test_data/canonSmiles.long.smi";
25   std::string pkl_name = "canonSmiles.long.bin";
26 
27   // tab-delimited file, SMILES in column 0, name in 1, no title line
28   RDKit::SmilesMolSupplier suppl( smi_file , "\t" , 0 , 1 , false );
29   std::ofstream pickle_ostream( pkl_name.c_str() , std::ios_base::binary );
30   int write_cnt = 0;
31   while( !suppl.atEnd() ) {
32     std::shared_ptr<RDKit::ROMol> mol( suppl.next() );
33     // write all props (including _Name) to the pickle.  Default is not to:
34     // RDKit::MolPickler::pickleMol( *mol , pickle_ostream);
35     // RDKit::MolPickler::pickleMol( *mol , pickle_ostream, RDKit::PicklerOps::NoProps);
36     RDKit::MolPickler::pickleMol( *mol , pickle_ostream, RDKit::PicklerOps::AllProps );
37     ++write_cnt;
38   }
39   pickle_ostream.close();
40   std::cout << "Wrote " << write_cnt << " molecules" << std::endl;
41 
42   // reading from pickle file
43   std::ifstream pickle_istream( pkl_name.c_str() , std::ios_base::binary );
44   int read_cnt = 0;
45   while( !pickle_istream.eof() ) {
46     RDKit::ROMol mol3;
47     try {
48       RDKit::MolPickler::molFromPickle( pickle_istream , mol3 );
49     } catch( RDKit::MolPicklerException &e ) {
50       break;
51     }
52     if(!read_cnt) {
53       try {
54 	std::cout << "Read mol of name : "
55 		  << mol3.getProp<std::string>("_Name") << std::endl;
56       } catch(KeyErrorException &e) {
57 	std::cerr << "Pickle read error : " << e.what() << std::endl;
58       }
59     }
60     ++read_cnt;
61   }
62   pickle_istream.close();
63   std::cout << "Read " << read_cnt << " molecules." << std::endl;
64 
65 }
66 
67 
68