-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsmiley.h
2964 lines (2778 loc) · 89.4 KB
/
smiley.h
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) 2012, Tim Vandermeersch
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SMILEY_SMILEY_H
#define SMILEY_SMILEY_H
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <limits>
#include <iostream>
#include <cctype>
//#include <cassert>
#define DEBUG 0
//@cond DEV
namespace Smiley {
/**
* @mainpage
*
* Smiley is a SMILES/SMARTS parser that is OpenSMILES (http://www.opensmiles.org)
* compliant (draft 2007-11-13).
*
* @section usage Usage
*
* Smiley is a single header file which contains the Parser class in the
* Smiley namespace. User actions are invoked using a functor object that is
* specified when a Parser is instantiated. Below is a simple example which
* uses the PrintCallback to print the events as they occur. The example below
* also shows how to handle exceptions and print useful error reports.
*
* @code
* #include "smiley.h"
*
* using namespace Smiley;
*
* int main(int argc, char **argv)
* {
* PrintCallback callback;
* Parser<PrintCallback> parser(callback);
*
* try {
* parser.parse(argv[1]);
* } catch (Exception &e) {
* if (e.type() == Exception::SyntaxError)
* std::cerr << "Syntax";
* else
* std::cerr << "Semantics";
* std::cerr << "Error: " << e.what() << "." << std::endl;
* std::cerr << argv[1] << std::endl;
* for (std::size_t i = 0; i < e.pos(); ++i)
* std::cerr << " ";
* for (std::size_t i = 0; i < e.length(); ++i)
* std::cerr << "^";
* std::cerr << std::endl;
* }
* }
* @endcode
*
* Example of errors:
* @code
* SyntaxError: Bracket atom expression contains invalid trailing characters.
* F.FB(F)F.[NH2+251][C@@H](CP(c1ccccc1)c1ccccc1)C(C)(C)C 31586112
* ^^
* SyntaxError: Unmatched branch opening.
* CC(CC
* ^^^
* SyntaxError: Unmatched branch closing.
* CC)CC
* ^^^
* SemanticsError: Unmatched ring bond.
* C1CCC
* ^
* SemanticsError: Conflicing ring bonds.
* C-1CCCCC=1
* ^
* @endcode
*
* Although this is useful for debugging, using Smiley in an application
* requires a custom callback function object.
*
* @subsection callback Callback
* The callback function object type is a template parameter to the Parser
* class. The should be derived publicly from CallbackBase so unneeded methods
* do not have to be specified. For SMILES, the class may contain 4 methods:
*
* @code
* struct MyCustomCallback
* {
* void clear()
* {
* // prepare for new SMILES
* }
*
* void addAtom(int element, bool aromatic, int isotope, int hCount, int charge, int atomClass)
* {
* // invoked when an atom is completely parsed
*
* // element: 0, 1, 2, ... (0 is '*' in SMILES)
* // aromatic: true if the atom was lower case c, n, ...
* // isotope: -1, 0, 1, 2, 3, 4 ... (-1 means no isotope specified and is not the same as 0)
* // hCount: -1, 0, 1, 2, ..., 9 (-1 means default valence and is only for unbracketed atoms)
* // charge: -9, -8, ..., -1, 0, 1, ..., 8, 9
* // atomClass: 0, 1, 2, 3, 4, ... (0 means no atom class, specified atom classes should start from 1)
* }
*
* void addBond(int source, int target, int order, bool isUp, bool isDown)
* {
* // invoked for each bond once both of it's atoms have been added by
* // calling addAtom(). This ensures that the bond's atom indexes are always valid.
*
* // source: source atom index starting from 0 (order from addAtom() calls)
* // target: target atom index starting from 0 (order from addAtom() calls)
* // order: 1, 2, 3, 4, 5 (5 means aromatic)
* // isUp: true if bond is single order up bond '/'
* // isDown: true if bond is single order down bond '\'
* }
*
* void setChiral(int index, Chirality chirality, const std::vector<int> &chiralNbrs)
* {
* // invoked at the end of parsing for each chiral atom
*
* // index: atom index starting from 0
* // chirality: Clockwise, AntiClockwise, TH1, AL2, SP3, TB14, OH26, ...
* // chiralNbrs: atom indices of neighbors, size 4 for TH, AL and SP, size 5 for TB and 6 for OH
* }
* };
* @endcode
*
* @section smiles_semantics SMILES Semantics
*
* For a detailed description of the OpenSMILES semantics, the specification
* should be consulted. Apart for syntactical and grammatical correctness,
* Smiley als verifies some basic semantics. When a semantics error is found,
* an Exception is thrown with the corresponding ErrorCode. Some of these
* exceptions (UnmatchedRingBond, ConflictingRingBond, InvalidRingBond,
* InvalidChiralValence and InvalidChiralHydrogenCount) can be disabled using
* Parser::disableExceptions(). By default, all exceptions are enabled to
* ensure OpenSMILES compliance. The effect of disabling these exceptions is
* specified in subsequent subsections.
*
* @subsection semantics_HH Hydrogen with Hydrogen Count
* Hydrogen atoms can not have a hydrogen count. Hydrogen bound to a hydrogen
* atom should be specified by two bracket atom expressions. If such an
* expression is found during parsing, an Exception with ErrorCode
* HydrogenHydrogenCount is thrown.
*
* Eamples:
* @code
* [HH] invalid
* [HH1] invalid (same as [HH]
* [HH3] invalid
* [HH0] valid (same as [H])
* [H][H] valid
* @endcode
*
* @subsection semantics_unmatched_ringbond Unmatched Ring Bond
* When there is an unmatched ring bond, an Exception with ErrorCode
* UnmatchedRingBond will be thrown. Disabling this exception will
* ignore the ring bond(s).
*
* Example:
* @code
* C1CCC
* @endcode
*
* @subsection semantics_conflicing_ringbond Conflicting Ring Bonds
* When the bond type for ring bonds are explicitly specified at both ends,
* these should be the same. If not, an Exception with ErrorCode
* ConflictingRingBonds is thrown. Disabling this exception will use the
* first bond specification (i.e. a single bond in the example below).
*
* Example:
* @code
* C-1CCCCCC=1
* @endcode
*
* @subsection semantics_invalid_ringbond Invalid Ring Bonds
* There are two types of invalid ring bonds. The first is when two atoms both
* have the same two ring bonds. This would mean adding a parallel edge in the
* graph which is not allowed. The second type is similar but results in a
* self-loop by having a ring bond number twice. An Exception with ErrorCode
* InvalidRingBond is thrown when such a bond is encountered. Disabling this
* exception will ignore the invalid ring bonds.
*
* Eamples:
* @code
* C12CCCC12 parallel bond
* C11 self-loop bond
* @endcode
*
* @subsection semantics_chiral_valence Invalid Chiral Valence
* When an atom is specified as being chiral, it should have the correct
* number of neighboring atoms (possibly including an implicit H inside the
* bracket. An Exception with ErrorCode InvalidChiralValence is thrown when
* a valence is incorrect. Disabling this exception will result in no
* verification and leaves this to the Callback functor.
*
* The valid valences are:
* @code
* Tetrahedral (TH) : 4
* Allene (AL) : 4 (*)
* Square Planar (SP) : 4
* Trigonal Bypiramidal (TB) : 5
* Octahedral(OH) : 6
*
* (*) The chiral atom has only 2 bonds but the neighbor's neighbors are
* counted: NC(Br)=[C@AL1]=C(F)I
* @endcode
*
* @subsection semantics_chiral_hydrogens Invalid Chiral Hydrogen Count
* Chiral atoms can only have one hydrogen in their bracket since multiple
* hydrogens would make them not chiral. An Exception with ErrorCode
* InvalidChiralHydrogenCount is thrown when such an atom is encountered.
* Disabling this exception allows a chiral specification with a hydrogen
* count higher than 2. Note: only 1 implcitHydrogen() is added to nbrs.
*
* Example:
* @code
* C[C@H2]F
* @endcode
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* @section license License
* @code
* Copyright (c) 2012, Tim Vandermeersch
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* @endcode
*/
/**
* The elements.
*/
enum Elements {
H = 1, He,
Li, Be, B, C, N, O, F, Ne,
Na, Mg, Al, Si, P, S, Cl, Ar,
K, Ca, Sc, Ti, V, Cr, Mn, Fe, Co, Ni, Cu, Zn, Ga, Ge, As, Se, Br, Kr,
Rb, Sr, Y, Zr, Nb, Mo, Tc, Ru, Rh, Pd, Ag, Cd, In, Sn, Sb, Te, I, Xe,
Cs, Ba, La, Ce, Pr, Nd, Pm, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb, Lu, Hf, Ta, W, Re, Os, Ir, Pt, Au, Hg, Tl, Pb, Bi, Po, At, Rn,
Fr, Ra, Ac, Th, Pa, U, Np, Pu, Am, Cm, Bk, Cf, Es, Fm, Md, No, Lr, Rf, Db, Sg, Bh, Hs, Mt, Ds, Rg, Cn, Fl = 114, Lv = 116
};
/**
* Chirality classes.
*/
enum Chirality {
NotChiral = 0,
AntiClockwise, Clockwise,
TH1, TH2,
AL1, AL2,
SP1, SP2, SP3,
TB1, TB2, TB3, TB4, TB5, TB6, TB7, TB8, TB9, TB10,
TB11, TB12, TB13, TB14, TB15, TB16, TB17, TB18, TB19, TB20,
OH1, OH2, OH3, OH4, OH5, OH6, OH7, OH8, OH9, OH10,
OH11, OH12, OH13, OH14, OH15, OH16, OH17, OH18, OH19, OH20,
OH21, OH22, OH23, OH24, OH25, OH26, OH27, OH28, OH29, OH30
};
/**
* Error codes for Exception exceptions.
*/
enum ErrorCode {
////////////////////////////////////////
//
// SyntaxError
//
////////////////////////////////////////
/**
* No error
*/
None,
/**
* Example: "[C"
*/
NoClosingAtomBracket = 1,
/**
* Examples: "[]", "[13]", "[+]"
*/
NoSymbolInBracketAtom = 2,
/**
* Examples: "[C@@T]", "[C@@A]", "[C@@TB]", "[C@@TH99]", "[C@@OH0]"
*/
InvalidChirality = 3,
/**
* Example: "[C:]"
*/
NoAtomClass = 4,
/**
* Example: "CC(C"
*/
UnmatchedBranchOpening = 5,
/**
* Example: "CC)C"
*/
UnmatchedBranchClosing = 6,
/**
* Examples: "Q", "!", "&", "Mm", "r"
*/
InvalidAtomExpr = 7,
/**
* Example: "[13C$]", "[NP]"
*/
TrailingCharInBracketAtom = 8,
/**
* Example: ".C"
*/
LeadingDot = 9,
/**
* Example: "C."
*/
TrailingDot = 10,
/**
* Example: "C-", "C/"
*/
TrailingExplicitBond = 11,
/**
* Example: "C%123CC%123", "C%CC%"
*/
InvalidRingBondNumber = 12,
//////////////////
// SMARTS
//////////////////
/**
* Example: "[&C]"
*/
BinaryOpWithoutLeftOperand = 13,
/**
* Example: "[C&]"
*/
BinaryOpWithoutRightOperand = 14,
/**
* Example: "[C!]"
*/
UnaryOpWithoutArgument = 15,
/**
* Example: "[Q]"
*/
InvalidAtomPrimitive = 16,
/**
* Example: "C^C"
*/
InvalidBondPrimitive = 17,
////////////////////////////////////////
//
// SemanticsError
//
////////////////////////////////////////
/**
* Example: "[HH1]"
*/
HydrogenHydrogenCount = 32,
/**
* Example: "C1CC"
*/
UnmatchedRingBond = 64,
/**
* Example: "C-1CCCC=1"
*/
ConflictingRingBonds = 128,
/**
* Example: "C12CCCCC12", "C11"
*/
InvalidRingBond = 256,
/**
* Example: "C[C@H](F)(Cl)(Br)I", "O[C@]"
*/
InvalidChiralValence = 512,
/**
* Example: "N[C@H2](F)I"
*/
InvalidChiralHydrogenCount = 1024
};
/**
* Exception class.
*/
class Exception
{
public:
/**
* Exception type.
*/
enum Type { NoError, SyntaxError, SemanticsError };
/**
* Default Constructor.
*/
Exception() : m_type(NoError), m_errorCode(None), m_pos(0), m_length(0)
{
}
/**
* Constructor.
*
* @param type The exception type.
* @param errorCode The numeric error code.
* @param what Details of the exception.
* @param pos The position in the SMILES/SMARTS string.
* @param length The length of the error in the SMILES/SMARTS string.
*/
Exception(Type type, ErrorCode errorCode, const std::string &what, std::size_t pos, std::size_t length = 1)
: m_type(type), m_errorCode(errorCode), m_what(what), m_pos(pos), m_length(length)
{
}
/**
* The type of the exception.
*/
Type type() const
{
return m_type;
}
/**
* The ErrorCode for the exception.
*/
ErrorCode errorCode() const
{
return m_errorCode;
}
/**
* Details concerning the exception.
*/
const std::string& what() const
{
return m_what;
}
/**
* The position in the specified string where the error starts.
*/
std::size_t pos() const
{
return m_pos;
}
/**
* The length of the error.
*/
std::size_t length() const
{
return m_length;
}
private:
Type m_type;
ErrorCode m_errorCode;
std::string m_what;
std::size_t m_pos;
std::size_t m_length;
};
/**
* Value for implicit hydrogen in chiral nbrs.
*/
inline int implicitHydrogen()
{
return std::numeric_limits<int>::max();
}
enum SmartsLogicalOpType
{
OP_Not = 1,
OP_AndHi = 2,
OP_AndLo = 4,
OP_And = OP_AndHi | OP_AndLo, // 6
OP_Or = 7
};
enum SmartsAtomExprType
{
AE_True = 8,
AE_False,
AE_Aromatic,
AE_Aliphatic,
AE_Cyclic,
AE_Acyclic,
AE_Isotope,
AE_AtomicNumber,
AE_AromaticElement,
AE_AliphaticElement,
AE_Degree,
AE_Valence,
AE_Connectivity,
AE_TotalH,
AE_ImplicitH,
AE_RingMembership,
AE_RingSize,
AE_RingConnectivity,
AE_Charge,
AE_Chirality,
AE_AtomClass,
AE_Recursive
};
enum SmartsBondExprType
{
BE_True = AE_AtomClass + 1,
BE_False,
BE_Single,
BE_Double,
BE_Triple,
BE_Quadriple,
BE_Aromatic,
BE_Up,
BE_Down,
BE_Ring,
BE_UpUnspecified = BE_Single,
BE_DownUnspecified = BE_Single,
BE_Any = BE_True
};
/**
* Base class for Callback function objects.
*/
struct CallbackBase
{
//@name SMILES/SMARTS
//@{
/**
* Prepare the callback functor for a new SMILES/SMARTS. This method is
* always invoked at the start of parsing before any of the other methods.
*/
void clear() {}
/**
* Set the chirality for an atom. This method is invoked when the entire
* SMILES/SMARTS is parsed.
*/
void setChiral(int index, Chirality chirality, const std::vector<int> &chiralNbrs) {}
void end() {}
//@}
//@name SMILES
/**
* Invoked when an atom is completly parsed.
*/
void addAtom(int element, bool aromatic, int isotope, int hCount, int charge, int atomClass) {}
/**
* Invoked once both bon atom are added using addAtom().
*/
void addBond(int source, int target, int order, bool isUp, bool isDown) {}
//@}
//@name SMARTS
//@{
/**
* Invoked when a unary or binary logical operator is parsed
* (i.e. '&', ';' or ','). This method is also invoked for implicit AND.
*/
void atomOperation(int type) {}
void bondOperation(int type) {}
/**
* Invoked when an unbracketed atom (i.e. organic subset) is parsed.
*/
void addOrganicSubsetAtom(int element, bool aromatic) {}
/**
* Invoked when an atom primitive is parsed.
*/
void beginAtom() {}
void atomPrimitive(int type, int value) {}
void endAtom() {}
/**
* Invoked when a bond primitive is parsed. This method is also invoked for
* implicit bonds.
*/
void bondPrimitive(int type) {}
/**
* Invoked when a new ring bond number is parsed.
*/
void startRingBond(int number) {}
/**
* Invoked when a prviously found ring bond number is parsed to add the bond.
*/
void endRingBond(int number) {}
/**
* Invoked when a recursive (i.e. $(...)) SMARTS is found.
*/
void pushState() {}
/**
* Invoked when a recursive SMARTS is done parsing.
*/
void popState() {}
//@}
};
/**
* Example Callback implementation to print the parsed results.
*/
struct PrintCallback : public CallbackBase
{
/**
* The clear() method is invoked when Parser::parse() is called and should
* be used to initialize the callback function object to receive events for
* a new SMILES/SMARTS.
*/
void clear()
{
str.clear();
}
/**
* The addAtom() method is invoked when an atom is completly parsed.
*/
void addAtom(int element, bool aromatic, int isotope, int hCount, int charge, int atomClass)
{
std::cout << "addAtom:" << std::endl
<< " element: " << element << std::endl
<< " aromatic: " << aromatic << std::endl
<< " isotope: " << isotope << std::endl
<< " hCount: " << hCount << std::endl
<< " charge: " << charge << std::endl
<< " atomClass: " << atomClass << std::endl;
}
/**
* The addBond() method is invoked once both of the bond's atoms have been
* added (by calling addAtom()). Therefore are the bond indices always
* valid.
*/
void addBond(int source, int target, int order, bool isUp, bool isDown)
{
std::cout << "addBond:" << std::endl
<< " source: " << source << std::endl
<< " target: " << target << std::endl
<< " order: " << order << std::endl
<< " siUp: " << isUp << std::endl
<< " isDown: " << isDown << std::endl;
}
/**
* The setChiral() method is invoked at the end of parsing for each atom
* that has a chirality specified.
*/
void setChiral(int index, Chirality chirality, const std::vector<int> &nbrs)
{
std::cout << "setChiral:" << std::endl
<< " index: " << index << std::endl
<< " chirality: " << chirality << std::endl
<< " nbrs: ";
for (std::size_t i = 0; i < nbrs.size(); ++i)
std::cout << nbrs[i] << " ";
std::cout << std::endl;
}
void atomOperation(int type)
{
switch (type) {
case OP_Not:
str += "!";
break;
case OP_AndHi:
str += "&";
break;
case OP_AndLo:
str += ";";
break;
case OP_Or:
str += ",";
break;
}
std::cout << "operation: " << str[str.size() - 1] << std::endl;
}
void bondOperation(int type)
{
atomOperation(type);
}
void addOrganicSubsetAtom(int element, bool aromatic)
{
std::size_t pos = str.size();
if (element == 0)
str+= "*";
else if (aromatic)
str += "<a" + number2string(element) + ">";
else
str += "<A" + number2string(element) + ">";
std::cout << "addOrganicSubsetAtom: " << str.substr(pos) << std::endl;
}
std::string number2string(int value)
{
std::stringstream ss;
ss << value;
return ss.str();
}
void beginAtom()
{
std::cout << "beginAtom()" << std::endl;
}
void atomPrimitive(int type, int value)
{
std::size_t pos = str.size();
switch (type) {
case AE_True:
str += "*";
break;
case AE_False:
str += "!*";
break;
case AE_Aromatic:
str += "a";
break;
case AE_Aliphatic:
str += "A";
break;
case AE_Cyclic:
str += "R";
break;
case AE_Acyclic:
str += "R0";
break;
case AE_Isotope:
str += number2string(value);
break;
case AE_AtomicNumber:
str += "#" + number2string(value);
break;
case AE_AromaticElement:
str += "<a" + number2string(value) + ">";
break;
case AE_AliphaticElement:
str += "<A" + number2string(value) + ">";
break;
case AE_Degree:
str += "D" + number2string(value);
break;
case AE_Valence:
str += "v" + number2string(value);
break;
case AE_Connectivity:
str += "X" + number2string(value);
break;
case AE_TotalH:
str += "H" + number2string(value);
break;
case AE_ImplicitH:
str += "h";
if (value != -1)
str += number2string(value);
break;
case AE_RingMembership:
str += "R" + number2string(value);
break;
case AE_RingSize:
str += "r" + number2string(value);
break;
case AE_RingConnectivity:
str += "x";
if (value != -1)
str += number2string(value);
break;
case AE_Charge:
if (value > 0)
str += "+";
str += number2string(value);
break;
case AE_Chirality:
str += "@" + number2string(value);
break;
case AE_AtomClass:
str += ":" + number2string(value);
break;
default:
return;
}
std::cout << "atomPrimitive: " << str.substr(pos) << std::endl;
}
void endAtom()
{
std::cout << "endAtom()" << std::endl;
}
void bondPrimitive(int type)
{
switch (type) {
case BE_Single:
str += "-";
break;
case BE_Double:
str += "=";
break;
case BE_Triple:
str += "#";
break;
case BE_Quadriple:
str += "$";
break;
case BE_Aromatic:
str += ":";
break;
case BE_Up:
str += "/";
break;
case BE_Down:
str += "\\";
break;
case BE_Any:
str += "~";
break;
case BE_Ring:
str += "@";
break;
default:
return;
}
std::cout << "bondPrimitive: " << str[str.size() - 1] << std::endl;
}
void startRingBond(int number)
{
str += number2string(number);
std::cout << "startRingBond: " << number << std::endl;
}
void endRingBond(int number)
{
str += number2string(number);
std::cout << "endRingBond: " << number << std::endl;
}
void pushState()
{
std::cout << "pushState" << std::endl;
}
void popState()
{
std::cout << "popState" << std::endl;
}
std::string str;
};
/**
* @class Parser smiley.h <smiley.h>
*
* This is the main class for the Smiley SMILES/SMARTS parser.
*
* @code
* #include "smiley.h"
*
* using namespace Smiley;
*
* int main(int argc, char **argv)
* {
* PrintCallback callback;
* Parser<PrintCallback> parser(callback);
*
* try {
* parser.parse(argv[1]);
* } catch (Exception &e) {
* if (e.type() == Exception::SyntaxError)
* std::cerr << "Syntax";
* else
* std::cerr << "Semantics";
* std::cerr << "Error: " << e.what() << "." << std::endl;
* std::cerr << argv[1] << std::endl;
* for (std::size_t i = 0; i < e.pos(); ++i)
* std::cerr << " ";
* for (std::size_t i = 0; i < e.length(); ++i)
* std::cerr << "^";
* std::cerr << std::endl;
* }
* }
* @endcode
*/
template<typename Callback>
class Parser
{
private:
/**
* Internal structure to hold ring bond information.
*/
struct RingBondInfo
{
RingBondInfo() : pos(std::string::npos), number(-1), order(-1),
isUp(false), isDown(false), isExplicit(false)
{
}
RingBondInfo(int number_, int order_, bool isUp_, bool isDown_,
bool isExplicit_, std::size_t pos_) : pos(pos_), number(number_),
order(order_), isUp(isUp_), isDown(isDown_),
isExplicit(isExplicit_)
{
}
std::size_t pos;
int number;
int order;
bool isUp;
bool isDown;
bool isExplicit;
};
/**
* Internal structure to hold branch information.
*/
struct BranchInfo
{
BranchInfo() : pos(std::string::npos), index(-1)
{
}
BranchInfo(int index_, std::size_t pos_) : pos(pos_), index(index_)
{
}
std::size_t pos;
int index;
};
/**
* Internal structure to hold chiral information
*/
struct ChiralInfo
{
ChiralInfo() : pos(std::string::npos), chiral(NotChiral)
{
}