Repository navigation
Expand file tree
/
Copy path_pach3.pxi
More file actions
1490 lines (1398 loc) · 77.3 KB
/
Copy path_pach3.pxi
File metadata and controls
1490 lines (1398 loc) · 77.3 KB
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
#
# Copyright 2026 Ramil Nugmanov <nougmanoff@protonmail.com>
# This file is part of chython.
#
# chython is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, see <https://www.gnu.org/licenses/>.
#
# ==================================================================================================
# pach VERSIONS 3 AND 4. One design and one reader; version 3 carries display coordinates and
# version 4 does not. `docs/pach.rst` is the wire layout a third party implements against and this
# comment is the same layouts stated where the code is.
#
# Header, 12 bytes:
# 0 version u8 3 | 4
# 1 flags u8 bit 0 = map block present; bit 1 = bond-group block present;
# bits 2-7 reserved, must be 0
# 2-3 atoms u16
# 4-5 bonds u16
# 6-7 stereo u16
# 8-9 sgroups u16 atom enhanced-stereo entries
# 10-11 bgroups u16 bond enhanced-stereo entries
#
# Every count is in the header and every stride is constant, so a record's length is arithmetic and
# `pach_record_length` is O(1). The header is the one place slack is deliberate: a future block needs
# a COUNT, and spare bits inside a fixed-stride record cannot hold one.
# ==================================================================================================
DEF PACH3_VERSION_XY = 3
DEF PACH3_VERSION_FLAT = 4
DEF PACH3_HEADER_LEN = 12
DEF PACH3_ATOM_XY_LEN = 9
DEF PACH3_ATOM_FLAT_LEN = 3
DEF PACH3_BOND_LEN = 5
DEF PACH3_STEREO_LEN = 9
DEF PACH3_SGROUP_LEN = 3
DEF PACH3_MAP_LEN = 2
DEF PACH3_FLAG_MAP = 0x01
DEF PACH3_FLAG_BGROUP = 0x02
# One entry per BOND in a bond enhanced-stereo collection. Atom indices and five bytes rather than
# a bond position and three: the atom-group block references indices, `PACH3_BOND_LEN` is already 5
# for the same pair-plus-byte shape, and `docs/pach.rst` is a layout a third party implements
# against -- resolving a reference should not require counting positions in another block.
# 0-1 u16 atom index a
# 2-3 u16 atom index b
# 4 u8 the sg_pack byte: kind 2 | group 6
DEF PACH3_BGROUP_LEN = 5
# The isotope field is 6 bits spelling `MDL_ISOTOPE[z] - 32 + value` for value 1..63, and 0 for unset:
# mass numbers 31 below the element's MDL reference to 31 above it. Measured maximum shift over
# chython's 436 nuclides is 8, so the field cannot fill.
DEF PACH3_ISOTOPE_BIAS = 32
# int24 two's complement at XY_SCALE: +/-838.8607 Angstrom, exact rather than rounded, so a decode and
# re-encode of a coordinate-bearing record is byte-stable.
DEF PACH3_XY_LIMIT = 8388607
cdef inline uint32_t _p3_u16(const unsigned char *p) noexcept nogil:
return p[0] | (<uint32_t> p[1] << 8)
cdef inline uint32_t _p3_present(Py_ssize_t at, Py_ssize_t length, uint32_t declared,
Py_ssize_t stride) noexcept nogil:
"""How many of a block's declared records are in the buffer.
THE HEADER'S COUNTS DEFINE THE LAYOUT AND THE BUFFER'S LENGTH DECIDES HOW MUCH OF IT ARRIVED. A
block starts where the declared counts put it and stops at whichever comes first, its own count or
the buffer's end -- so a missing byte costs the record it falls in and none of the records behind
it, and a count larger than the block holds reads what follows the block as its own records.
"""
cdef Py_ssize_t have
if at >= length:
return 0
have = (length - at) // stride
return declared if <Py_ssize_t> declared <= have else <uint32_t> have
cdef inline void _p3_put_u16(unsigned char *p, uint32_t v) noexcept nogil:
p[0] = <unsigned char> (v & 0xff)
p[1] = <unsigned char> ((v >> 8) & 0xff)
cdef inline int32_t _p3_i24(const unsigned char *p) noexcept nogil:
cdef uint32_t v = p[0] | (<uint32_t> p[1] << 8) | (<uint32_t> p[2] << 16)
if v & 0x800000:
return <int32_t> v - 0x1000000
return <int32_t> v
cdef inline void _p3_put_i24(unsigned char *p, int32_t v) noexcept nogil:
cdef uint32_t u = <uint32_t> v & 0xffffff
p[0] = <unsigned char> (u & 0xff)
p[1] = <unsigned char> ((u >> 8) & 0xff)
p[2] = <unsigned char> ((u >> 16) & 0xff)
cdef inline Py_ssize_t _pach3_size(uint32_t atoms, uint32_t bonds, uint32_t stereo, uint32_t sgroups,
uint32_t bgroups, bint want_xy, bint want_map) noexcept nogil:
"""The length arithmetic the header states, from the counts rather than from a buffer."""
cdef Py_ssize_t out = PACH3_HEADER_LEN \
+ <Py_ssize_t> atoms * (PACH3_ATOM_XY_LEN if want_xy else PACH3_ATOM_FLAT_LEN) \
+ <Py_ssize_t> bonds * PACH3_BOND_LEN \
+ <Py_ssize_t> stereo * PACH3_STEREO_LEN \
+ <Py_ssize_t> sgroups * PACH3_SGROUP_LEN \
+ <Py_ssize_t> bgroups * PACH3_BGROUP_LEN
if want_map:
out += <Py_ssize_t> atoms * PACH3_MAP_LEN
return out
cdef Py_ssize_t _pach3_length(const unsigned char *data, Py_ssize_t length) noexcept nogil:
"""Byte length of the version 3 or 4 record at `data`, or -1 when the header is not all there.
Reads the header and nothing else: a length that had to walk the record would make a caller
stepping through a concatenated store quadratic in the store.
"""
if length < PACH3_HEADER_LEN:
return -1
return _pach3_size(_p3_u16(data + 2), _p3_u16(data + 4), _p3_u16(data + 6), _p3_u16(data + 8),
_p3_u16(data + 10), data[0] == PACH3_VERSION_XY,
(data[1] & PACH3_FLAG_MAP) != 0)
cdef int _pach3_report_losses(MoleculeContainer mol, uint32_t drop_mask, bint strict) except -1:
"""Everything the arena holds that versions 3 and 4 have no field for, named one field at a time.
A conformer set is one of them: the coordinate block is 2D display geometry, so a 3D conformer is
a loss this asks about rather than a coordinate it could write. Map numbers, wedges, atom and bond
stereo groups and stereo each have a block of their own and are not asked about here.
`_pach_loss` is the destination and the strict switch; see it for why a writer logs.
"""
cdef Structure structure = mol._structure
cdef atom_t *atoms = structure.atoms()
cdef halfedge_t *edges = csr_edges(structure)
cdef uint32_t i, k, hits
cdef uint32_t first = 0
if not (drop_mask & PACH_DROP_CIP):
hits = 0
for i in range(structure.header.atom_count):
if atoms[i].reserved & ATOM_CIP_MASK:
if not hits:
first = i
hits += 1
if hits:
_pach_loss(mol, strict, 'pach:cip-lost',
'atom %d carries a cip descriptor and the pach format has no field for one; '
'pass drop=[\'cip\'] to write the record without it' % atoms[first].n,
'the pach format has no cip field, so %d atom descriptor(s) were not written; '
'assign_cip() recomputes them' % hits)
hits = 0
for k in range(2 * structure.header.bond_count):
if edges[k].flags & HE_CIP_MASK:
hits += 1
if hits:
_pach_loss(mol, strict, 'pach:cip-lost',
'a bond carries a cip descriptor and the pach format has no field for one; '
'pass drop=[\'cip\'] to write the record without it',
'the pach format has no cip field, so %d bond descriptor(s) were not written'
% (hits // 2))
if not (drop_mask & PACH_DROP_SGROUPS) and structure_sgroup_count(structure):
_pach_loss(mol, strict, 'pach:sgroups-lost',
'this molecule carries %d sgroups and the pach format has no field for them; pass '
'drop=[\'sgroups\'] to write the record without them'
% structure_sgroup_count(structure),
'the pach format has no S-group field, so %d sgroup(s) were not written'
% structure_sgroup_count(structure))
if not (drop_mask & PACH_DROP_CONFORMERS) and structure_has(structure, SEG_CONFORMERS):
_pach_loss(mol, strict, 'pach:conformers-lost',
'this molecule carries 3D conformers and the pach format holds 2D display '
'coordinates only; pass drop=[\'conformers\'] to write the record without them, or '
'to_bytes() to keep them',
'the pach format holds 2D display coordinates only, so %d conformer(s) were not '
'written; to_bytes() keeps them' % structure_conformer_count(structure))
if not (drop_mask & PACH_DROP_TITLE) and len(blob_bytes(structure, SEG_OPAQUE_BLOB, 0)):
_pach_loss(mol, strict, 'pach:title-lost',
'this molecule carries a title and the pach format has no text of any kind; pass '
'drop=[\'title\'] to write the record without it',
'the pach format has no text of any kind, so the title was not written')
# `_meta` and not `meta`, so asking the question does not create the dict it is asking about
if not (drop_mask & PACH_DROP_META) and mol._meta:
_pach_loss(mol, strict, 'pach:meta-lost',
'this molecule carries %d metadata key(s) and the pach format has no field for any '
'of them; pass drop=[\'meta\'] to write the record without them' % len(mol._meta),
'the pach format has no metadata field, so %d key(s) were not written'
% len(mol._meta))
return 0
cdef int _pach3_put_atom(atom_t *a, unsigned char *out) except -1:
"""The three bytes both versions share, at `out[0:3]`.
byte 0 bit 7 clear: bits 6-0 are the atomic number. Bit 7 set: bits 6-0 are the R index.
byte 1 isotope 6 | radical 1 | h_pinned 1
byte 2 implicit H 4 | charge + 4, 4
No field crosses a byte boundary, and the hydrogen nibble is the arena's own: 0..14 and 15 for
H_UNKNOWN, with no translation either way.
"""
cdef int32_t shift, charge
if a.element == 0:
if a.isotope:
raise ValueError('atom %d is an R marker carrying isotope %d, and the isotope field is a '
'shift from an element\'s reference mass' % (a.n, a.isotope))
out[0] = <unsigned char> (0x80 | (at_r_index(a) & 0x7f))
else:
out[0] = <unsigned char> a.element
out[1] = 0
if a.isotope:
shift = <int32_t> a.isotope - <int32_t> MDL_ISOTOPE[a.element] + PACH3_ISOTOPE_BIAS
if shift < 1 or shift > 63:
raise ValueError('atom %d carries isotope %d and the pach isotope field reaches 31 mass '
'numbers either side of element %d\'s reference %d'
% (a.n, a.isotope, a.element, MDL_ISOTOPE[a.element]))
out[1] = <unsigned char> shift
if at_radical(a):
out[1] |= 0x40
if at_h_pinned(a):
out[1] |= 0x80
charge = <int32_t> a.charge + 4
if charge < 0 or charge > 15:
raise ValueError('atom %d carries charge %d and the pach charge field holds -4 to +11'
% (a.n, a.charge))
out[2] = <unsigned char> ((a.hydrogens & 0x0f) | (<unsigned char> charge << 4))
return 0
cdef inline void _pach3_unit_frame(stereo_unit_t *u, uint32_t *want) noexcept nogil:
"""The unit's four directions in the ORDER THE RECORD USES, which is stated here and nowhere else.
SU_TETRA the three named directions in refs order, then the implied one -- refs[3] when
all four are named, and the unnamed direction otherwise
bond kinds per list, the named direction and then the list's other one, the anchor's list
first. `SU_NO_REF` sits in the MIDDLE of the four slots for a bond kind -- an
implicit-hydrogen but-2-ene is (C, None, C, None) -- which is why this is built
per list rather than by compacting the four.
Ruling F41 puts at most one unnamed direction in a list, so "the named one" is `refs[base]` unless
that is `SU_NO_REF`. F26 orders each list's unnamed direction last, so the frame EQUALS `refs` on
every unit perception emits today and `smi_perm_of` answers the identity --
`test_pach3.py:test_the_frame_is_refs_order_on_every_configured_unit` is that claim's harness. The
frame is built anyway because then a revised F26 cannot change what a stored record means. The
decoder inverts exactly this, and `translate_parity` is an XOR by the permutation's parity and
therefore its own inverse, which makes the pair a fixed point.
"""
cdef uint32_t j, base, r
cdef uint32_t k = 0
if u.kind == SU_TETRA:
want[0] = SU_NO_REF; want[1] = SU_NO_REF; want[2] = SU_NO_REF; want[3] = SU_NO_REF
for j in range(4):
r = u.refs[j]
if r != SU_NO_REF:
want[k] = r
k += 1
else:
for base in range(0, 4, 2):
r = u.refs[base]
if r == SU_NO_REF:
want[base] = u.refs[base + 1]
want[base + 1] = SU_NO_REF
else:
want[base] = r
want[base + 1] = u.refs[base + 1]
cdef int _pach3_stereo_record(MoleculeContainer mol, Structure structure, stereo_unit_t *u,
uint8_t parity, unsigned char *out, bint strict) except -1:
"""One nine-byte stereo record, or nothing written and 0 returned when the unit is unconfigured.
bytes 0-1 slot0 bytes 2-3 slot1 bytes 4-5 slot2 bytes 6-7 slot3
byte 8 kind 3 | sign 1 | reserved 4
kind 0 SU_TETRA centre d0 d1 d2
kind 1 SU_CIS_TRANS end A a0 end B b0
kind 2 SU_ALLENE end A a0 end B b0 (the chain centre is not stored)
kind 3 SU_ATROPISOMER pivot A oA0 pivot B oB0
kind 4 SU_HELICAL fjord A iA0 fjord B iB0
kind 5 SU_PLANAR anchor r0 anchor r2 (one owner, stated twice)
A slot is an ATOM INDEX in the record's own atom block, which is arena slot order. A
configuration states the owner of each direction list and all but one of its directions; the last
is implied by identity -- the owner's direction not already named -- so there are no masks and no
sentinels and every slot holds a real atom.
`sign` is one bit because a record exists only for a configured unit: 0 is the even parity and 1
the odd one, and the unset third state needs no spelling. The reserved nibble is where a
three-state parity would go without touching the stride. The sign is the parity in the frame
`_pach3_unit_frame` builds, which is what lets ruling F26 be revised without invalidating a stored
record: nothing in the record depends on the direction ORDERING, only on identity.
"""
cdef atom_t *atoms = structure.atoms()
cdef uint32_t *ptr = csr_ptr(structure)
cdef halfedge_t *edges = csr_edges(structure)
cdef uint8_t kind = u.kind
cdef uint32_t anchor = u.anchor
cdef uint32_t owner_a, owner_b
cdef uint32_t terms[2]
cdef uint32_t inwards[2]
cdef uint32_t want[4]
cdef uint32_t perm[4]
if parity == 0:
return 0
if u.n_refs != 4:
# UNREACHABLE THROUGH PERCEPTION and kept anyway: `_stereo.pxi`'s "WHY N==4 IS THE ONLY CASE"
# states that all four `_stereo_emit` sites pass `n_refs=4` and that the one site which does
# not, `_stereo_anchor_collision_probe`, has its unit refused before translation. That is an
# invariant of another file over a table this one only reads, so the guard states it here.
_pach_loss(mol, strict, 'pach:stereo-lost',
'the stereo unit anchored at atom %d orders %d reference direction(s) and a parity '
'is a fact about four; pass drop=[\'stereo\'] to write the record without it'
% (atoms[anchor].n, u.n_refs),
'the stereo unit anchored at atom %d orders %d reference direction(s) and a parity '
'is a fact about four, so it was not written' % (atoms[anchor].n, u.n_refs))
return 0
_pach3_unit_frame(u, want)
if kind == SU_TETRA:
if want[2] == SU_NO_REF:
_pach_loss(mol, strict, 'pach:stereo-lost',
'the tetrahedral centre at atom %d names %d direction(s) with an atom of their '
'own and the pach record states three; pass drop=[\'stereo\'] to write the '
'record without it' % (atoms[anchor].n, 1 if want[1] == SU_NO_REF else 2),
'the tetrahedral centre at atom %d names %d direction(s) with an atom of their '
'own and the pach record states three, so it was not written'
% (atoms[anchor].n, 1 if want[1] == SU_NO_REF else 2))
return 0
_p3_put_u16(out, anchor)
_p3_put_u16(out + 2, want[0])
_p3_put_u16(out + 4, want[1])
_p3_put_u16(out + 6, want[2])
else:
# A list with TWO unnamed directions has no second slot to name and, per ruling F41
# (`_list_has_two_unnamed`), is not stereogenic -- so a configured unit cannot present one.
if want[0] == SU_NO_REF or want[2] == SU_NO_REF:
_pach_loss(mol, strict, 'pach:stereo-lost',
'the stereo unit anchored at atom %d has a direction list with no named '
'direction, so the pach record has nothing to state it against; pass '
'drop=[\'stereo\'] to write the record without it' % atoms[anchor].n,
'the stereo unit anchored at atom %d has a direction list with no named '
'direction, so it was not written' % atoms[anchor].n)
return 0
if kind == SU_ALLENE:
# The anchor is the chain's CENTRE and the record names the two ENDS, so the ends come
# from the chain and which end leads comes from which one owns the first named direction.
if not _pach_allene_ends(ptr, edges, anchor, terms, inwards):
_pach_loss(mol, strict, 'pach:stereo-lost',
'atom %d anchors an allene whose chain this molecule does not hold; pass '
'drop=[\'stereo\'] to write the record without it' % atoms[anchor].n,
'atom %d anchors an allene whose chain this molecule does not hold, so it '
'was not written' % atoms[anchor].n)
return 0
if csr_find_at(ptr, edges, terms[0], want[0]) is not NULL:
owner_a = terms[0]
owner_b = terms[1]
else:
owner_a = terms[1]
owner_b = terms[0]
elif kind == SU_PLANAR:
owner_a = anchor
owner_b = anchor
else:
owner_a = anchor
owner_b = stereo_unit_partner(structure, u)
if owner_b == SU_NO_REF:
_pach_loss(mol, strict, 'pach:stereo-lost',
'the stereo unit anchored at atom %d names two atoms and the second is not '
'in this molecule; pass drop=[\'stereo\'] to write the record without it'
% atoms[anchor].n,
'the stereo unit anchored at atom %d names a second atom this molecule does '
'not hold, so it was not written' % atoms[anchor].n)
return 0
_p3_put_u16(out, owner_a)
_p3_put_u16(out + 2, want[0])
_p3_put_u16(out + 4, owner_b)
_p3_put_u16(out + 6, want[2])
smi_perm_of(u, want, perm)
out[8] = <unsigned char> (kind | ((translate_parity(parity, perm) - 1) << 3))
return 1
cdef int _pach3_stereo_block(MoleculeContainer mol, Structure structure, unsigned char *out,
uint32_t *count, bint strict) except -1:
"""Every configured unit as a nine-byte record, into room for `unit_count` of them.
Called only when `stereo` was not dropped, so a unit this format cannot state is logged here and
skipped -- `drop=['stereo']` is the caller saying so in advance, and `strict=True` the caller who
wants the refusal. The table holds unconfigured units too, which is why the header's count is what
was WRITTEN. One unit per anchor, so that count cannot exceed the atom count and the header's u16
field cannot fill.
"""
cdef stereo_unit_t *units = structure_stereo_units(structure)
cdef stereo_unit_t *u
cdef uint32_t total = structure_stereo_unit_count(structure)
cdef uint32_t i
cdef uint32_t written = 0
for i in range(total):
u = units + i
written += <uint32_t> _pach3_stereo_record(mol, structure, u,
structure_parity_at(structure, u.anchor),
out + written * PACH3_STEREO_LEN, strict)
count[0] = written
return 0
cdef bytes _pach3_encode(MoleculeContainer mol, uint32_t drop_mask, bint strict):
"""One version 3 or version 4 pach record, uncompressed.
Version 3 when the molecule has coordinates and `coordinates` was not dropped, else version 4.
ATOM ORDER IS ARENA SLOT ORDER and stable ids are not written: bonds and stereo slots address
positions in the atom block, so a reader reproduces the order by reading it, and the record has no
12-bit id ceiling to run into.
"""
cdef Structure structure = mol._structure
cdef atom_t *atoms
cdef uint32_t *ptr
cdef halfedge_t *edges
cdef halfedge_t *rev
cdef xy_t *xy
cdef uint8_t *groups
cdef stereo_unit_t *u
cdef uint32_t oa = 0, ob = 0
cdef uint32_t n, nb, i, j, k, a1, a2
cdef uint32_t unit_count, stereo_count, sgroup_count, bgroup_count
cdef uint8_t sg_value
cdef bint want_xy
cdef bint want_map
cdef bint drop_wedges
cdef unsigned char wedge
cdef uint32_t wedged
cdef Py_ssize_t alloc, at
cdef unsigned char *buf
cdef bytes out
mol._require_clean()
_pach3_report_losses(mol, drop_mask, strict)
# DERIVED and unmarked, and it can reallocate, so every pointer below is taken after it. The
# decoder asks the same question, and the two directions have to ask the same one or a stored
# configuration means two things.
ensure_stereo_units_unmarked(structure)
structure = mol._structure
atoms = structure.atoms()
ptr = csr_ptr(structure)
edges = csr_edges(structure)
n = structure.header.atom_count
nb = structure.header.bond_count
if n > 65535:
raise ValueError('this molecule has %d atoms and the pach atom count is a 16 bit field; use '
'to_bytes(), which is lossless' % n)
if nb > 65535:
raise ValueError('this molecule has %d bonds and the pach bond count is a 16 bit field; use '
'to_bytes(), which is lossless' % nb)
want_xy = structure_has(structure, SEG_XY) and not (drop_mask & PACH_DROP_COORDINATES)
xy = NULL
if want_xy:
xy = structure_xy(structure)
# THE RANGE IS ASKED BEFORE THE VERSION BYTE IS CHOSEN, not inside the atom loop: a drawing
# outside +/-838.8607 costs the record its coordinates, which makes it a version 4 record, and
# that is a decision the header has to be able to state. One sentence names the first atom past
# the field and the repair, because the whole plane moves together.
for i in range(n):
if xy[i].x < -PACH3_XY_LIMIT or xy[i].x > PACH3_XY_LIMIT \
or xy[i].y < -PACH3_XY_LIMIT or xy[i].y > PACH3_XY_LIMIT:
_pach_loss(mol, strict, 'pach:coordinates-lost',
'atom %d sits at (%r, %r) and the pach coordinate field reaches '
'+/-838.8607; pass drop=[\'coordinates\'] to write the record without a '
'drawing' % (atoms[i].n, xy_read_x(&xy[i]), xy_read_y(&xy[i])),
'atom %d sits at (%r, %r) and the pach coordinate field reaches '
'+/-838.8607, so the record was written without a drawing; recenter2d() '
'moves a far-away plane onto the origin and clean2d(force=True) replaces it'
% (atoms[i].n, xy_read_x(&xy[i]), xy_read_y(&xy[i])))
want_xy = False
xy = NULL
break
unit_count = 0
if not (drop_mask & PACH_DROP_STEREO):
unit_count = structure_stereo_unit_count(structure)
# EITHER NAME DROPS BOTH BLOCKS. `drop=['stereo']` drops them along with the configurations, a
# caller asking for a record without stereo meaning without stereo; `drop=['stereo_groups']` drops
# them alone and is the name the version 0 and 2 writers' own refusal tells a caller to pass.
# `drop=['sgroups']` is a different field -- `_pach3_refuse_losses` asks about the CTfile S-group
# records, which have no block here at all.
# THE SPLIT IS BY OWNER COUNT, not by where the byte is stored -- every group byte is at a unit's
# anchor slot. A one-owner unit's group is an atom entry; an axis's is a bond entry keyed on the
# two atoms the axis is NAMED on, which for an allene are the chain terminals rather than the
# midpoint the byte sits at, and which need not be bonded (hexa-2,3,4-triene's are three bonds
# apart).
groups = NULL
sgroup_count = 0
bgroup_count = 0
if structure_has(structure, SEG_STEREO_GROUPS) \
and not (drop_mask & (PACH_DROP_STEREO | PACH_DROP_STEREO_GROUPS)):
groups = structure_stereo_groups(structure)
for i in range(n):
if not groups[i]:
continue
u = stereo_unit_of(structure, i)
if u is not NULL and stereo_unit_owners(atoms, ptr, edges, u, &oa, &ob) == 2:
bgroup_count += 1
else:
sgroup_count += 1
want_map = False
if not (drop_mask & PACH_DROP_MAP_NUMBER):
for i in range(n):
if atoms[i].map_number:
want_map = True
break
# ONE ALLOCATION, at the stereo block's upper bound: the table holds unconfigured units, so how
# many records there are is known only once they are written. The stereo block is written in
# place at its own offset and the record is the prefix `buf[:at]`, which is what a scratch buffer
# and a memcpy would otherwise be for.
alloc = _pach3_size(n, nb, unit_count, sgroup_count, bgroup_count, want_xy, want_map)
buf = <unsigned char *> PyMem_Malloc(alloc)
if buf is NULL:
raise MemoryError('pach record allocation failed')
try:
memset(buf, 0, alloc)
buf[0] = PACH3_VERSION_XY if want_xy else PACH3_VERSION_FLAT
buf[1] = (PACH3_FLAG_MAP if want_map else 0) | (PACH3_FLAG_BGROUP if bgroup_count else 0)
_p3_put_u16(buf + 2, n)
_p3_put_u16(buf + 4, nb)
_p3_put_u16(buf + 8, sgroup_count)
_p3_put_u16(buf + 10, bgroup_count)
at = PACH3_HEADER_LEN
for i in range(n):
_pach3_put_atom(&atoms[i], buf + at)
if want_xy:
# In range by construction: `want_xy` is only still set because the pre-pass above
# checked every atom against `PACH3_XY_LIMIT`.
_p3_put_i24(buf + at + 3, xy[i].x)
_p3_put_i24(buf + at + 6, xy[i].y)
at += PACH3_ATOM_XY_LEN if want_xy else PACH3_ATOM_FLAT_LEN
drop_wedges = (drop_mask & PACH_DROP_WEDGES) != 0 or not want_xy
# A version 4 record has a wedge nibble and no drawing for it to mean anything against, so the
# nibble is written 0 and the loss is on the molecule's log rather than raised: dropping the
# coordinates is what the caller asked for and the wedge went with them.
wedged = 0
if not want_xy and not (drop_mask & PACH_DROP_WEDGES):
for k in range(2 * nb):
if edges[k].wedge:
wedged += 1
if wedged:
mol._log_event('pach:wedge-lost', 'pach',
'version 4 carries no coordinates, so %d wedge(s) were not written'
% wedged, mc_lost())
for i in range(n):
for k in range(ptr[i], ptr[i + 1]):
j = edges[k].to
if j < i:
continue # the other half-edge wrote this bond
a1 = i
a2 = j
wedge = 0
if not drop_wedges:
wedge = edges[k].wedge
if wedge == 0:
# the wedge's narrow end is j, and the pair is written narrow end first
rev = csr_find_at(ptr, edges, j, i)
if rev is not NULL and rev.wedge:
a1 = j
a2 = i
wedge = rev.wedge
_p3_put_u16(buf + at, a1)
_p3_put_u16(buf + at + 2, a2)
buf[at + 4] = <unsigned char> (edges[k].order | (wedge << 4))
at += PACH3_BOND_LEN
stereo_count = 0
if unit_count:
_pach3_stereo_block(mol, structure, buf + at, &stereo_count, strict)
_p3_put_u16(buf + 6, stereo_count)
at += <Py_ssize_t> stereo_count * PACH3_STEREO_LEN
# ATOM ENHANCED STEREO, three bytes an entry and only for an atom that carries one: `atom u16`
# and the arena's own packed group byte, kind in bits 7-6 and group in bits 5-0. Its own
# block rather than a field in a stereo record because `set_stereo_group` accepts ANY atom,
# so an atom owning no unit has no record to hold it.
if sgroup_count:
for i in range(n):
sg_value = groups[i]
if not sg_value:
continue
u = stereo_unit_of(structure, i)
if u is not NULL and stereo_unit_owners(atoms, ptr, edges, u, &oa, &ob) == 2:
continue
_p3_put_u16(buf + at, i)
buf[at + 2] = sg_value
at += PACH3_SGROUP_LEN
# BOND ENHANCED STEREO, five bytes an entry: the axis's owner pair and the sg_pack byte. In
# ANCHOR order, which is the order a decode writes the bytes back in, so a decode and re-encode
# is byte-identical. Owner order would not be well defined against it: an atropisomer axis
# anchored at its higher pivot can precede an axis whose owners are numerically smaller.
if bgroup_count:
# THE MEMORY-SAFE HALF ONLY. The allocation above is the stereo block's upper bound, so a
# molecule holding an unconfigured unit has slack this check passes through: `O=C=O` with a
# short `_pach3_size` raises here, `CC` carries two unconfigured units and 18 bytes of slack
# and writes a record whose declared length is wrong instead -- which is what
# `test_bgroup_record_length_agrees_with_the_true_length` compares.
if at + <Py_ssize_t> bgroup_count * PACH3_BGROUP_LEN > alloc:
raise ValueError('the pach bond-group write loop would exceed the allocated buffer '
'(%d bytes at offset %d, %d bytes allocated); `_pach3_size` and '
'this loop disagree'
% (<Py_ssize_t> bgroup_count * PACH3_BGROUP_LEN, at, alloc))
for i in range(n):
if not groups[i]:
continue
u = stereo_unit_of(structure, i)
if u is NULL or stereo_unit_owners(atoms, ptr, edges, u, &oa, &ob) != 2:
continue
_p3_put_u16(buf + at, oa)
_p3_put_u16(buf + at + 2, ob)
buf[at + 4] = groups[i]
at += PACH3_BGROUP_LEN
if want_map:
for i in range(n):
_p3_put_u16(buf + at, atoms[i].map_number)
at += PACH3_MAP_LEN
# `at` and not `alloc`: the record ends where the last block ended, and an unconfigured unit
# left room the header does not declare. `pach_record_length` reads the counts, so the two
# have to agree -- `test_the_declared_length_is_the_buffer_length` is where they are compared.
out = <bytes> buf[:at]
finally:
PyMem_Free(buf)
return out
cdef struct pach3_atom_t:
uint8_t element # 0 for an R marker
uint8_t r_index
int8_t charge
uint8_t radical
uint8_t pinned
uint8_t hydrogens # the arena's own nibble, H_UNKNOWN included
uint16_t isotope # absolute mass number, 0 for unset
int32_t x
int32_t y
cdef MoleculeContainer _pach3_build(pach3_atom_t *pa, uint32_t atoms_count, edge_edit_t *edits,
uint32_t bonds_count, bint want_xy, bint want_parity,
const uint8_t *groups, const uint16_t *maps):
"""Lay out the arena and wrap it in a container.
STABLE IDS ARE NOT STORED, so the numbers are 1..n in record order. `pack()` renumbers and the
arena's `n` is a container's private label; that is what removes the 12-bit id ceiling rather than
widening a field. `rebuild_derived` REALLOCATES, which is why nothing here reads `atoms` after
it -- the numbers come from the loop index, not from the buffer (ruling F60).
`want_parity` is the header's DECLARED stereo count, not the number of configurations that turn out
to resolve: the caller has the header before it has the graph a record resolves against, and the
price of asking the earlier question is one byte per atom on a record whose every configuration is
then dropped.
`groups` is one packed group byte per atom in atom order, or NULL when the record asks for no group
segment at all -- the enhanced-stereo block names an atom rather than a unit, so the caller resolves
it against the atom block alone and hands the finished row over. An all-zero row is a record whose
only entries are bond-group ones, which resolve to their anchors after the seal and write into this
same segment.
`maps` is a map number per atom in atom order, or NULL when all atoms are unmapped -- written
beside `atoms[i].n` as a persistent field no derived segment reads.
"""
cdef Structure structure
cdef atom_t *atoms
cdef pach3_atom_t *src
cdef atom_t *dst
cdef xy_t *xy
cdef xy_t *xyp
cdef uint32_t i, seg_mask = 0
cdef int rc
cdef list numbers = []
cdef dict index_of = {}
cdef MoleculeContainer mol
if want_xy:
seg_mask = SEG_MASK_XY
if want_parity:
# `_pach3_apply_stereo` runs after this function seals the arena, so the segment it writes into
# is named here or nowhere (the persistent block is laid out once).
seg_mask |= SEG_MASK_PARITY
if groups is not NULL:
seg_mask |= SEG_MASK_STEREO
structure = structure_alloc_full(atoms_count, bonds_count, False, seg_mask, NULL)
atoms = structure.atoms()
for i in range(atoms_count):
src = pa + i
dst = atoms + i
dst.element = src.element
dst.charge = src.charge
dst.isotope = src.isotope
dst.n = i + 1
if maps is not NULL:
dst.map_number = maps[i]
# the explicit nibble is derived and `rebuild_derived` fills it from the CSR
at_set_h(dst, src.hydrogens, 0)
if src.element == 0:
at_set_r_index(dst, src.r_index)
if src.radical:
at_set_radical(dst, True)
if src.pinned:
at_set_h_pinned(dst, True)
with nogil:
rc = csr_build(structure, edits, bonds_count)
if rc:
raise MemoryError('csr scratch allocation failed')
if want_xy:
xy = structure_xy(structure)
for i in range(atoms_count):
src = pa + i
xyp = xy + i
xyp.x = src.x
xyp.y = src.y
if groups is not NULL:
# `sg_len` is `align8(atom_count)`, so one byte an atom is inside the segment
memcpy(structure_stereo_groups(structure), groups, atoms_count)
rebuild_derived(structure)
for i in range(atoms_count):
numbers.append(i + 1)
index_of[i + 1] = i
mol = MoleculeContainer.__new__(MoleculeContainer)
mol._structure = structure
mol._numbers = numbers
mol._index_of = index_of
mol._next_id = atoms_count + 1
mol._first_pending = atoms_count + 1
return mol
cdef inline bint _pach3_seen(edge_edit_t *edits, uint32_t count, uint32_t a1,
uint32_t a2) noexcept nogil:
"""Whether this pair is already in the kept-bond array. Linear, and deliberately so: a duplicate
is a damage report and the array is the record's own bond count."""
cdef uint32_t k
cdef edge_edit_t *e
for k in range(count):
e = edits + k
if (e.src == a1 and e.dst == a2) or (e.src == a2 and e.dst == a1):
return True
return False
cdef int _pach3_apply_wedges(MoleculeContainer mol, edge_edit_t *edits, uint8_t *wedges,
uint32_t count) except -1:
"""Each record's wedge onto the half-edge LEAVING its `a1`, which is the narrow end.
After the build, not before: `csr_build` clears both halves' wedge, and `rebuild_derived`
reallocates the persistent buffer, so the pointers have to be taken here.
"""
cdef Structure structure = mol._structure
cdef uint32_t *ptr = csr_ptr(structure)
cdef halfedge_t *edges = csr_edges(structure)
cdef halfedge_t *he
cdef edge_edit_t *e
cdef uint32_t k
for k in range(count):
if not wedges[k]:
continue
e = edits + k
he = csr_find_at(ptr, edges, e.src, e.dst)
if he is not NULL:
he.wedge = wedges[k]
return 0
# THE PERMUTATION IS BUILT FROM refs INDICES AND NEVER FROM DIRECTION VALUES, which is the one place
# the decoder does not mirror the writer's spelling. `_pach3_unit_frame` hands `smi_perm_of` a frame
# whose direction lists are still in `refs` order, and there its in-order pairing of the anonymous
# `SU_NO_REF` positions is exact. A record read from its FAR owner (the fallback below) presents the
# two lists swapped, and then the two anonymous positions swap with them -- so pairing them in order
# adds a transposition and inverts the parity of every unit whose both lists carry an unnamed
# direction, which is every `C/C=C/C`. An index is not anonymous, so this asks the question that has
# one answer: which `refs` slot is the record's i-th direction.
cdef inline bint _p3_pair_index(stereo_unit_t *u, uint32_t base, uint32_t named,
uint32_t *index) noexcept nogil:
"""The `refs` index at which the list `refs[base:base+2]` holds `named`.
False when the list does not hold `named` at all, which is a record disagreeing with the graph it
was decoded into. The list's other index is `2 * base + 1 - index[0]`, so naming one names both.
The two entries are hoisted rather than addressed because `refs` lives in a packed struct
(RULES.md 2.3).
"""
cdef uint32_t r0 = u.refs[base]
cdef uint32_t r1 = u.refs[base + 1]
if r0 == named:
index[0] = base
return True
if r1 == named:
index[0] = base + 1
return True
return False
cdef inline bint _p3_tetra_indices(stereo_unit_t *u, const uint32_t *named3,
uint32_t *perm) noexcept nogil:
"""`perm[0:3]` the `refs` index of each direction the record names, `perm[3]` the one left over.
False when the three the record names are not three of the unit's four. `used` is a match mask, so
a name is consumed by one slot only -- an unnamed direction is `SU_NO_REF` in `refs` and the record
never states one, but the mask is what keeps that a property of the loop rather than of the input.
The four entries are hoisted rather than addressed because `refs` lives in a packed struct
(RULES.md 2.3), and the inner loop reads all four of them.
"""
cdef uint32_t j, k
cdef uint32_t used = 0
cdef bint found
cdef uint32_t refs[4]
for j in range(4):
refs[j] = u.refs[j]
perm[0] = 0; perm[1] = 0; perm[2] = 0; perm[3] = 0
for k in range(3):
found = False
for j in range(4):
if refs[j] == named3[k] and not (used & (1u << j)):
perm[k] = j
used |= 1u << j
found = True
break
if not found:
return False
for j in range(4):
if not (used & (1u << j)):
perm[3] = j
return True
return False
cdef inline stereo_unit_t *_p3_allene_unit(Structure structure, uint32_t a, uint32_t b,
uint32_t *base_a) noexcept nogil:
"""The allene unit holding `a` in one direction list and `b` in the other, with which list is `a`'s.
An allene's anchor is the chain CENTRE, which the record does not store, so this is the one kind
looked up by refs membership rather than by anchor. The chain is not walked either way.
The four entries are hoisted rather than addressed because `refs` lives in a packed struct
(RULES.md 2.3), and each candidate unit reads all four of them twice.
"""
cdef stereo_unit_t *units = structure_stereo_units(structure)
cdef stereo_unit_t *u
cdef uint32_t total = structure_stereo_unit_count(structure)
cdef uint32_t i, r0, r1, r2, r3
for i in range(total):
u = units + i
if u.kind != SU_ALLENE:
continue
r0 = u.refs[0]
r1 = u.refs[1]
r2 = u.refs[2]
r3 = u.refs[3]
if (r0 == a or r1 == a) and (r2 == b or r3 == b):
base_a[0] = 0
return u
if (r2 == a or r3 == a) and (r0 == b or r1 == b):
base_a[0] = 2
return u
return NULL
cdef int _pach3_apply_stereo(MoleculeContainer mol, const unsigned char *data, Py_ssize_t at,
uint32_t count, uint32_t n, list problems) except -1:
"""The stereo block onto a built molecule: one configuration per nine bytes, each dropped alone.
`_pach3_stereo_record` inverted. The unit is found by IDENTITY and never by walking a chain -- by
anchor for a centre, by anchor at either owner slot for the two axis kinds, by refs membership for
an allene, whose anchor is the chain centre and is not stored. The record's direction frame is then
rebuilt as a permutation of that unit's `refs` -- `_pach3_unit_frame` is the writer's half and the
two are read together -- and `translate_parity` runs back. It is an XOR by the permutation's
parity, so the writer's call and this one are the same call and the pair is a fixed point rather
than a near miss.
A record that does not resolve costs its own configuration and nothing else -- a loop over a
million stored records must not stop at one of them.
"""
cdef Structure structure
cdef atom_t *atoms
cdef uint32_t *ptr
cdef halfedge_t *edges
cdef stereo_unit_t *u
cdef uint32_t k, slot0, slot1, slot2, slot3, kind, sign, reserved, base_a, base_b
cdef uint32_t named[3]
cdef uint32_t perm[4]
cdef bint wrote = False
cdef object err
if count == 0:
return 0
structure = mol._structure
# DERIVING THE UNIT TABLE CAN FAIL and must not become this function's exception: the core refuses
# a graph in which two units claim one anchor, and a damaged record can decode to such a graph.
try:
ensure_stereo_units_unmarked(structure)
except Exception as err:
problems.append('this record\'s graph has no usable stereo unit table (%s), so the %d '
'configuration(s) it states were dropped' % (err, count))
return 0
atoms = structure.atoms() # after, not before: the ensure may reallocate
ptr = csr_ptr(structure)
edges = csr_edges(structure)
for k in range(count):
slot0 = _p3_u16(data + at)
slot1 = _p3_u16(data + at + 2)
slot2 = _p3_u16(data + at + 4)
slot3 = _p3_u16(data + at + 6)
kind = data[at + 8] & 0x07
sign = (data[at + 8] >> 3) & 1
reserved = data[at + 8] >> 4
at += PACH3_STEREO_LEN
if reserved:
problems.append('stereo record %d byte 8 bits 4-7 are reserved and must be 0; %d is '
'ignored' % (k, reserved))
if slot0 >= n or slot1 >= n or slot2 >= n or slot3 >= n:
problems.append('stereo record %d names atom index %d and this record has %d atom(s); the '
'configuration was dropped'
% (k, max(max(slot0, slot1), max(slot2, slot3)), n))
continue
if kind > SU_PLANAR:
problems.append('stereo record %d states kind %d and pach has six, 0 tetrahedral, 1 '
'cis/trans, 2 allene, 3 atropisomer, 4 helical and 5 planar; the '
'configuration was dropped' % (k, kind))
continue
base_a = 0
if kind == SU_TETRA:
u = stereo_unit_of(structure, slot0)
if u is not NULL and u.kind != SU_TETRA:
u = NULL
elif kind == SU_ALLENE:
u = _p3_allene_unit(structure, slot1, slot3, &base_a)
# Slot0 and slot2 are the terminals, which the refs search did not read, so they are an
# adjacency cross-check: one CSR lookup per end and no chain walk.
if u is not NULL and (csr_find_at(ptr, edges, slot0, slot1) is NULL
or csr_find_at(ptr, edges, slot2, slot3) is NULL):
u = NULL
elif kind == SU_PLANAR:
u = stereo_unit_of(structure, slot0)
if u is not NULL and (u.kind != SU_PLANAR or slot2 != slot0):
u = NULL
else:
# Ruling F45 relocates an axis' anchor to the other pivot, so the unit is looked for at
# BOTH ends and the record stays readable either way round. When it is the far owner that
# anchors, `refs[0:2]` is slot2's list and slot1's is `refs[2:4]`.
u = stereo_unit_of(structure, slot0)
if u is NULL or u.kind != kind or stereo_unit_partner(structure, u) != slot2:
u = stereo_unit_of(structure, slot2)
base_a = 2
if u is NULL or u.kind != kind or stereo_unit_partner(structure, u) != slot0:
u = NULL
if u is NULL:
if kind == SU_TETRA:
problems.append('stereo record %d states a tetrahedral centre at atom %d, which '
'anchors no stereo unit of that kind in this molecule; the '
'configuration was dropped' % (k, atoms[slot0].n))
else:
problems.append('stereo record %d states %s over atoms %d and %d, which anchor no '
'stereo unit of that kind in this molecule; the configuration was '
'dropped'
% (k, smi_kind_name(<uint8_t> kind), atoms[slot0].n, atoms[slot2].n))
continue
if u.n_refs != 4:
# The encoder's twin, and unreachable for the same reason: `_stereo.pxi`'s "WHY N==4 IS THE
# ONLY CASE" states that every perception emit site passes `n_refs=4`. A decode path must
# not assume an invariant another file maintains over a table rebuilt from a forged
# record's own graph, so the guard stays and reports rather than raising.
problems.append('stereo record %d resolves to a unit ordering %d reference direction(s) '
'and a parity is a fact about four; the configuration was dropped'
% (k, u.n_refs))
continue
if structure_parity_at(structure, u.anchor):
problems.append('stereo record %d resolves to the unit anchored at atom %d, which an '
'earlier record already configured; the later one was dropped'
% (k, atoms[u.anchor].n))
continue
# THE RECORD'S FRAME, as a permutation of `refs`: slot1 and slot3 are the named directions and
# the implied ones are whichever slots those leave.
if kind == SU_TETRA:
named[0] = slot1
named[1] = slot2
named[2] = slot3
if not _p3_tetra_indices(u, named, perm):
problems.append('stereo record %d names three directions of the centre at atom %d and '
'at least one is not one of its four; the configuration was dropped'
% (k, atoms[slot0].n))
continue
else:
base_b = 2 - base_a
if not _p3_pair_index(u, base_a, slot1, &perm[0]) \
or not _p3_pair_index(u, base_b, slot3, &perm[2]):
problems.append('stereo record %d names directions %d and %d, which are not the ones '
'the unit over atoms %d and %d orders; the configuration was dropped'
% (k, atoms[slot1].n, atoms[slot3].n, atoms[slot0].n, atoms[slot2].n))
continue
perm[1] = 2 * base_a + 1 - perm[0]
perm[3] = 2 * base_b + 1 - perm[2]
structure_set_parity(structure, u.anchor, translate_parity(<uint8_t> (sign + 1), perm))
wrote = True
if wrote:
refresh_parity_features(structure)