-
Notifications
You must be signed in to change notification settings - Fork 289
/
Copy pathCifMoleculeReader.cpp
2405 lines (1991 loc) · 69.6 KB
/
CifMoleculeReader.cpp
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
/*
* Read a molecule from CIF
*
* (c) 2014 Schrodinger, Inc.
*/
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <vector>
#include <memory>
#include <array>
#include "os_predef.h"
#include "os_std.h"
#include "MemoryDebug.h"
#include "Err.h"
#include "AssemblyHelpers.h"
#include "AtomInfo.h"
#include "Base.h"
#include "Executive.h"
#include "P.h"
#include "Util.h"
#include "Scene.h"
#include "Rep.h"
#include "ObjectMolecule.h"
#include "CifFile.h"
#include "CifBondDict.h"
#include "Util2.h"
#include "Vector.h"
#include "Lex.h"
#include "strcasecmp.h"
#include "pymol/zstring_view.h"
#include "Feedback.h"
#ifdef _PYMOL_IP_PROPERTIES
#endif
using pymol::cif_data;
using pymol::cif_array;
/**
* CIF parser which captures the last error message.
*/
class cif_file_with_error_capture : public pymol::cif_file
{
public:
std::string m_error_msg;
void error(const char* msg) override { m_error_msg = msg; }
};
// canonical amino acid three letter codes
const char * aa_three_letter[] = {
"ALA", // A
"ASX", // B for ambiguous asparagine/aspartic-acid
"CYS", // C
"ASP", // D
"GLU", // E
"PHE", // F
"GLY", // G
"HIS", // H
"ILE", // I
nullptr, // J
"LYS", // K
"LEU", // L
"MET", // M
"ASN", // N
"HOH", // O for water
"PRO", // P
"GLN", // Q
"ARG", // R
"SER", // S
"THR", // T
nullptr, // U
"VAL", // V
"TRP", // W
nullptr, // X for other
"TYR", // Y
"GLX", // Z for ambiguous glutamine/glutamic acid
};
// amino acid one-to-three letter code translation
static const char * aa_get_three_letter(char aa) {
if (aa < 'A' || aa > 'Z')
return "UNK";
const char * three = aa_three_letter[aa - 'A'];
return (three) ? three : "UNK";
}
// dictionary content types
enum CifDataType {
CIF_UNKNOWN,
CIF_CORE, // small molecule
CIF_MMCIF, // macromolecular structure
CIF_CHEM_COMP // chemical component
};
// simple 1-indexed string storage
class seqvec_t : public std::vector<std::string> {
public:
void set(int i, const char * mon_id) {
if (i < 1) {
printf("error: i(%d) < 1\n", i);
return;
}
if (i > size())
resize(i);
(*this)[i - 1] = mon_id;
}
const char * get(int i) const {
if (i < 1 || i > size())
return nullptr;
return (*this)[i - 1].c_str();
}
};
// structure to collect information about a data block
struct CifContentInfo {
PyMOLGlobals * G;
CifDataType type;
bool fractional;
bool use_auth;
std::set<lexidx_t> chains_filter;
std::set<std::string> polypeptide_entities; // entity ids
std::map<std::string, seqvec_t> sequences; // entity_id -> [resn1, resn2, ...]
bool is_excluded_chain(const char * chain) const {
if (chains_filter.empty())
return false;
auto borrowed = LexBorrow(G, chain);
if (borrowed != LEX_BORROW_NOTFOUND)
return is_excluded_chain(borrowed);
return false;
}
bool is_excluded_chain(const lexborrow_t& chain) const {
return (!chains_filter.empty() &&
chains_filter.count(reinterpret_cast<const lexidx_t&>(chain)) == 0);
}
bool is_polypeptide(const char * entity_id) const {
return polypeptide_entities.count(entity_id);
}
CifContentInfo(PyMOLGlobals * G, bool use_auth=true) :
G(G),
type(CIF_UNKNOWN),
fractional(false),
use_auth(use_auth) {}
};
/**
* Make a string key that represents the collection of alt id, asym id,
* atom id, comp id and seq id components of the label for a macromolecular
* atom site.
*/
static std::string make_mm_atom_site_label(PyMOLGlobals * G, const AtomInfoType * a) {
char resi[8];
AtomResiFromResv(resi, sizeof(resi), a);
std::string key(LexStr(G, a->chain));
key += '/';
key += LexStr(G, a->resn);
key += '/';
key += resi;
key += '/';
key += LexStr(G, a->name);
key += '/';
key += a->alt;
return key;
}
static std::string make_mm_atom_site_label(PyMOLGlobals * G, const char * asym_id,
const char * comp_id, const char * seq_id, const char * ins_code,
const char * atom_id, const char * alt_id) {
std::string key(asym_id);
key += '/';
key += comp_id;
key += '/';
key += seq_id;
key += ins_code;
key += '/';
key += atom_id;
key += '/';
key += alt_id;
return key;
}
/**
* Like strncpy, but only copy alphabetic characters.
*/
static void strncpy_alpha(char* dest, const char* src, size_t n)
{
for (size_t i = 0; i != n; ++i) {
if (!isalpha(src[i])) {
memset(dest + i, 0, n - i);
break;
}
dest[i] = src[i];
}
}
/**
* Get first non-NULL element
*/
template <typename T>
static T VLAGetFirstNonNULL(T * vla) {
int n = VLAGetSize(vla);
for (int i = 0; i < n; ++i)
if (vla[i])
return vla[i];
return nullptr;
}
/**
* Lookup one key in a map, return true if found and
* assign output reference `value1`
*/
template <typename Map, typename Key, typename T>
inline bool find1(Map& dict, T& value1, const Key& key1) {
auto it = dict.find(key1);
if (it == dict.end())
return false;
value1 = it->second;
return true;
}
/**
* Lookup two keys in a map, return true if both found and
* assign output references `value1` and `value2`.
*/
template <typename Map, typename Key, typename T>
inline bool find2(Map& dict,
T& value1, const Key& key1,
T& value2, const Key& key2) {
if (!find1(dict, value1, key1))
return false;
if (!find1(dict, value2, key2))
return false;
return true;
}
static void AtomInfoSetEntityId(PyMOLGlobals * G, AtomInfoType * ai, const char * entity_id) {
ai->custom = LexIdx(G, entity_id);
#ifdef _PYMOL_IP_PROPERTIES
PropertySet(G, ai, "entity_id", entity_id);
#endif
}
/**
* Initialize a bond. Only one of symmetry_1 or symmetry_2 must be non-default.
* If symmetry_2 is default and symmetry_1 is non-default, then swap the
* indices.
*/
static bool BondTypeInit3(PyMOLGlobals* G, BondType* bond, unsigned i1,
unsigned i2, const char* symmetry_1, const char* symmetry_2, int order = 1)
{
auto symop_1 = pymol::SymOp(symmetry_1);
auto symop_2 = pymol::SymOp(symmetry_2);
if (symop_1) {
if (symop_2) {
PRINTFB(G, FB_Executive, FB_Warnings)
" Warning: Bonds with two symmetry operations not supported\n" ENDFB(G);
return false;
}
std::swap(i1, i2);
std::swap(symop_1, symop_2);
}
BondTypeInit2(bond, i1, i2, order);
bond->symop_2 = symop_2;
return true;
}
/**
* Add one bond without checking if it already exists
*/
static void ObjectMoleculeAddBond2(ObjectMolecule * I, int i1, int i2, int order) {
VLACheck(I->Bond, BondType, I->NBond);
BondTypeInit2(I->Bond + I->NBond, i1, i2, order);
I->NBond++;
}
/**
* Get the distance between two atoms in ObjectMolecule
*/
static float GetDistance(ObjectMolecule * I, int i1, int i2) {
const CoordSet *cset;
int idx1 = -1, idx2 = -1;
// find first coordset which contains both atoms
if (I->DiscreteFlag) {
cset = I->DiscreteCSet[i1];
if (cset == I->DiscreteCSet[i2]) {
idx1 = I->DiscreteAtmToIdx[i1];
idx2 = I->DiscreteAtmToIdx[i2];
}
} else {
for (int i = 0; i < I->NCSet; ++i) {
if ((cset = I->CSet[i])) {
if ((idx1 = cset->AtmToIdx[i1]) != -1 &&
(idx2 = cset->AtmToIdx[i2]) != -1) {
break;
}
}
}
}
if (idx1 == -1 || idx2 == -1)
return 999.f;
float v[3];
subtract3f(
cset->coordPtr(idx1),
cset->coordPtr(idx2), v);
return length3f(v);
}
/**
* Bond order string to int
*/
static int bondOrderLookup(const char * order) {
if (p_strcasestartswith(order, "doub"))
return 2;
if (p_strcasestartswith(order, "trip"))
return 3;
if (p_strcasestartswith(order, "arom"))
return 4;
if (p_strcasestartswith(order, "delo"))
return 4;
// single
return 1;
}
/**
* Read bonds from CHEM_COMP_BOND in `bond_dict` dictionary
*/
static bool read_chem_comp_bond_dict(const cif_data * data, bond_dict_t &bond_dict) {
const cif_array *arr_id_1, *arr_id_2, *arr_order, *arr_comp_id;
if( !(arr_id_1 = data->get_arr("_chem_comp_bond.atom_id_1")) ||
!(arr_id_2 = data->get_arr("_chem_comp_bond.atom_id_2")) ||
!(arr_order = data->get_arr("_chem_comp_bond.value_order")) ||
!(arr_comp_id = data->get_arr("_chem_comp_bond.comp_id"))) {
if ((arr_comp_id = data->get_arr("_chem_comp_atom.comp_id"))) {
// atom(s) but no bonds (e.g. metals)
bond_dict.set_unknown(arr_comp_id->as_s());
return true;
}
return false;
}
const char *name1, *name2, *resn;
int order_value;
int nrows = arr_id_1->size();
for (int i = 0; i < nrows; i++) {
resn = arr_comp_id->as_s(i);
name1 = arr_id_1->as_s(i);
name2 = arr_id_2->as_s(i);
const char *order = arr_order->as_s(i);
order_value = bondOrderLookup(order);
bond_dict[resn].set(name1, name2, order_value);
}
// alt_atom_id -> atom_id
if ((arr_comp_id = data->get_arr("_chem_comp_atom.comp_id")) &&
(arr_id_1 = data->get_arr("_chem_comp_atom.atom_id")) &&
(arr_id_2 = data->get_arr("_chem_comp_atom.alt_atom_id"))) {
nrows = arr_id_1->size();
// set of all non-alt ids
std::set<pymol::zstring_view> atom_ids;
for (int i = 0; i < nrows; ++i) {
atom_ids.insert(arr_id_1->as_s(i));
}
for (int i = 0; i < nrows; ++i) {
resn = arr_comp_id->as_s(i);
name1 = arr_id_1->as_s(i);
name2 = arr_id_2->as_s(i);
// skip identity mapping
if (strcmp(name1, name2) == 0) {
continue;
}
// alt id must not also be a non-alt id (PYMOL-3470)
if (atom_ids.count(name2)) {
fprintf(stderr,
"Warning: _chem_comp_atom.alt_atom_id %s/%s ignored for bonding\n",
resn, name2);
continue;
}
bond_dict[resn].add_alt_name(name1, name2);
}
}
return true;
}
/**
* parse $PYMOL_DATA/chem_comp_bond-top100.cif (subset of components.cif) into
* a static (global) dictionary.
*/
static bond_dict_t * get_global_components_bond_dict(PyMOLGlobals * G) {
static bond_dict_t bond_dict;
if (bond_dict.empty()) {
const char * pymol_data = getenv("PYMOL_DATA");
if (!pymol_data || !pymol_data[0])
return nullptr;
std::string path(pymol_data);
path.append(PATH_SEP).append("chem_comp_bond-top100.cif");
cif_file_with_error_capture cif;
if (!cif.parse_file(path.c_str())) {
PRINTFB(G, FB_Executive, FB_Warnings)
" Warning: Loading '%s' failed: %s\n", path.c_str(),
cif.m_error_msg.c_str() ENDFB(G);
return nullptr;
}
for (const auto& [code, datablock] : cif.datablocks()) {
read_chem_comp_bond_dict(&datablock, bond_dict);
}
}
return &bond_dict;
}
/**
* True for N-H1 and N-H3, those are not in the chemical components dictionary.
*/
static bool is_N_H1_or_H3(PyMOLGlobals * G,
const AtomInfoType * a1,
const AtomInfoType * a2) {
if (a2->name == G->lex_const.N) {
a2 = a1;
} else if (a1->name != G->lex_const.N) {
return false;
}
return (a2->name == G->lex_const.H1 || a2->name == G->lex_const.H3);
}
/**
* Add bonds for one residue, with atoms spanning from i_start to i_end-1,
* based on components.cif
*/
static void ConnectComponent(ObjectMolecule * I, int i_start, int i_end,
bond_dict_t * bond_dict) {
if (i_end - i_start < 2)
return;
auto G = I->G;
const AtomInfoType *a1, *a2, *ai = I->AtomInfo.data();
int order;
// get residue bond dictionary
auto res_dict = bond_dict->get(G, LexStr(G, ai[i_start].resn));
if (res_dict == nullptr)
return;
// for all pairs of atoms in given set
for (int i1 = i_start + 1; i1 < i_end; i1++) {
for (int i2 = i_start; i2 < i1; i2++) {
a1 = ai + i1;
a2 = ai + i2;
// don't connect different alt codes
if (a1->alt[0] && a2->alt[0] && strcmp(a1->alt, a2->alt) != 0) {
continue;
}
// restart if we hit the next residue in bulk solvent (atoms must
// not be sorted for this)
// TODO artoms are sorted at this point
if (a1->name == a2->name) {
i_start = i1;
break;
}
// lookup if atoms are bonded
order = res_dict->get(LexStr(G, a1->name), LexStr(G, a2->name));
if (order < 0) {
if (!is_N_H1_or_H3(G, a1, a2) || GetDistance(I, i1, i2) > 1.2)
continue;
order = 1;
}
// make bond
ObjectMoleculeAddBond2(I, i1, i2, order);
}
}
}
/**
* Add intra residue bonds based on components.cif, and common polymer
* connecting bonds (C->N, O3*->P)
*/
static int ObjectMoleculeConnectComponents(ObjectMolecule * I,
bond_dict_t * bond_dict=nullptr) {
PyMOLGlobals * G = I->G;
int i_start = 0;
std::vector<int> i_prev_c[2], i_prev_o3[2];
const lexborrow_t lex_O3s = LexBorrow(G, "O3*");
const lexborrow_t lex_O3p = LexBorrow(G, "O3'");
if (!bond_dict) {
// read components.cif
if (!(bond_dict = get_global_components_bond_dict(G)))
return false;
}
// reserve some memory for new bonds
I->Bond.reserve(I->NAtom * 4);
for (int i = 0; i < I->NAtom; ++i) {
auto const& atom = I->AtomInfo[i];
// intra-residue
if(!AtomInfoSameResidue(G, I->AtomInfo + i_start, I->AtomInfo + i)) {
ConnectComponent(I, i_start, i, bond_dict);
i_start = i;
i_prev_c[0] = std::move(i_prev_c[1]);
i_prev_o3[0] = std::move(i_prev_o3[1]);
i_prev_c[1].clear();
i_prev_o3[1].clear();
}
// inter-residue polymer bonds
if (atom.name == G->lex_const.C) {
i_prev_c[1].push_back(i);
} else if (atom.name == lex_O3s || atom.name == lex_O3p) {
i_prev_o3[1].push_back(i);
} else {
auto const* i_prev_ptr =
(atom.name == G->lex_const.N) ? i_prev_c :
(atom.name == G->lex_const.P) ? i_prev_o3 : nullptr;
if (i_prev_ptr && !i_prev_ptr->empty()) {
for (int i_prev : *i_prev_ptr) {
bool alt_check = !atom.alt[0] || !I->AtomInfo[i_prev].alt[0] ||
atom.alt[0] == I->AtomInfo[i_prev].alt[0];
if (alt_check && GetDistance(I, i_prev, i) < 1.8) {
// make bond
ObjectMoleculeAddBond2(I, i_prev, i, 1);
}
}
}
}
}
// final residue
ConnectComponent(I, i_start, I->NAtom, bond_dict);
// clean up
VLASize(I->Bond, BondType, I->NBond);
return true;
}
/**
* secondary structure hash
*/
class sshashkey {
public:
lexborrow_t chain; // borrowed ref
int resv;
char inscode;
void assign(const lexborrow_t& asym_id_, int resv_, char ins_code_ = '\0') {
chain = asym_id_;
resv = resv_;
inscode = ins_code_;
}
// comparable to sshashkey and AtomInfoType
template <typename T> int compare(const T &other) const {
int test = resv - other.resv;
if (test == 0) {
test = (chain - other.chain);
if (test == 0)
test = inscode - other.inscode;
}
return test;
}
bool operator<(const sshashkey &other) const { return compare(other) < 0; }
bool operator>(const sshashkey &other) const { return compare(other) > 0; }
};
class sshashvalue {
public:
char ss;
sshashkey end;
};
typedef std::map<sshashkey, sshashvalue> sshashmap;
// PDBX_STRUCT_OPER_LIST type
typedef std::map<std::string, std::array<float, 16> > oper_list_t;
// type for parsed PDBX_STRUCT_OPER_LIST
typedef std::vector<std::vector<std::string> > oper_collection_t;
/**
* Parse operation expressions like (1,2)(3-6)
*/
static oper_collection_t parse_oper_expression(const std::string &expr) {
oper_collection_t collection;
// first step to split parenthesized chunks
std::vector<std::string> a_vec = strsplit(expr, ')');
// loop over chunks (still include leading '(')
for (auto& a_item : a_vec) {
const char * a_chunk = a_item.c_str();
// finish chunk
while (*a_chunk == '(')
++a_chunk;
// skip empty chunks
if (!*a_chunk)
continue;
collection.resize(collection.size() + 1);
oper_collection_t::reference ids = collection.back();
// split chunk by commas
std::vector<std::string> b_vec = strsplit(a_chunk, ',');
// look for ranges
for (auto& b_item : b_vec) {
// "c_d" will have either one (no range) or two items
std::vector<std::string> c_d = strsplit(b_item, '-');
ids.push_back(c_d[0]);
if (c_d.size() == 2)
for (int i = atoi(c_d[0].c_str()) + 1,
j = atoi(c_d[1].c_str()) + 1; i < j; ++i)
{
char i_str[16];
snprintf(i_str, sizeof(i_str), "%d", i);
ids.push_back(i_str);
}
}
}
return collection;
}
/**
* Get chains which are part of the assembly
*
* assembly_chains: output set
* assembly_id: ID of the assembly or nullptr to use first assembly
*/
static bool get_assembly_chains(PyMOLGlobals * G,
const cif_data * data,
std::set<lexidx_t> &assembly_chains,
const char * assembly_id) {
const cif_array *arr_id, *arr_asym_id_list;
if ((arr_id = data->get_arr("_pdbx_struct_assembly_gen.assembly_id")) == nullptr ||
(arr_asym_id_list = data->get_arr("_pdbx_struct_assembly_gen.asym_id_list")) == nullptr)
return false;
for (unsigned i = 0, nrows = arr_id->size(); i < nrows; ++i) {
if (strcmp(assembly_id, arr_id->as_s(i)))
continue;
const char * asym_id_list = arr_asym_id_list->as_s(i);
std::vector<std::string> chains = strsplit(asym_id_list, ',');
for (auto& chain : chains) {
assembly_chains.insert(LexIdx(G, chain.c_str()));
}
}
return !assembly_chains.empty();
}
/**
* Read assembly
*
* atInfo: atom info array to use for chain check
* cset: template coordinate set to create assembly coordsets from
* assembly_id: assembly identifier
*
* return: assembly coordinates as VLA of coordinate sets
*/
static
CoordSet ** read_pdbx_struct_assembly(PyMOLGlobals * G,
const cif_data * data,
const AtomInfoType * atInfo,
const CoordSet * cset,
const char * assembly_id) {
const cif_array *arr_id, *arr_assembly_id, *arr_oper_expr, *arr_asym_id_list;
if ((arr_id = data->get_arr("_pdbx_struct_oper_list.id")) == nullptr ||
(arr_assembly_id = data->get_arr("_pdbx_struct_assembly_gen.assembly_id")) == nullptr ||
(arr_oper_expr = data->get_arr("_pdbx_struct_assembly_gen.oper_expression")) == nullptr ||
(arr_asym_id_list = data->get_arr("_pdbx_struct_assembly_gen.asym_id_list")) == nullptr)
return nullptr;
const cif_array * arr_matrix[] = {
data->get_opt("_pdbx_struct_oper_list.matrix[1][1]"),
data->get_opt("_pdbx_struct_oper_list.matrix[1][2]"),
data->get_opt("_pdbx_struct_oper_list.matrix[1][3]"),
data->get_opt("_pdbx_struct_oper_list.vector[1]"),
data->get_opt("_pdbx_struct_oper_list.matrix[2][1]"),
data->get_opt("_pdbx_struct_oper_list.matrix[2][2]"),
data->get_opt("_pdbx_struct_oper_list.matrix[2][3]"),
data->get_opt("_pdbx_struct_oper_list.vector[2]"),
data->get_opt("_pdbx_struct_oper_list.matrix[3][1]"),
data->get_opt("_pdbx_struct_oper_list.matrix[3][2]"),
data->get_opt("_pdbx_struct_oper_list.matrix[3][3]"),
data->get_opt("_pdbx_struct_oper_list.vector[3]")
};
// build oper_list from _pdbx_struct_oper_list
oper_list_t oper_list;
for (unsigned i = 0, nrows = arr_id->size(); i < nrows; ++i) {
float * matrix = oper_list[arr_id->as_s(i)].data();
identity44f(matrix);
for (int j = 0; j < 12; ++j) {
matrix[j] = arr_matrix[j]->as_d(i);
}
}
CoordSet ** csets = nullptr;
int csetbeginidx = 0;
// assembly
for (unsigned i = 0, nrows = arr_oper_expr->size(); i < nrows; ++i) {
if (strcmp(assembly_id, arr_assembly_id->as_s(i)))
continue;
const char * oper_expr = arr_oper_expr->as_s(i);
const char * asym_id_list = arr_asym_id_list->as_s(i);
oper_collection_t collection = parse_oper_expression(oper_expr);
std::vector<std::string> chains = strsplit(asym_id_list, ',');
std::set<lexborrow_t> chains_set;
for (auto& chain : chains) {
auto borrowed = LexBorrow(G, chain.c_str());
if (borrowed != LEX_BORROW_NOTFOUND) {
chains_set.insert(borrowed);
}
}
// new coord set VLA
int ncsets = 1;
for (const auto& c_item : collection) {
ncsets *= c_item.size();
}
if (!csets) {
csets = VLACalloc(CoordSet*, ncsets);
} else {
csetbeginidx = VLAGetSize(csets);
VLASize(csets, CoordSet*, csetbeginidx + ncsets);
}
// for cartesian product
int c_src_len = 1;
// coord set for subset of atoms
CoordSet ** c_csets = csets + csetbeginidx;
c_csets[0] = CoordSetCopyFilterChains(cset, atInfo, chains_set);
// build new coord sets
for (auto c_it = collection.rbegin(); c_it != collection.rend(); ++c_it) {
// copy
int j = c_src_len;
while (j < c_src_len * c_it->size()) {
// cartesian product
for (int k = 0; k < c_src_len; ++k, ++j) {
c_csets[j] = CoordSetCopy(c_csets[k]);
}
}
// transform
j = 0;
for (auto& s_item : *c_it) {
const float * matrix = oper_list[s_item].data();
// cartesian product
for (int k = 0; k < c_src_len; ++k, ++j) {
CoordSetTransform44f(c_csets[j], matrix);
}
}
// cartesian product
// Note: currently, "1m4x" seems to be the only structure in the PDB
// which uses a cartesian product expression
c_src_len *= c_it->size();
}
}
// return assembly coordsets
return csets;
}
/**
* Set ribbon_trace_atoms and cartoon_trace_atoms for CA/P only models
*/
static bool read_pdbx_coordinate_model(PyMOLGlobals * G, const cif_data * data, ObjectMolecule * mol) {
const cif_array * arr_type = data->get_arr("_pdbx_coordinate_model.type");
const cif_array * arr_asym = data->get_arr("_pdbx_coordinate_model.asym_id");
if (!arr_type || !arr_asym)
return false;
// affected chains
std::set<pymol::zstring_view> asyms;
// collect CA/P-only chain identifiers
for (unsigned i = 0, nrows = arr_type->size(); i < nrows; ++i) {
const char * type = arr_type->as_s(i);
// no need anymore to check "CA ATOMS ONLY", since nonbonded CA are
// now (v1.8.2) detected automatically in RepCartoon and RepRibbon
if (strcmp(type, "P ATOMS ONLY") == 0) {
asyms.insert(arr_asym->as_s(i));
}
}
if (asyms.empty())
return false;
// set on atom-level
for (int i = 0, nrows = VLAGetSize(mol->AtomInfo); i < nrows; ++i) {
AtomInfoType * ai = mol->AtomInfo + i;
if (asyms.count(LexStr(G, ai->segi))) {
SettingSet(G, cSetting_cartoon_trace_atoms, true, ai);
SettingSet(G, cSetting_ribbon_trace_atoms, true, ai);
}
}
return true;
}
/**
* Read CELL and SYMMETRY
*/
static CSymmetry * read_symmetry(PyMOLGlobals * G, const cif_data * data) {
const cif_array * cell[6] = {
data->get_arr("_cell?length_a"),
data->get_arr("_cell?length_b"),
data->get_arr("_cell?length_c"),
data->get_arr("_cell?angle_alpha"),
data->get_arr("_cell?angle_beta"),
data->get_arr("_cell?angle_gamma")
};
for (int i = 0; i < 6; i++)
if (cell[i] == nullptr)
return nullptr;
CSymmetry * symmetry = new CSymmetry(G);
if (!symmetry)
return nullptr;
float cellparams[6];
for (int i = 0; i < 6; ++i) {
cellparams[i] = cell[i]->as_d();
}
symmetry->Crystal.setDims(cellparams);
symmetry->Crystal.setAngles(cellparams + 3);
symmetry->setSpaceGroup(
data->get_opt("_symmetry?space_group_name_h-m",
"_space_group?name_h-m_alt")->as_s());
symmetry->PDBZValue = data->get_opt("_cell.z_pdb")->as_i(0, 1);
// register symmetry operations if given
const cif_array * arr_as_xyz = data->get_arr(
"_symmetry_equiv?pos_as_xyz",
"_space_group_symop?operation_xyz");
if (arr_as_xyz) {
std::vector<std::string> sym_op;
for (unsigned i = 0, n = arr_as_xyz->size(); i < n; ++i) {
sym_op.push_back(arr_as_xyz->as_s(i));
}
SymmetrySpaceGroupRegister(G, symmetry->spaceGroup(), sym_op);
}
return symmetry;
}
/**
* Read CHEM_COMP_ATOM
*/
static CoordSet ** read_chem_comp_atom_model(PyMOLGlobals * G, const cif_data * data,
AtomInfoType ** atInfoPtr) {
const cif_array *arr_x, *arr_y = nullptr, *arr_z = nullptr;
// setting to exclude one or more coordinate columns
unsigned mask = SettingGetGlobal_i(G, cSetting_chem_comp_cartn_use);
const char * feedback = "";
if (!mask) {
mask = 0xFF;
}
if ((mask & 0x01)
&& (arr_x = data->get_arr("_chem_comp_atom.pdbx_model_cartn_x_ideal"))
&& !arr_x->is_missing_all()) {
arr_y = data->get_arr("_chem_comp_atom.pdbx_model_cartn_y_ideal");
arr_z = data->get_arr("_chem_comp_atom.pdbx_model_cartn_z_ideal");
feedback = ".pdbx_model_Cartn_{x,y,z}_ideal";
} else if ((mask & 0x02)
&& (arr_x = data->get_arr("_chem_comp_atom.model_cartn_x"))) {
arr_y = data->get_arr("_chem_comp_atom.model_cartn_y");
arr_z = data->get_arr("_chem_comp_atom.model_cartn_z");
feedback = ".model_Cartn_{x,y,z}";
} else if ((mask & 0x04)
&& (arr_x = data->get_arr("_chem_comp_atom.x"))
&& !arr_x->is_missing_all()) {
arr_y = data->get_arr("_chem_comp_atom.y");
arr_z = data->get_arr("_chem_comp_atom.z");
feedback = ".{x,y,z}";
}
if (!arr_x || !arr_y || !arr_z) {
return nullptr;
}
PRINTFB(G, FB_Executive, FB_Details)
" ExecutiveLoad-Detail: Detected chem_comp CIF (%s)\n", feedback
ENDFB(G);
const cif_array * arr_name = data->get_opt("_chem_comp_atom.atom_id");
const cif_array * arr_symbol = data->get_opt("_chem_comp_atom.type_symbol");
const cif_array * arr_resn = data->get_opt("_chem_comp_atom.comp_id");
const cif_array * arr_partial_charge = data->get_opt("_chem_comp_atom.partial_charge");
const cif_array * arr_formal_charge = data->get_opt("_chem_comp_atom.charge");
const cif_array * arr_stereo = data->get_opt("_chem_comp_atom.pdbx_stereo_config");
int nrows = arr_x->size();
AtomInfoType *ai;
int atomCount = 0, nAtom = nrows;
float * coord = VLAlloc(float, 3 * nAtom);
int auto_show = RepGetAutoShowMask(G);
for (int i = 0; i < nrows; i++) {
if (arr_x->is_missing(i))
continue;
VLACheck(*atInfoPtr, AtomInfoType, atomCount);
ai = *atInfoPtr + atomCount;
memset((void*) ai, 0, sizeof(AtomInfoType));
ai->rank = atomCount;
ai->id = atomCount + 1;
LexAssign(G, ai->name, arr_name->as_s(i));
LexAssign(G, ai->resn, arr_resn->as_s(i));
strncpy(ai->elem, arr_symbol->as_s(i), cElemNameLen);
ai->partialCharge = arr_partial_charge->as_d(i);
ai->formalCharge = arr_formal_charge->as_i(i);
ai->hetatm = true;
ai->visRep = auto_show;
AtomInfoSetStereo(ai, arr_stereo->as_s(i));
AtomInfoAssignParameters(G, ai);
AtomInfoAssignColors(G, ai);
coord[atomCount * 3 + 0] = arr_x->as_d(i);
coord[atomCount * 3 + 1] = arr_y->as_d(i);