openbabel-sys 0.5.4+openbabel-3.1.1

Native bindings to OpenBabel
Documentation
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
/**********************************************************************
Copyright (C) 2012 by Tim Vandermeersch

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
***********************************************************************/

#include <openbabel/babelconfig.h>
#include <openbabel/obmolecformat.h>
#include <openbabel/mol.h>
#include <openbabel/atom.h>
#include <openbabel/elements.h>
#include <openbabel/bond.h>
#include <openbabel/obiter.h>

#include <openbabel/typer.h>
#include <openbabel/stereo/tetrahedral.h>
#include <openbabel/stereo/cistrans.h>

#include "smiley.h"

using namespace std;

namespace OpenBabel
{

  template<typename T>
  void print_vector(const std::string &label, const std::vector<T> &v)
  {
    std::cout << label << ": ";
    for (std::size_t i = 0; i < v.size(); ++i)
      std::cout << v[i] << " ";
    std::cout << std::endl;
  }

  /**
   *
   * Smiley callback.
   *
   */
  struct OpenBabelCallback : public Smiley::CallbackBase
  {
    enum UpDown {
      IsNotUpDown,
      IsUp,
      IsDown
    };

    OpenBabelCallback(OBMol *pmol) : mol(pmol)
    {
    }

    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)

      OBAtom *atom = mol->NewAtom();
      atom->SetAtomicNum(element);

      indices.push_back(mol->NumAtoms());

      if (aromatic)
        atom->SetAromatic();
      //else if (hCount == -1)
      //  atom->ForceImplH();

      if (hCount > -1) {
        if (hCount == 0)
          atom->SetSpinMultiplicity(2);

        for (int i = 0; i < hCount; ++i) {
          OBAtom *hydrogen = mol->NewAtom();
          hydrogen->SetAtomicNum(1);
          mol->AddBond(atom->GetIdx(), hydrogen->GetIdx(), 1);
          upDown.push_back(IsNotUpDown);
        }
      }

      if (isotope > 0)
        atom->SetIsotope(isotope);

      atom->SetFormalCharge(charge);
    }

    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 '\'

      //std::cout << "addBond(" << source << ", " << target << ")" << std::endl;

      if (isDown)
        upDown.push_back(IsDown);
      else if (isUp)
        upDown.push_back(IsUp);
      else
        upDown.push_back(IsNotUpDown);

      /*
      if (isUp || isDown) {
        std::cout << "addBond(" << source << ", " << target << ")" << std::endl;
        std::cout << "isUp: " << isUp << ", isDown: " << isDown << std::endl;
      }
      */

      mol->AddBond(indices[source], indices[target], order);
      if (order == 5)
        mol->GetBond(mol->NumBonds() - 1)->SetAromatic();
    }

    void setChiral(int index, Smiley::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

      //print_vector("chiralNbrs", chiralNbrs);

      unsigned long center = indices[index] - 1;
      unsigned long from = indices[chiralNbrs[0]] - 1;
      std::vector<unsigned long> refs(chiralNbrs.size() - 1);
      for (std::size_t i = 0; i < refs.size(); ++i)
        if (chiralNbrs[i + 1] == Smiley::implicitHydrogen())
          refs[i] = OBStereo::ImplicitRef;
        else
          refs[i] = indices[chiralNbrs[i + 1]] - 1;

      //std::cout << "center: " << center << std::endl;
      //std::cout << "from: " << from << std::endl;
      //print_vector("refs", refs);

      switch (chirality) {
        case Smiley::Clockwise:
          switch (chiralNbrs.size()) {
            case 4:
              OBTetrahedralStereo *stereo = new OBTetrahedralStereo(mol);
              stereo->SetConfig(OBTetrahedralStereo::Config(center, from, refs));
              mol->SetData(stereo);
              break;
          }
          break;
        case Smiley::AntiClockwise:
          switch (chiralNbrs.size()) {
            case 4:
              OBTetrahedralStereo *stereo = new OBTetrahedralStereo(mol);
              stereo->SetConfig(OBTetrahedralStereo::Config(center, from, refs, OBStereo::AntiClockwise));
              mol->SetData(stereo);
              break;
          }
          break;
      }
    }

    OBMol *mol;
    std::vector<UpDown> upDown;
    std::vector<int> indices;
  };

  /**
   *
   * OpenBabel format.
   *
   */
  class SmileyFormat : public OBMoleculeFormat
  {
    public:
      SmileyFormat()
      {
        OBConversion::RegisterFormat("smy", this);
      }

      virtual const char* Description() //required
      {
        return "SMILES format using Smiley parser\n\n"

"The Smiley parser presents an alternative to the standard SMILES parser\n"
"(:ref:`SMILES_format`). It was written to be strictly compatible with the\n"
"OpenSMILES standard (http://opensmiles.org). In comparison, the standard\n"
"parser is more forgiving to erroneous input, and also supports some extensions\n"
"such as for radicals.\n\n"

"In addition, the Smiley parser returns detailed error messages when problems\n"
"arise parsing or validating the SMILES, whereas the standard parser seldom\n"
"describes the specific problem. For a detailed description of the OpenSMILES\n"
"semantics, the specification should be consulted. In addition to syntactical\n"
"and grammatical correctness, the Smiley parser also verifies some basic\n"
"semantics.\n"
"\n"
"Here are some examples of the errors reported::\n"
"\n"
"   SyntaxError: Bracket atom expression contains invalid trailing characters.\n"
"   F.FB(F)F.[NH2+251][C@@H](CP(c1ccccc1)c1ccccc1)C(C)(C)C 31586112\n"
"                  ^^\n"
"   SyntaxError: Unmatched branch opening.\n"
"   CC(CC\n"
"     ^^^\n"
"   SyntaxError: Unmatched branch closing.\n"
"   CC)CC\n"
"   ^^^\n"
"   SemanticsError: Unmatched ring bond.\n"
"   C1CCC\n"
"   ^\n"
"   SemanticsError: Conflicing ring bonds.\n"
"   C-1CCCCC=1\n"
"\n"
"Hydrogen with Hydrogen Count\n"
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
"Hydrogen atoms can not have a hydrogen count. Hydrogen bound to a hydrogen\n"
"atom should be specified by two bracket atom expressions.\n"
"\n"
"Examples::\n"
"\n"
"  [HH]        invalid\n"
"  [HH1]       invalid (same as [HH]\n"
"  [HH3]       invalid\n"
"  [HH0]       valid (same as [H])\n"
"  [H][H]      valid\n"
"\n"
"Unmatched Ring Bond\n"
"~~~~~~~~~~~~~~~~~~~\n"
"Report unmatched ring bonds.\n"
"\n"
"Example::\n"
"\n"
"  C1CCC\n"
"\n"
"Conflicting Ring Bonds\n"
"~~~~~~~~~~~~~~~~~~~~~~\n"
"When the bond type for ring bonds are explicitly specified at both ends,\n"
"these should be the same.\n"
"\n"
"Example::\n"
"\n"
"  C-1CCCCCC=1\n"
"\n"
"Invalid Ring Bonds\n"
"~~~~~~~~~~~~~~~~~~\n"
"There are two types of invalid ring bonds. The first is when two atoms both\n"
"have the same two ring bonds. This would mean adding a parallel edge in the\n"
"graph which is not allowed. The second type is similar but results in a\n"
"self-loop by having a ring bond number twice.\n"
"\n"
"Examples::\n"
"\n"
"  C12CCCC12      parallel bond\n"
"  C11            self-loop bond\n"
"\n"
"Invalid Chiral Valence\n"
"~~~~~~~~~~~~~~~~~~~~~~\n"
"When an atom is specified as being chiral, it should have the correct\n"
"number of neighboring atoms (possibly including an implicit H inside the\n"
"bracket.\n"
"\n"
"The valid valences are::\n"
"\n"
"  Tetrahedral (TH)          : 4\n"
"  Allene (AL)               : 4 (*)\n"
"  Square Planar (SP)        : 4\n"
"  Trigonal Bypiramidal (TB) : 5\n"
"  Octahedral(OH)            : 6\n"
"\n"
"  (*) The chiral atom has only 2 bonds but the neighbor's neighbors are\n"
"      counted: NC(Br)=[C@AL1]=C(F)I\n"
"\n"
"Invalid Chiral Hydrogen Count\n"
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
"Chiral atoms can only have one hydrogen in their bracket since multiple\n"
"hydrogens would make them not chiral.\n"
"\n"
"Example::\n"
"\n"
"  C[C@H2]F\n\n";
      }

      virtual const char* SpecificationURL()
      {
        return "http://opensmiles.org";
      }

      virtual const char* GetMIMEType()
      {
        return "chemical/x-daylight-smiles";
      }

      virtual unsigned int Flags()
      {
        return NOTWRITABLE;
      }

      virtual bool ReadMolecule(OBBase* pOb, OBConversion* pConv);

    private:
      void CreateCisTrans(OBMol *mol, const std::vector<OpenBabelCallback::UpDown> &upDown);
      bool AssignNbrAtoms(const std::vector<OpenBabelCallback::UpDown> &upDown, OBAtom *atom,
          unsigned long &above, unsigned long &below);

  };

  ////////////////////////////////////////////////////

  //Make an instance of the format class
  SmileyFormat theSmileyFormat;

  /////////////////////////////////////////////////////////////////




  bool SmileyFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv)
  {
    OBMol* pmol = pOb->CastAndClear<OBMol>();
    if (!pmol)
      return false;

    // get the input stream
    istream& ifs = *pConv->GetInStream();

    // read the smiles string
    std::string smiles;
    std::getline(ifs, smiles);

    // extract title
    std::size_t space_pos = smiles.find(" ");
    std::size_t tab_pos = smiles.find("\t");
    if (space_pos != std::string::npos && tab_pos != std::string::npos)
      space_pos = std::min(space_pos, tab_pos);
    else if (tab_pos != std::string::npos)
      space_pos = tab_pos;

    if (space_pos != std::string::npos) {
      while (space_pos < smiles.size() && (smiles[space_pos] == ' ' || smiles[space_pos] == '\t'))
        ++space_pos;
      pmol->SetTitle(smiles.substr(space_pos).c_str());
    }

    pmol->BeginModify();
    pmol->SetDimension(0);

    // create callback and parser object
    OpenBabelCallback callback(pmol);
    Smiley::Parser<OpenBabelCallback> parser(callback);

    try {
      parser.parse(smiles);
    } catch (Smiley::Exception &e) {
      if (e.type() == Smiley::Exception::SyntaxError)
        std::cerr << "Syntax";
      else
        std::cerr << "Semantics";
      std::cerr << "Error: " << e.what() << "." << std::endl;
      std::cerr << smiles << 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;
    }

    pmol->EndModify();

    // handle aromaticity
    pmol->SetAromaticPerceived();

    // create cis/trans stereo objects
    CreateCisTrans(pmol, callback.upDown);
    StereoFrom0D(pmol);

    return true;
  }

  bool SmileyFormat::AssignNbrAtoms(const std::vector<OpenBabelCallback::UpDown> &upDown,
      OBAtom *atom, unsigned long &aboveId, unsigned long &belowId)
  {
    OBAtom *above = nullptr;
    OBAtom *below = nullptr;
    OBAtom *unspecified = nullptr;

    FOR_BONDS_OF_ATOM (bond, atom) {
      if (!bond->IsAromatic() && bond->GetBondOrder() == 2)
        continue;

      OBAtom *nbr = bond->GetNbrAtom(atom);
      //std::cout << "atom: " << atom->GetIndex() << std::endl;
      //std::cout << "nbr: " << nbr->GetIndex() << std::endl;

      switch (upDown[bond->GetIdx()]) {
        case OpenBabelCallback::IsUp:
          if (nbr->GetIndex() < atom->GetIndex() && bond->GetBeginAtomIdx() < bond->GetEndAtomIdx()) {
            //std::cout << "below: " << nbr->GetIndex() << std::endl;
            if (below)
              return false;
            below = nbr;
          } else {
            //std::cout << "above: " << nbr->GetIndex() << std::endl;
            if (above)
              return false;
            above = nbr;
          }
          break;
        case OpenBabelCallback::IsDown:
          if (nbr->GetIndex() < atom->GetIndex() && bond->GetBeginAtomIdx() < bond->GetEndAtomIdx()) {
            if (above)
              return false;
            above = nbr;
          } else {
            if (below)
              return false;
            below = nbr;
          }
          break;
        case OpenBabelCallback::IsNotUpDown:
          //std::cout << "unspecified: " << nbr->GetIndex() << std::endl;
          unspecified = nbr;
          break;
      }
    }

    // at least 1 bond should be specified
    if (!above && !below)
      return true;

    if (above && unspecified)
      below = unspecified;
    else if (below && unspecified)
      above = unspecified;

    aboveId = above ? above->GetId() : OBStereo::ImplicitRef;
    belowId = below ? below->GetId() : OBStereo::ImplicitRef;

    return true;
  }

  void SmileyFormat::CreateCisTrans(OBMol *mol, const std::vector<OpenBabelCallback::UpDown> &upDown)
  {
    FOR_BONDS_OF_MOL (doubleBond, mol) {
      if (doubleBond->GetBondOrder() != 2 || doubleBond->IsAromatic())
        continue;

      OBAtom *source = doubleBond->GetBeginAtom();
      OBAtom *target = doubleBond->GetEndAtom();

      //std::cout << "double bond: " << source->GetIndex() << " " << target->GetIndex() << std::endl;

      // Check that both atoms on the double bond have at least one
      // other neighbor, but not more than two other neighbors;
      int v1 = source->GetExplicitDegree();
      int v2 = target->GetExplicitDegree();
      if (v1 < 2 || v1 > 3 || v2 < 2 || v2 > 3)
        continue;

      unsigned long aboveSource = OBStereo::ImplicitRef;
      unsigned long belowSource = OBStereo::ImplicitRef;
      if (!AssignNbrAtoms(upDown, source, aboveSource, belowSource)) {
        std::cerr << "Invalid cis/trans specification" << std::endl;
        continue;
      }

      if (aboveSource == OBStereo::ImplicitRef && belowSource == OBStereo::ImplicitRef)
        continue;

      unsigned long aboveTarget = OBStereo::ImplicitRef;
      unsigned long belowTarget = OBStereo::ImplicitRef;
      if (!AssignNbrAtoms(upDown, target, aboveTarget, belowTarget)) {
        std::cerr << "Invalid cis/trans specification" << std::endl;
        continue;
      }

      if (aboveTarget == OBStereo::ImplicitRef && belowTarget == OBStereo::ImplicitRef)
        continue;

      //std::cout << "refs: " << aboveSource << " " << aboveTarget << " " << belowTarget << " " << belowSource << std::endl;

      OBCisTransStereo *stereo = new OBCisTransStereo(mol);
      stereo->SetConfig(OBCisTransStereo::Config(source->GetId(), target->GetId(),
            OBStereo::MakeRefs(aboveSource, belowSource, belowTarget, aboveTarget),
            OBStereo::ShapeU));

      mol->SetData(stereo);
    }
  }

} //namespace OpenBabel