File: CifFile.cpp

package info (click to toggle)
pymol 1.8.4.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 42,248 kB
  • ctags: 24,095
  • sloc: cpp: 474,635; python: 75,034; ansic: 22,888; sh: 236; makefile: 78; csh: 21
file content (345 lines) | stat: -rw-r--r-- 8,854 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
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
/*
 * CIF tokenizer
 *
 * All keys are canonicalized to lowercase
 *
 * (c) 2014 Schrodinger, Inc.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <vector>
#include <iostream>
#include <stdexcept>

#include "CifFile.h"
#include "File.h"
#include "MemoryDebug.h"

// basic IO and string handling

/*
 * atof which ignores uncertainty notation
 * 1.23(45)e2 -> 1.23e2
 */
double scifloat(const char *str) {
  const char *close, *open = strchr(str, '(');
  if (open && (close = strchr(open, ')'))) {
    double value;
    char *copy = strdup(str);
    strcpy(copy + (open - str), close + 1);
    value = atof(copy);
    free(copy);
    return value;
  }
  return atof(str);
}

// Return true if "c" is whitespace or null
static bool iswhitespace0(char c) {
  return strchr(" \t\r\n", c) ? true : false;
}

// Return true if "c" is whitespace
static bool iswhitespace(char c) {
  return (c && iswhitespace0(c));
}

// Return true if "c" is line feed or carriage return
static bool islinefeed(char c) {
  return (c == '\r' || c == '\n');
}

// Return true if "c" is line feed or carriage return or null
static bool islinefeed0(char c) {
  return (!c || islinefeed(c));
}

// Return true if "c" is double or single quote
static bool isquote(char c) {
  return (c == '"' || c == '\'');
}

// FreeBSD name conflict
#ifdef isspecial
#undef isspecial
#endif

// Return true if token is a STAR keyword
static bool isspecial(const char *token) {
  return (token[0] == '_'
      || strncasecmp("data_", token, 5) == 0
      || strncasecmp("save_", token, 5) == 0
      || strcasecmp("loop_", token) == 0
      || strcasecmp("stop_", token) == 0
      || strcasecmp("global_", token) == 0);
}

// convert all chars to lowercase
static void tolowerinplace(char *p) {
  for (; *p; p++) {
    if (*p <= 'Z' && *p >= 'A')
      *p -= 'Z' - 'z';
  }
}

// CIF stuff

static const char * EMPTY_STRING = "";
static cif_array EMPTY_ARRAY(NULL);

// get table value, return NULL if indices out of bounds
const char * cif_loop::get_value_raw(int row, int col) const {
  if (row >= nrows)
    return NULL;
  return values[row * ncols + col];
}

// get array value, return NULL if row-index out of bounds
const char * cif_array::get_value_raw(int row) const {
  if (col < 0)
    return (row > 0) ? NULL : pointer.value;
  return pointer.loop->get_value_raw(row, col);
};

// get array value, return NULL if value in ['.', '?']
const char * cif_array::get_value(int row) const {
  const char * s = get_value_raw(row);
  return (s && (s[0] == '?' || s[0] == '.') && !s[1]) ? NULL : s;
}

// get array value, return an empty string if missing
const char * cif_array::as_s(int row) const {
  const char * s = get_value(row);
  return s ? s : EMPTY_STRING;
}

// get array value as integer, return d (default 0) if missing
int cif_array::as_i(int row, int d) const {
  const char * s = get_value(row);
  return s ? atoi(s) : d;
}

// get array value as double, return d (default 0.0) if missing
double cif_array::as_d(int row, double d) const {
  const char * s = get_value(row);
  return s ? scifloat(s) : d;
}

// templated getters
template <> const char* cif_array::as<const char* >(int row) const { return as_s(row); }
template <> std::string cif_array::as<std::string >(int row) const { return as_s(row); }
template <> int         cif_array::as<int         >(int row) const { return as_i(row); }
template <> double      cif_array::as<double      >(int row) const { return as_d(row); }
template <> float       cif_array::as<float       >(int row) const { return as_d(row); }

/*
 * Get a pointer to array or NULL if not found
 *
 * Can lookup up to 3 different aliases, the first one found is returned.
 * Also supports an alias shortcut for the trivial case where mmCIF uses
 * a colon and CIF uses an underscore: (key="_foo?bar") is identical to
 * (key="_foo.bar", alias1="_foo_bar")
 */
const cif_array * cif_data::get_arr(const char * key, const char * alias1, const char * alias2) const {
  const char * p;
  const char * aliases[] = {alias1, alias2, NULL};
  m_str_cifarray_t::const_iterator it;

  for (int j = 0; key; key = aliases[j++]) {
    // support alias shortcut: '?' matches '.' and '_'
    if ((p = strchr(key, '?'))) {
      std::string tmp(key);
      for (const char * d = "._"; *d; ++d) {
        // replace '?' by '.' or '_'
        tmp[p - key] = *d;
        if ((it = dict.find(tmp.c_str())) != dict.end())
          return &it->second;
      }
    } else {
      if ((it = dict.find(key)) != dict.end())
        return &it->second;
    }
  }

  return NULL;
}

// Get a pointer to array or to a default value if not found
const cif_array * cif_data::get_opt(const char * key, const char * alias1, const char * alias2) const {
  const cif_array * arr = get_arr(key, alias1, alias2);
  if (arr == NULL)
    return &EMPTY_ARRAY;
  return arr;
}

// constructor
cif_file::cif_file(const char* filename, const char* contents_) {
  if (contents_) {
    contents = mstrdup(contents_);
  } else {
    contents = FileGetContents(filename, NULL);
    if (!contents)
      std::cerr << "ERROR: Failed to load file '" << filename << "'" << std::endl;
  }

  if (contents)
    parse();
}

// destructor
cif_file::~cif_file() {
  for (m_str_cifdatap_t::iterator it = datablocks.begin(),
      it_end = datablocks.end(); it != it_end; ++it)
    delete it->second;

  if (contents)
    mfree(contents);
}

// destructor
cif_data::~cif_data() {
  for (m_str_cifdatap_t::iterator it = saveframes.begin(),
      it_end = saveframes.end(); it != it_end; ++it)
    delete it->second;

  for (v_cifloopp_t::iterator it = loops.begin(),
      it_end = loops.end(); it != it_end; ++it)
    delete *it;
}

// parse CIF contents
bool cif_file::parse() {
  char *p = contents;
  char quote;
  char prev = '\0';

  std::vector<char> codes;

  // tokenize
  while (true) {
    while (iswhitespace(*p))
      prev = *(p++);

    if (!*p)
      break;

    if (*p == '#') {
      while (!(islinefeed0(*++p)));
      prev = *p;
    } else if (isquote(*p)) { // will NULL the closing quote
      quote = *p;
      codes.push_back('Q');
      tokens.push_back(p + 1);
      while (*++p && !(*p == quote && iswhitespace0(p[1])));
      if (*p)
        *(p++) = 0;
      prev = *p;
    } else if (*p == ';' && islinefeed(prev)) { // will NULL the line feed before the closing semicolon
      codes.push_back('Q');
      tokens.push_back(p + 1);
      while (*++p && !(islinefeed(*p) && p[1] == ';'));
      if (*p) {
        *p = 0;
        p += 2;
      }
      prev = ';';
    } else { // will null the whitespace
      codes.push_back('R');
      tokens.push_back(p);
      while (!iswhitespace0(*p)) ++p;
      prev = *p;
      if (*p)
        *(p++) = 0;
    }
  }

  cif_data *current_data = NULL, *current_frame = NULL, *global_block = NULL;

  // parse into dictionary
  for (unsigned int i = 0, n = tokens.size(); i < n; i++) {
    if (codes[i] == 'Q') {
      std::cout << "ERROR" << std::endl;
      break;
    } else if (tokens[i][0] == '_') {
      if (current_frame) {
        tolowerinplace(tokens[i]);
        current_frame->dict[tokens[i]].set_value(tokens[i + 1]);
      }

      i++;
    } else if (strcasecmp("loop_", tokens[i]) == 0) {
      int ncols = 0;
      int nrows = 0;
      cif_loop *loop = NULL;

      // loop data
      if (current_frame) {
        loop = new cif_loop;

        // add to loops list
        current_frame->loops.push_back(loop);
      }

      // columns
      while (++i < n && codes[i] != 'Q' && tokens[i][0] == '_') {
        tolowerinplace(tokens[i]);

        if (current_frame) {
          current_frame->dict[tokens[i]].set_loop(loop, ncols);
        }

        ncols++;
      }

      if (loop) {
        // loop data
        loop->values = (const char **) &tokens[i];
        loop->ncols = ncols;
      }

      // rows
      while (i < n && (codes[i] == 'Q' || !isspecial(tokens[i]))) {
        i += ncols;
        nrows++;
      }

      // loop data
      if (loop) {
        loop->nrows = nrows;
      }

      i--;

    } else if (strncasecmp("data_", tokens[i], 5) == 0) {
      const char * key(tokens[i] + 5);
      datablocks[key] = current_data = current_frame = new cif_data;

    } else if (strncasecmp("global_", tokens[i], 5) == 0) {
      // STAR feature, not supported in CIF
      global_block = current_data = current_frame = new cif_data;

    } else if (strncasecmp("save_", tokens[i], 5) == 0) {
      if (tokens[i][5]) {
        // begin
        const char * key(tokens[i] + 5);
        current_data->saveframes[key] = current_frame = new cif_data;
      } else {
        // end
        current_frame = current_data;
      }
    } else {
      std::cout << "ERROR" << std::endl;
      break;
    }
  }

  if (global_block)
    delete global_block;

  return true;
}

// vi:sw=2:ts=2