File: freefracformat.cpp

package info (click to toggle)
openbabel 2.4.1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 58,308 kB
  • sloc: cpp: 459,210; ansic: 90,514; php: 13,963; python: 7,899; perl: 6,518; pascal: 793; sh: 179; xml: 97; ruby: 64; makefile: 46; java: 23; cs: 14
file content (269 lines) | stat: -rw-r--r-- 8,568 bytes parent folder | download | duplicates (4)
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
/**********************************************************************
Copyright (C) 2005-2006 by Geoffrey R. Hutchison
Some portions Copyright (C) 2004 by Chris Morley

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/math/matrix3x3.h>

using namespace std;
namespace OpenBabel
{

  class FreeFormFractionalFormat : public OBMoleculeFormat
  {
  public:
    //Register this format type ID
    FreeFormFractionalFormat()
    {
      OBConversion::RegisterFormat("fract",this);
    }

    virtual const char* Description() //required
    {
      return
"Free Form Fractional format\n"
"General purpose crystallographic format\n"
"The \"free-form\" fractional format attempts to allow for input from a\n"
"range of fractional / crystallography file formats. As such, it has only\n"
"a few restrictions on input:\n\n"

"- Line one of the file contains a title or comment.\n"
"- Line two of the file contains the unit cell parameters separated by\n"
"  whitespace and/or commas (i.e. \"a b c alpha beta gamma\").\n"
"- Any remaining lines are parsed for atom information. Lines start with\n"
"  the element symbol, followed by fractional X, Y, and Z coordinates\n"
"  (in angstroms) separated by whitespace.\n\n"

"Any numeric input (i.e., unit cell parameters, XYZ coordinates) can include\n"
"designations of errors, although this is currently ignored. For example::\n\n"

"  C 1.00067(3) 2.75(2) 3.0678(12)\n\n"

"will be parsed as::\n\n"

"  C 1.00067 2.75 3.0678\n\n"

"When used as an **output** format, The first line written is the title of the\n"
"molecule or the filename if no title is defined. If a molecule has a defined\n"
"unit cell, then the second line will be formatted as::\n\n"

"  a b c alpha beta gamma\n\n"

"where a, b, c are the unit cell vector lengths, and alpha, beta, and gamma are\n"
"the angles between them. These numbers are formatted as \"10.5\", which means that\n"
"5 decimal places will be output for all numbers. In the case where no unit cell\n"
"is defined for the molecule, the vector lengths will be defined as 1.0, and the\n"
"angles to 90.0 degrees.\n\n"

"Remaining lines define the atoms in the file. The first column is the atomic\n"
"symbol, followed by the XYZ coordinates in 10.5 format (in angstroms).\n\n"

"Here is an example file::\n\n"

" ZnO test file\n"
" 3.14 3.24 5.18 90.0 90.0 120.0\n"
" O 0.66667  0.33333  0.3750\n"
" O 0.33333  0.66667  0.8750\n"
" Zn 0.66667  0.33333  0.0000\n"
" Zn 0.33333  0.66667  0.5000\n\n"

"Read Options e.g. -as\n"
"  s  Output single bonds only\n"
"  b  Disable bonding entirely\n\n";
    };

    virtual const char* SpecificationURL()
    {return "http://openbabel.org/wiki/Free_Form_Fractional";}; //optional

    //*** This section identical for most OBMol conversions ***
    ////////////////////////////////////////////////////
    /// The "API" interface functions
    virtual bool ReadMolecule(OBBase* pOb, OBConversion* pConv);
    virtual bool WriteMolecule(OBBase* pOb, OBConversion* pConv);
  };
  //***

  //Make an instance of the format class
  FreeFormFractionalFormat theFreeFormFractionalFormat;

/*  const char * TrimErrors(const std::string data)
  {
    string temp = data;
    size_t stdErr = temp.rfind("(");

    if(stdErr!=string::npos)
      temp.erase(stdErr);

    return temp.c_str();
  }
*/
  /////////////////////////////////////////////////////////////////
  bool FreeFormFractionalFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv)
  {

    OBMol* pmol = pOb->CastAndClear<OBMol>();
    if(pmol==NULL)
      return false;

    //Define some references so we can use the old parameter names
    istream &ifs = *pConv->GetInStream();
    OBMol &mol = *pmol;
    const char* title = pConv->GetTitle();

    char buffer[BUFF_SIZE];

    if (!ifs.getline(buffer,BUFF_SIZE))
      {
        obErrorLog.ThrowError(__FUNCTION__,
                              "Problems reading a free form fractional file: Could not read the first line (title/comments).", obWarning);
        return(false);
      }
    if (strlen(buffer) != 0)
      mol.SetTitle(buffer);
    else
      mol.SetTitle(title);

    if (!ifs.getline(buffer,BUFF_SIZE))
      {
        obErrorLog.ThrowError(__FUNCTION__,
                              "Problems reading a free form fractional file: Could not read the second line (unit cell parameters a b c alpha beta gamma).",
                              obWarning);
        return(false);
      }
    vector<string> vs;
    tokenize(vs,buffer," \n\t,");
    if (vs.size() != 6)
      return(false);

    //parse cell values
    double A, B, C, Alpha, Beta, Gamma;
    string temp; // used to trim ending (xx) data from strings

    A = atof(vs[0].c_str());
    B = atof(vs[1].c_str());
    C = atof(vs[2].c_str());
    Alpha = atof(vs[3].c_str());
    Beta  = atof(vs[4].c_str());
    Gamma = atof(vs[5].c_str());
    OBUnitCell *uc = new OBUnitCell;
    uc->SetOrigin(fileformatInput);
    uc->SetData(A, B, C, Alpha, Beta, Gamma);
    mol.SetData(uc);

    mol.BeginModify();

    string str;
    double x,y,z;
    vector3 v;
    int atomicNum;
    OBAtom *atom;

    while(ifs.getline(buffer,BUFF_SIZE))
      {
        if (strlen(buffer) == 0 || *buffer == 0x0D) //incl Windows kludge
          // blank line -- consider it the end of this molecule
          break;

        tokenize(vs,buffer);
        if (vs.size() != 4)
          return(false);

        atom = mol.NewAtom();

        // check to see if first column is number or element symbol
        // (PCModel has files of the form X Y Z symbol)
        atomicNum = etab.GetAtomicNum(vs[0].c_str());
        if (atomicNum == 0 && (isdigit(vs[0][0]) || ispunct(vs[0][0])))
          {
            x = atof(vs[0].c_str());
            y = atof(vs[1].c_str());
            z = atof(vs[2].c_str());
            atomicNum = etab.GetAtomicNum(vs[3].c_str());
          }
        else
          {
            x = atof(vs[1].c_str());
            y = atof(vs[2].c_str());
            z = atof(vs[3].c_str());
          }
        v.Set(x, y, z);
        v = uc->FractionalToCartesian(v);
        atom->SetVector(v);

        atom->SetAtomicNum(atomicNum);
      }

    // clean out any remaining blank lines
    while(ifs.peek() != EOF && ifs.good() &&
          (ifs.peek() == '\n' || ifs.peek() == '\r'))
      ifs.getline(buffer,BUFF_SIZE);

    if (!pConv->IsOption("b",OBConversion::INOPTIONS))
      mol.ConnectTheDots();
    if (!pConv->IsOption("s",OBConversion::INOPTIONS)
        && !pConv->IsOption("b",OBConversion::INOPTIONS))
      mol.PerceiveBondOrders();

    mol.EndModify();
    return(true);
  }

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

  bool FreeFormFractionalFormat::WriteMolecule(OBBase* pOb, OBConversion* pConv)
  {
    OBMol* pmol = dynamic_cast<OBMol*>(pOb);
    if(pmol==NULL)
      return false;

    //Define some references so we can use the old parameter names
    ostream &ofs = *pConv->GetOutStream();
    OBMol &mol = *pmol;

    char buffer[BUFF_SIZE];
    OBUnitCell *uc = NULL;

    ofs << mol.GetTitle() << endl;

    if (!mol.HasData(OBGenericDataType::UnitCell))
      ofs << "   1.00000   1.00000   1.00000  90.00000  90.00000  90.00000\n";
    else
      {
        uc = (OBUnitCell*)mol.GetData(OBGenericDataType::UnitCell);
        snprintf(buffer, BUFF_SIZE,
                 "%10.5f%10.5f%10.5f%10.5f%10.5f%10.5f",
                 uc->GetA(), uc->GetB(), uc->GetC(),
                 uc->GetAlpha() , uc->GetBeta(), uc->GetGamma());
        ofs << buffer << "\n";
      }

    vector3 v;
    FOR_ATOMS_OF_MOL(atom, mol)
      {
        v = atom->GetVector();
        if (uc != NULL)
          v = uc->CartesianToFractional(v);

        snprintf(buffer, BUFF_SIZE, "%s %10.5f%10.5f%10.5f",
                 etab.GetSymbol(atom->GetAtomicNum()),
                 v.x(),
                 v.y(),
                 v.z());
        ofs << buffer << endl;
      }
    ofs << endl; // add a blank line between molecules
    return(true);
  }

} //namespace OpenBabel