File: CifFile.h

package info (click to toggle)
pymol 3.1.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 74,084 kB
  • sloc: cpp: 482,660; python: 89,328; ansic: 29,512; javascript: 6,792; sh: 84; makefile: 25
file content (383 lines) | stat: -rw-r--r-- 10,315 bytes parent folder | download
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
/*
 * CIF tokenizer
 *
 * (c) 2014 Schrodinger, Inc.
 */

#ifndef _H_CIFFILE
#define _H_CIFFILE

#include <cstddef>
#include <cstdint>
#include <cstring>
#include <map>
#include <memory>
#include <vector>
#include <string>
#include <variant>

// for pymol::default_free
#include "MemoryDebug.h"

template<class... Ts>
struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;

namespace pymol {
namespace _cif_detail {

/**
 * Null-terminated string view.
 */
class zstring_view {
  const char* m_data;

public:
  zstring_view(const char* s) : m_data(s) {}

  bool operator<(zstring_view rhs) const {
    return std::strcmp(m_data, rhs.m_data) < 0;
  }
};

/**
 * Convert a raw cif data value to a typed value
 */
template <typename T> T raw_to_typed(const char*);

} // namespace _cif_detail

// cif data types
class cif_data;
class cif_loop;
class cif_array;
namespace cif_detail {
  struct cif_str_data;
  struct bcif_data;
};
using CIFData = std::variant<cif_detail::cif_str_data, cif_detail::bcif_data>;

/**
 * Class for reading CIF files.
 * Parses the entire file and exposes its data blocks.
 *
 * Read CIF file:
 * @verbatim auto cf = cif_file("file.cif"); @endverbatim
 *
 * Read CIF string:
 * @verbatim auto cf = cif_file(nullptr, cifstring); @endverbatim
 *
 * Iterate over data blocks:
 * @verbatim
   for (auto& [code, block] : cf.datablocks()) {
     // data_<code>
     const char* code = block->code();

     // get data item pointer, or nullptr if name not found
     auto* dataitem1 = block->get_arr("_some.name1");
     auto* dataitem2 = block->get_arr("_some.name2", "_alternate.name");

     // get data item pointer, or default item if name not found
     auto* dataitem3 = block->get_opt("_some.name3");

     // value of data item
     const char* stringvalue = dataitem3->as_s();
     int intvalue = dataitem3->as_i();

     // values of looped data item
     for (unsigned i = 0, i_end = dataitem3->size(); i != i_end; ++i) {
       const char* stringvalue = dataitem3->as_s(i);
     }
   }
   @endverbatim
 */
class cif_file {
  std::vector<char*> m_tokens;
  std::map<std::string, cif_data> m_datablocks;
  std::unique_ptr<char, pymol::default_free> m_contents;

  /**
   * Parse CIF string
   * @param p CIF string (takes ownership)
   * @post datablocks() is valid
   */
  bool parse(char*&&);

public:
  /// Parse CIF file
  bool parse_file(const char*);

  /// Parse CIF string
  bool parse_string(const char*);

  /**
   * Parse BinaryCIF blob
   * @param bytes BinaryCIF blob
   * @param size Blob size
   * @post datablocks() is valid
  */
  bool parse_bcif(const char* bytes, std::size_t size);

protected:
  /// Report a parsing error
  virtual void error(const char*);

public:
  cif_file();
  cif_file(cif_file&&);
  cif_file(const cif_file&) = delete;
  cif_file& operator=(cif_file&&);
  cif_file& operator=(const cif_file&) = delete;
  virtual ~cif_file();

  /// Construct from file name or buffer
  cif_file(const char* filename, const char* contents = nullptr);

  /// Data blocks
  const std::map<std::string, cif_data>& datablocks() const { return m_datablocks; }
};


using CifArrayElement = std::variant<std::int8_t, std::int16_t, std::int32_t,
    std::uint8_t, std::uint16_t, std::uint32_t, float, double, std::string>;

namespace cif_detail {
  struct cif_str_array {
    enum { NOT_IN_LOOP = -1 };

    // column index, -1 if not in loop
    short col;

    // pointer to either loop or single value
    union {
      const cif_loop * loop;
      const char * value;
    } pointer;

    // Raw data value or NULL for unknown/inapplicable and `pos >= size()`
    const char* get_value_raw(unsigned pos = 0) const;

    // point this array to a loop (only for parsing)
    void set_loop(const cif_loop * loop, short col_) {
      col = col_;
      pointer.loop = loop;
    };

    // point this array to a single value (only for parsing)
    void set_value(const char * value) {
      col = NOT_IN_LOOP;
      pointer.value = value;
    };
  };
  struct bcif_array {
    std::vector<CifArrayElement> m_arr{};
  };

  /**
   * Returns a typed value from a CIF data element.
   * If the element is missing or inapplicable, return `d`.
   * @param var CIF data element
   * @param d default value
   * @return typed value
   */
  template <typename T> T var_to_typed(const CifArrayElement& var, const T& d)
  {
    if constexpr (std::is_same_v<T, const char*>) {
      auto& str = std::get<std::string>(var);
      return !str.empty() ? str.c_str() : d;
    } else {
      if (auto ptr = std::get_if<std::string>(&var); ptr && ptr->empty()) {
        return d;
      }
      if constexpr (!std::is_same_v<T, std::string>) {
        return std::visit(overloaded{[](const std::string& s) -> T {
                                       return _cif_detail::raw_to_typed<T>(
                                           s.c_str());
                                     },
                              [](const auto& v) -> T { return v; }},
            var);
      }
    }
    return d;
  }
}

/**
 * View on a CIF data array. The viewed data is owned by the cif_file
 */
class cif_array {
  friend class cif_file;

private:
  mutable std::string m_internal_str_cache;
  std::variant<cif_detail::cif_str_array, cif_detail::bcif_array> m_array;

public:
  // constructor
  cif_array() = default;

  // constructor (only needed for EMPTY_ARRAY)
  cif_array(std::nullptr_t) { 
    if (auto arr = std::get_if<cif_detail::cif_str_array>(&m_array)) {
      arr->set_value(nullptr);
    } else if (auto arr = std::get_if<cif_detail::bcif_array>(&m_array)) {
      arr->m_arr.clear();
    }
  }

  cif_array(std::vector<CifArrayElement>&& arr) {
    m_array = cif_detail::bcif_array{std::move(arr)};
  }

  /// Number of elements in this array (= number of rows in loop)
  unsigned size() const;

  /// True if value in ['.', '?']
  bool is_missing(unsigned pos = 0) const {
    if (auto arr = std::get_if<cif_detail::cif_str_array>(&m_array)) {
      return !arr->get_value_raw(pos);
    } else {
      return false;
    }
  }

  /// True if all values in ['.', '?']
  bool is_missing_all() const;

  /**
   * Get element as type T. If `pos >= size()` then return `d`.
   * @param pos element index (= row index in loop)
   * @param d default value for unknown/inapplicable elements
   */
  template <typename T> T as(unsigned pos = 0, T d = T()) const {
    if (auto arr = std::get_if<cif_detail::cif_str_array>(&m_array)) {
      const char* s = arr->get_value_raw(pos);
      return s ? _cif_detail::raw_to_typed<T>(s) : d;
    } else if (auto arr = std::get_if<cif_detail::bcif_array>(&m_array)) {
      if (pos >= arr->m_arr.size())
        return d;
      auto& var = arr->m_arr[pos];
      return cif_detail::var_to_typed<T>(var, d);
    }
    return d;
  }

  /**
   * Get element as null-terminated string. The default value is the empty
   * string, unlike as<const char*>() which returns nullptr as the default value.
   * If `pos >= size()` then return `d`.
   * @param pos element index (= row index in loop)
   * @param d default value for unknown/inapplicable elements
   */
  const char* as_s(unsigned pos = 0, const char* d = "") const {
    if (std::get_if<cif_detail::cif_str_array>(&m_array)) {
      return as(pos, d);
    } else if (auto arr = std::get_if<cif_detail::bcif_array>(&m_array)) {
      if (pos >= arr->m_arr.size())
        return d;
      if (auto str_ptr = std::get_if<std::string>(&arr->m_arr[pos])) {
        return str_ptr->c_str();
      }
      m_internal_str_cache = std::visit([](auto&& arg) -> std::string {
        if constexpr (std::is_same_v<std::decay_t<decltype(arg)>,
                          std::string>) {
          return arg;
        } else {
          return std::to_string(arg);
        }
      }, arr->m_arr[pos]);
      return m_internal_str_cache.c_str();
    }
    return d;
  }

  /// Alias for as<int>()
  int as_i(unsigned pos = 0, int d = 0) const { return as(pos, d); }

  /// Alias for as<double>()
  double as_d(unsigned pos = 0, double d = 0.) const { return as(pos, d); }

  /**
   * Get a copy of the array.
   * @param d default value for unknown/inapplicable elements
   */
  template <typename T> std::vector<T> to_vector(T d = T()) const {
    auto n = size();
    std::vector<T> v;
    v.reserve(n);
    for (unsigned i = 0; i < n; ++i)
      v.push_back(as<T>(i, d));
    return v;
  }
};

/**
 * CIF data block. The viewed data is owned by the cif_file.
 */

namespace cif_detail {
  struct cif_str_data {
    // data_<code>
    const char* m_code = nullptr;

    std::map<_cif_detail::zstring_view, cif_array> m_dict;
    std::map<std::string, cif_array> m_dict_str;
    std::map<_cif_detail::zstring_view, cif_detail::cif_str_data> m_saveframes;

    // only needed for freeing
    std::vector<std::unique_ptr<cif_loop>> m_loops;
  };

  using ColumnMap = std::map<std::string, std::vector<CifArrayElement>>;
  using CategoryMap = std::map<std::string, ColumnMap>;
  using DataBlockMap = std::map<std::string, CategoryMap>;
  struct bcif_data {
    std::string m_code;
    std::map<std::string, std::map<std::string, cif_array>> m_dict;
  };
}

class cif_data {
  friend class cif_file;

  CIFData m_data;

  // generic default value
  static const cif_array* empty_array();

public:

  cif_data() = default;
  cif_data(const cif_data&) = delete;
  cif_data(cif_data&&) = default;
  cif_data& operator=(const cif_data&) = delete;
  cif_data& operator=(cif_data&&) = default;

  /// Block code (never nullptr)
  const char* code() const;

  // Get a pointer to array or nullptr if not found
  const cif_array* get_arr(const char* key) const;
  template <typename... Args>
  const cif_array* get_arr(const char* key, Args... aliases) const
  {
    auto arr = get_arr(key);
    return arr ? arr : get_arr(aliases...);
  }

  /// Like get_arr() but return a default value instead of nullptr if not found
  template <typename... Args> const cif_array* get_opt(Args... keys) const
  {
    auto arr = get_arr(keys...);
    return arr ? arr : empty_array();
  }

  /// Get a pointer to a save frame or nullptr if not found
  const cif_detail::cif_str_data* get_saveframe(const char* code) const;
};

} // namespace pymol

#endif
// vi:sw=2:ts=2