forked from biopython/biopython
/
internal_coords.py
3479 lines (2993 loc) · 127 KB
/
internal_coords.py
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 2019 by Robert T. Miller. All rights reserved.
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Classes to support internal coordinates for protein structures.
Internal coordinates comprise Psi, Phi and Omega dihedral angles along the
protein backbone, Chi angles along the sidechains, and all 3-atom angles and
bond lengths comprising a protein chain. These routines can compute internal
coordinates from atom XYZ coordinates, and compute atom XYZ coordinates from
internal coordinates.
Internal coordinates are defined on sequences of atoms which span
residues or follow accepted nomenclature along sidechains. To manage these
sequences and support Biopython's disorder mechanisms, AtomKey specifiers are
implemented to capture residue, atom and variant identification in a single
object. A Hedron object is specified as three sequential AtomKeys, comprising
two bond lengths and the bond angle between them. A Dihedron consists of four
sequential AtomKeys, linking two Hedra with a dihedral angle between them.
A Protein Internal Coordinate (.pic) file format is defined to capture
sufficient detail to reproduce a PDB file from chain starting coordinates
(first residue N, Ca, C XYZ coordinates) and remaining internal coordinates.
These files are used internally to verify that a given structure can be
regenerated from its internal coordinates.
Internal coordinates may also be exported as OpenSCAD data arrays for
generating 3D printed protein models. OpenSCAD software is provided as
proof-of-concept for generating such models.
The following classes comprise the core functionality for processing internal
coordinates and are sufficiently related and coupled to place them together in
this module:
IC_Chain: Extends Biopython Chain on .internal_coord attribute.
Manages connected sequence of residues and chain breaks; methods generally
apply IC_Residue methods along chain.
IC_Residue: Extends for Biopython Residue on .internal_coord attribute.
Most control and methods of interest are in this class, see API.
Dihedron: four joined atoms forming a dihedral angle.
Dihedral angle, homogeneous atom coordinates in local coordinate space,
references to relevant Hedra and IC_Residue. Methods to compute
residue dihedral angles, bond angles and bond lengths.
Hedron: three joined atoms forming a plane.
Contains homogeneous atom coordinates in local coordinate space as well as
bond lengths and angle between them.
Edron: base class for Hedron and Dihedron classes.
Tuple of AtomKeys comprising child, string ID, mainchain membership boolean
and other routines common for both Hedra and Dihedra. Implements rich
comparison.
AtomKey: keys (dictionary and string) for referencing atom sequences.
Capture residue and disorder/occupancy information, provides a
no-whitespace key for .pic files, and implements rich comparison.
Custom exception classes: HedronMatchError and MissingAtomError
"""
import re
from collections import deque, namedtuple
try:
import numpy # type: ignore
except ImportError:
from Bio import MissingPythonDependencyError
raise MissingPythonDependencyError(
"Install NumPy to build proteins from internal coordinates."
)
from Bio.PDB.Atom import Atom, DisorderedAtom
from Bio.PDB.Polypeptide import three_to_one
from Bio.PDB.vectors import coord_space, multi_rot_Z, multi_rot_Y
# , calc_dihedral, Vector
from Bio.PDB.ic_data import ic_data_backbone, ic_data_sidechains
from Bio.PDB.ic_data import ic_data_sidechain_extras, residue_atom_bond_state
# for type checking only
from typing import List, Dict, Set, TextIO, Union, Tuple, cast, TYPE_CHECKING, Optional
if TYPE_CHECKING:
from Bio.PDB.Residue import Residue
from Bio.PDB.Chain import Chain
HKT = Tuple["AtomKey", "AtomKey", "AtomKey"] # Hedron key tuple
DKT = Tuple["AtomKey", "AtomKey", "AtomKey", "AtomKey"] # Dihedron Key Tuple
EKT = Union[HKT, DKT] # Edron Key Tuple
BKT = Tuple["AtomKey", "AtomKey"] # Bond Key Tuple
# HACS = Tuple[numpy.array, numpy.array, numpy.array] # Hedron Atom Coord Set
HACS = numpy.array # Hedron Atom Coord Set
DACS = Tuple[
numpy.array, numpy.array, numpy.array, numpy.array
] # Dihedron Atom Coord Set
class IC_Chain:
"""Class to extend Biopython Chain with internal coordinate data.
Attributes
----------
chain: biopython Chain object reference
The Chain object this extends
initNCaC: AtomKey indexed dictionary of N, Ca, C atom coordinates.
NCaCKeys start chain segments (first residue or after chain break).
These 3 atoms define the coordinate space for a contiguous chain segment,
as initially specified by PDB or mmCIF file.
MaxPeptideBond: **Class** attribute to detect chain breaks.
Override for fully contiguous chains with some very long bonds - e.g.
for 3D printing (OpenSCAD output) a structure with fully disordered
(missing) residues.
ordered_aa_ic_list: list of IC_Residue objects
IC_Residue objects ic algorithms can process (e.g. no waters)
hedra: dict indexed by 3-tuples of AtomKeys
Hedra forming residues in this chain
hedraLen: int length of hedra dict
hedraNdx: dict mapping hedra AtomKeys to numpy array data
dihedra: dict indexed by 4-tuples of AtomKeys
Dihedra forming (overlapping) this residue
dihedraLen: int length of dihedra dict
dihedraNdx: dict mapping dihedra AtomKeys to numpy array data
atomArray: numpy array of homogeneous atom coords for chain
atomArrayIndex: dict mapping AtomKeys to atomArray indexes
numpy arrays for vector processing of chain di/hedra:
hedraIC: length-angle-length entries for each hedron
hAtoms: homogeneous atom coordinates (3x4) of hedra, central atom at origin
hAtomsR: hAtoms in reverse order
hAtoms_needs_update: booleans indicating whether hAtoms represent hedraIC
dihedraIC: dihedral angles for each dihedron
dAtoms: homogeneous atom coordinates (4x4) of dihedra, second atom at origin
dAtoms_needs_update: booleans indicating whether dAtoms represent dihedraIC
Methods
-------
internal_to_atom_coordinates(verbose, start, fin)
Process ic data to Residue/Atom coordinates; calls assemble_residues()
followed by coords_to_structure()
assemble_residues(verbose, start, fin)
Generate IC_Residue atom coords from internal coordinates
coords_to_structure()
update Biopython Residue.Atom coords from IC_Residue coords for all
Residues with IC_Residue attributes
atom_to_internal_coordinates(verbose)
Calculate dihedrals, angles, bond lengths (internal coordinates) for
Atom data
link_residues()
Call link_dihedra() on each IC_Residue (needs rprev, rnext set)
set_residues()
Add .internal_coord attribute for all Residues in parent Chain, populate
ordered_aa_ic_list, set IC_Residue rprev, rnext or initNCaC coordinates
write_SCAD()
Write OpenSCAD matrices for internal coordinate data comprising chain
"""
MaxPeptideBond = 1.4 # larger C-N distance than this is chain break
def __init__(self, parent: "Chain", verbose: bool = False) -> None:
"""Initialize IC_Chain object, with or without residue/Atom data.
:param parent: Biopython Chain object
Chain object this extends
"""
# type hinting parent as Chain leads to import cycle
self.chain = parent
self.ordered_aa_ic_list: List[IC_Residue] = []
self.initNCaC: Dict[Tuple[str], Dict["AtomKey", numpy.array]] = {}
self.sqMaxPeptideBond = IC_Chain.MaxPeptideBond * IC_Chain.MaxPeptideBond
# need init here for _gen_edra():
self.hedra = {}
# self.hedraNdx = {}
self.dihedra = {}
# self.dihedraNdx = {}
self.set_residues(verbose) # no effect if no residues loaded
# return True if a0, a1 within supplied cutoff
def _atm_dist_chk(self, a0: Atom, a1: Atom, cutoff: float, sqCutoff: float) -> bool:
diff = a0.coord - a1.coord
sum = 0
for axis in diff:
if axis > cutoff:
# print("axis: ", axis)
return False
sum += axis * axis
if sum > sqCutoff:
# print("sq axis: ", sqrt(sum)) # need import math.sqrt
return False
return True
# return a string describing issue, or None if OK
def _peptide_check(self, prev: "Residue", curr: "Residue") -> Optional[str]:
if 0 == len(curr.child_dict):
# curr residue with no atoms => reading pic file, no break
return None
if (0 != len(curr.child_dict)) and (0 == len(prev.child_dict)):
# prev residue with no atoms, curr has atoms => reading pic file,
# have break
return "PIC data missing atoms"
# handle non-standard AA not marked as HETATM (1KQF, 1NTH)
if not prev.internal_coord.is20AA:
return "previous residue not standard amino acid"
# both biopython Residues have Atoms, so check distance
Natom = curr.child_dict.get("N", None)
pCatom = prev.child_dict.get("C", None)
if Natom is None or pCatom is None:
return f"missing {'previous C' if pCatom is None else 'N'} atom"
# confirm previous residue has all backbone atoms
pCAatom = prev.child_dict.get("CA", None)
pNatom = prev.child_dict.get("N", None)
if pNatom is None or pCAatom is None:
return "previous residue missing N or Ca"
tooFar = f"MaxPeptideBond ({IC_Chain.MaxPeptideBond} angstroms) exceeded"
if not Natom.is_disordered() and not pCatom.is_disordered():
dc = self._atm_dist_chk(
Natom, pCatom, IC_Chain.MaxPeptideBond, self.sqMaxPeptideBond
)
if dc:
return None
else:
return tooFar
Nlist: List[Atom] = []
pClist: List[Atom] = []
if Natom.is_disordered():
Nlist.extend(Natom.child_dict.values())
else:
Nlist = [Natom]
if pCatom.is_disordered():
pClist.extend(pCatom.child_dict.values())
else:
pClist = [pCatom]
for n in Nlist:
for c in pClist:
if self._atm_dist_chk(
Natom, pCatom, IC_Chain.MaxPeptideBond, self.sqMaxPeptideBond
):
return None
return tooFar
def clear_ic(self):
"""Clear residue internal_coord settings for this chain."""
for res in self.chain.get_residues():
res.internal_coord = None
def _add_residue(
self, res: "Residue", last_res: List, last_ord_res: List, verbose: bool = False
) -> bool:
"""Set rprev, rnext, determine chain break."""
if not res.internal_coord:
res.internal_coord = IC_Residue(res)
res.internal_coord.cic = self
if (
0 < len(last_res)
and last_ord_res == last_res
and self._peptide_check(last_ord_res[0].residue, res) is None
):
# no chain break
for prev in last_ord_res:
prev.rnext.append(res.internal_coord)
res.internal_coord.rprev.append(prev)
return True
elif all(atm in res.child_dict for atm in ("N", "CA", "C")):
# chain break, save coords for restart
if verbose and len(last_res) != 0: # not first residue
if last_ord_res != last_res:
reason = "disordered residues after {last_ord_res.pretty_str()}"
else:
reason = cast(
str, self._peptide_check(last_ord_res[0].residue, res)
)
print(
f"chain break at {res.internal_coord.pretty_str()} due to {reason}"
)
initNCaC: Dict["AtomKey", numpy.array] = {}
ric = res.internal_coord
for atm in ("N", "CA", "C"):
bpAtm = res.child_dict[atm]
if bpAtm.is_disordered():
for altAtom in bpAtm.child_dict.values():
ak = AtomKey(ric, altAtom)
initNCaC[ak] = IC_Residue.atm241(altAtom.coord)
else:
ak = AtomKey(ric, bpAtm)
initNCaC[ak] = IC_Residue.atm241(bpAtm.coord)
self.initNCaC[ric.rbase] = initNCaC
return True
elif (
0 == len(res.child_list)
and self.chain.child_list[0].id == res.id
and res.internal_coord.is20AA
):
# this is first residue, no atoms at all, is std amino acid
# conclude reading pic file with no N-Ca-C coords
return True
# chain break but do not have N, Ca, C coords to restart from
return False
def set_residues(self, verbose: bool = False) -> None:
"""Initialize internal_coord data for loaded Residues.
Add IC_Residue as .internal_coord attribute for each Residue in parent
Chain; populate ordered_aa_ic_list with IC_Residue references for residues
which can be built (amino acids and some hetatms); set rprev and rnext
on each sequential IC_Residue, populate initNCaC at start and after
chain breaks.
"""
# ndx = 0
last_res: List["IC_Residue"] = []
last_ord_res: List["IC_Residue"] = []
for res in self.chain.get_residues():
# select only not hetero or accepted hetero
if res.id[0] == " " or res.id[0] in IC_Residue.accept_resnames:
this_res: List["IC_Residue"] = []
if 2 == res.is_disordered():
# print('disordered res:', res.is_disordered(), res)
for r in res.child_dict.values():
if self._add_residue(r, last_res, last_ord_res, verbose):
this_res.append(r.internal_coord)
else:
if self._add_residue(res, last_res, last_ord_res, verbose):
this_res.append(res.internal_coord)
if 0 < len(this_res):
self.ordered_aa_ic_list.extend(this_res)
last_ord_res = this_res
last_res = this_res
def link_residues(self) -> None:
"""link_dihedra() for each IC_Residue; needs rprev, rnext set.
Called by PICIO:read_PIC() after finished reading chain
"""
for ric in self.ordered_aa_ic_list:
ric.cic = self
ric.link_dihedra()
def assemble_residues(
self,
verbose: bool = False,
start: Optional[int] = None,
fin: Optional[int] = None,
) -> None:
"""Generate IC_Residue atom coords from internal coordinates.
Filter positions between start and fin if set, find appropriate start
coordinates for each residue and pass to IC_Residue.assemble()
:param verbose bool: default False
describe runtime problems
:param: start, fin lists
sequence position, insert code for begin, end of subregion to
process
"""
for ric in self.ordered_aa_ic_list:
ric.clear_transforms()
for ric in self.ordered_aa_ic_list:
if not hasattr(ric, "NCaCKey"):
if verbose:
print(
f"no assembly for {str(ric)} due to missing N, Ca and/or C atoms"
)
continue
respos = ric.residue.id[1]
if start and start > respos:
continue
if fin and fin < respos:
continue
ric.atom_coords = cast(
Dict[AtomKey, numpy.array], ric.assemble(verbose=verbose)
)
if ric.atom_coords:
ric.ak_set = set(ric.atom_coords.keys())
def coords_to_structure(self) -> None:
"""Promote all ic atom_coords to Biopython Residue/Atom coords.
IC atom_coords are homogeneous [4], Biopython atom coords are XYZ [3].
"""
self.ndx = 0
for res in self.chain.get_residues():
if 2 == res.is_disordered():
for r in res.child_dict.values():
if r.internal_coord:
if r.internal_coord.atom_coords:
r.internal_coord.coords_to_residue()
elif (
r.internal_coord.rprev
and r.internal_coord.rprev[0].atom_coords
):
r.internal_coord.rprev[0].coords_to_residue(rnext=True)
elif res.internal_coord:
if res.internal_coord.atom_coords:
res.internal_coord.coords_to_residue()
elif (
res.internal_coord.rprev and res.internal_coord.rprev[0].atom_coords
):
res.internal_coord.rprev[0].coords_to_residue(rnext=True)
def init_edra(self) -> None:
"""Create chain level di/hedra arrays.
If called by read_PIC, self.di/hedra = {} and object tree has IC data.
-> build chain arrays from IC data
If called at start of atom_to_internal_coords, self.di/hedra fully
populated. -> create empty chain numpy arrays
In both cases, fix di/hedra object attributes to be views on
chain-level array data
"""
# hedra:
if self.hedra == {}:
# loaded objects from PIC file, so no chain-level hedra
hLAL = {}
for ric in self.ordered_aa_ic_list:
for k, h in ric.hedra.items():
self.hedra[k] = h
hLAL[k] = h.lal
self.hedraLen = len(self.hedra)
self.hedraIC = numpy.array(tuple(hLAL.values()))
else:
# atom_to_internal_coords() populates self.hedra via _gen_edra()
# a_to_ic will set ic so create empty
self.hedraLen = len(self.hedra)
self.hedraIC = numpy.empty((self.hedraLen, 3), dtype=numpy.float64)
self.hedraNdx = dict(zip(self.hedra.keys(), range(len(self.hedra))))
self.hAtoms: numpy.ndarray = numpy.zeros(
(self.hedraLen, 3, 4), dtype=numpy.float64
)
self.hAtoms[:, :, 3] = 1.0 # homogeneous
self.hAtomsR: numpy.ndarray = numpy.copy(self.hAtoms)
self.hAtoms_needs_update = numpy.full(self.hedraLen, True)
for ric in self.ordered_aa_ic_list:
for k, h in ric.hedra.items():
# all h.lal become views on hedraIC
h.lal = self.hedraIC[self.hedraNdx[k]]
# dihedra:
if self.dihedra == {}:
# loaded objects from PIC file, so no chain-level hedra
dic = {}
for ric in self.ordered_aa_ic_list:
for k, d in ric.dihedra.items():
self.dihedra[k] = d
dic[k] = d.angle
self.dihedraIC = numpy.array(tuple(dic.values()))
self.dihedraICr = numpy.deg2rad(self.dihedraIC)
self.dihedraLen = len(self.dihedra)
else:
# atom_to_internal_coords() populates self.hedra via _gen_edra()
# a_to_ic will set ic so create empty
self.dihedraLen = len(self.dihedra)
self.dihedraIC = numpy.empty(self.dihedraLen)
self.dihedraICr = numpy.empty(self.dihedraLen)
self.dihedraNdx = dict(zip(self.dihedra.keys(), range(len(self.dihedra))))
self.dAtoms: numpy.ndarray = numpy.empty(
(self.dihedraLen, 4, 4), dtype=numpy.float64
)
self.dAtoms[:, :, 3] = 1.0 # homogeneous
self.a4_pre_rotation = numpy.empty((self.dihedraLen, 4))
for k, d in self.dihedra.items():
d.initial_coords = self.dAtoms[self.dihedraNdx[k]]
d.a4_pre_rotation = self.a4_pre_rotation[self.dihedraNdx[k]]
self.dAtoms_needs_update = numpy.full(self.dihedraLen, True)
self.dRev = numpy.array(tuple(d.reverse for d in self.dihedra.values()))
self.dFwd = self.dRev != True # noqa: E712
self.dH1ndx = numpy.array(
tuple(self.hedraNdx[d.h1key] for d in self.dihedra.values())
)
self.dH2ndx = numpy.array(
tuple(self.hedraNdx[d.h2key] for d in self.dihedra.values())
)
# @profile
def init_atom_coords(self) -> None:
"""Set chain level di/hedra initial coord arrays from IC_Residue data."""
if not numpy.all(self.dAtoms_needs_update):
self.dAtoms_needs_update |= (self.hAtoms_needs_update[self.dH1ndx]) | (
self.hAtoms_needs_update[self.dH2ndx]
)
if numpy.any(self.hAtoms_needs_update):
# hedra initial coords
# supplementary angle radian: angles which add to 180 are supplementary
sar = numpy.deg2rad(
180.0 - self.hedraIC[:, 1][self.hAtoms_needs_update]
) # angle
sinSar = numpy.sin(sar)
cosSarN = numpy.cos(sar) * -1
# a2 is len3 up from a2 on Z axis, X=Y=0
self.hAtoms[:, 2, 2][self.hAtoms_needs_update] = self.hedraIC[:, 2][
self.hAtoms_needs_update
]
# a0 X is sin( sar ) * len12
self.hAtoms[:, 0, 0][self.hAtoms_needs_update] = (
sinSar * self.hedraIC[:, 0][self.hAtoms_needs_update]
)
# a0 Z is -(cos( sar ) * len12)
# (assume angle always obtuse, so a0 is in -Z)
self.hAtoms[:, 0, 2][self.hAtoms_needs_update] = (
cosSarN * self.hedraIC[:, 0][self.hAtoms_needs_update]
)
# same again but 'reversed' : a0 on Z axis, a1 at origin, a2 in -Z
# a0r is len12 up from a1 on Z axis, X=Y=0
self.hAtomsR[:, 0, 2][self.hAtoms_needs_update] = self.hedraIC[:, 0][
self.hAtoms_needs_update
]
# a2r X is sin( sar ) * len23
self.hAtomsR[:, 2, 0][self.hAtoms_needs_update] = (
sinSar * self.hedraIC[:, 2][self.hAtoms_needs_update]
)
# a2r Z is -(cos( sar ) * len23)
self.hAtomsR[:, 2, 2][self.hAtoms_needs_update] = (
cosSarN * self.hedraIC[:, 2][self.hAtoms_needs_update]
)
self.hAtoms_needs_update[...] = False
# dihedra initial coords
dhlen = numpy.sum(self.dAtoms_needs_update) # self.dihedraLen
# full size masks:
mdFwd = self.dFwd & self.dAtoms_needs_update
mdRev = self.dRev & self.dAtoms_needs_update
# update size masks
udFwd = self.dFwd[self.dAtoms_needs_update]
udRev = self.dRev[self.dAtoms_needs_update]
# only 4th atom takes work:
# pick 4th atom based on rev flag
self.a4_pre_rotation[mdRev] = self.hAtoms[self.dH2ndx, 0][mdRev]
self.a4_pre_rotation[mdFwd] = self.hAtomsR[self.dH2ndx, 2][mdFwd]
# numpy multiply, add operations below intermediate array but out= not
# working with masking:
self.a4_pre_rotation[:, 2][self.dAtoms_needs_update] = numpy.multiply(
self.a4_pre_rotation[:, 2][self.dAtoms_needs_update], -1
) # a4 to +Z
a4shift = numpy.empty(dhlen)
a4shift[udRev] = self.hedraIC[self.dH2ndx, 2][mdRev] # len23
a4shift[udFwd] = self.hedraIC[self.dH2ndx, 0][mdFwd] # len12
self.a4_pre_rotation[:, 2][self.dAtoms_needs_update] = numpy.add(
self.a4_pre_rotation[:, 2][self.dAtoms_needs_update], a4shift
) # so a2 at origin
# build rz rotation matrix for dihedral angle
rz = multi_rot_Z(self.dihedraICr[self.dAtoms_needs_update])
# p = numpy.matmul(mt, dha[:, 0].reshape(-1, 4, 1)).reshape(-1, 4)
a4rot = numpy.matmul(
rz, self.a4_pre_rotation[self.dAtoms_needs_update][:].reshape(-1, 4, 1)
).reshape(-1, 4)
# a4rot = rz.dot(self.a4_pre_rotation) # numpy.matmul(self.a4_pre_rotation, rz)
# now build dihedra initial coords
dH1atoms = self.hAtoms[self.dH1ndx] # fancy indexing so
dH1atomsR = self.hAtomsR[self.dH1ndx] # these copy not view
self.dAtoms[:, :3][mdFwd] = dH1atoms[mdFwd]
self.dAtoms[:, 3][mdFwd] = a4rot[udFwd] # [self.dFwd]
self.dAtoms[:, :3][mdRev] = dH1atomsR[:, 2::-1][mdRev]
self.dAtoms[:, 3][mdRev] = a4rot[udRev] # [self.dRev]
self.dAtoms_needs_update[...] = False
def internal_to_atom_coordinates(
self,
verbose: bool = False,
start: Optional[int] = None,
fin: Optional[int] = None,
promote: Optional[bool] = True,
) -> None:
"""Process, IC data to Residue/Atom coords.
Not yet vectorized.
:param verbose bool: default False
describe runtime problems
:param: start, fin lists
sequence position, insert code for begin, end of subregion to
process
:param promote bool: default True
If True (the default) copy result atom XYZ coordinates to
Biopython Atom objects for access by other Biopython methods;
otherwise, updated atom coordinates must be accessed through
IC_Residue and hedron objects.
"""
if self.dihedra == {}:
return # escape if nothing to process
self.init_atom_coords()
self.assemble_residues(
verbose=verbose, start=start, fin=fin
) # internal to XYZ coordinates
if promote:
self.coords_to_structure() # promote to BioPython Residue/Atom
# @profile
def atom_to_internal_coordinates(self, verbose: bool = False) -> None:
"""Calculate dihedrals, angles, bond lengths for Atom data.
:param verbose bool: default False
describe runtime problems
"""
hedraAtomDict = {}
dihedraAtomDict = {}
hInDset = set()
hedraDict2 = {}
gCBdihedra = set()
for ric in self.ordered_aa_ic_list:
ric.atom_to_internal_coordinates(verbose=verbose) # builds di/hedra objects
self.init_edra()
for ric in self.ordered_aa_ic_list:
for k, d in ric.dihedra.items():
hInDset.update((d.h1key, d.h2key))
try:
# get tuple of atom_coords from ric dict
dihedraAtomDict[k] = d.gen_acs(ric.atom_coords)
except KeyError:
gCBdihedra.add(d) # no atom_coords yet for gly CB
# init to rough approximation, overwrite later
# dihedron = O-C-Ca-Cb
# h1 = Ca-C-O (reversed)
# h2 = Cb-Ca-C (reversed)
# need dihedron atom coords all forward
h1 = d.hedron1.gen_acs(ric.atom_coords)
h1 = numpy.flipud(h1) # reverse h1 coords for building dihedron
xgcb = numpy.append(h1, [h1[2]], axis=0)
xgcb[3, 0] = xgcb[3, 0] + 1.0
dihedraAtomDict[k] = xgcb
for k, h in ric.hedra.items():
if k not in hInDset:
# print("inaccessible hedron outside dihedron: ", h)
try:
hedraAtomDict[k] = h.gen_acs(ric.atom_coords)
except KeyError: # gly CB
hedraAtomDict[k] = numpy.array(
[[1, 2, 3, 1], [2, 2, 3, 1], [3, 2, 3, 1]]
)
if self.dihedra == {}:
return # escape if no hedra loaded for this chain
if hedraAtomDict != {}:
# some hedra not in dihedra to process
# issue from alternate CB path, triggered by residue sidechain path not
# including n-ca-cb-xg
# not needed to build chain but include for consistency / statistics
hedraDict2 = {k: h for k, h in self.hedra.items() if k not in hInDset}
lh2a = len(hedraDict2)
if lh2a > 0:
h2a = numpy.array(tuple(hedraAtomDict.values()))
h2ai = dict(zip(hedraDict2.keys(), range(lh2a)))
# get dad for hedra
h_a0a1 = numpy.linalg.norm(h2a[:, 0] - h2a[:, 1], axis=1)
h_a1a2 = numpy.linalg.norm(h2a[:, 1] - h2a[:, 2], axis=1)
h_a0a2 = numpy.linalg.norm(h2a[:, 0] - h2a[:, 2], axis=1)
h_a0a1a2 = numpy.rad2deg(
numpy.arccos(
((h_a0a1 * h_a0a1) + (h_a1a2 * h_a1a2) - (h_a0a2 * h_a0a2))
/ (2 * h_a0a1 * h_a1a2)
)
)
for k, h in hedraDict2.items():
hndx = h2ai[k]
h.lal[:] = (h_a0a1[hndx], h_a0a1a2[hndx], h_a1a2[hndx])
# now process dihedra
dLen = self.dihedraLen
dha = numpy.array(tuple(dihedraAtomDict.values()))
dhai = dict(zip(self.dihedra.keys(), range(dLen)))
# get dadad dist-angle-dist-angle-dist for dihedra
a0a1 = numpy.linalg.norm(dha[:, 0] - dha[:, 1], axis=1)
a1a2 = numpy.linalg.norm(dha[:, 1] - dha[:, 2], axis=1)
a2a3 = numpy.linalg.norm(dha[:, 2] - dha[:, 3], axis=1)
a0a2 = numpy.linalg.norm(dha[:, 0] - dha[:, 2], axis=1)
a1a3 = numpy.linalg.norm(dha[:, 1] - dha[:, 3], axis=1)
sqr_a1a2 = numpy.multiply(a1a2, a1a2)
a0a1a2 = numpy.rad2deg(
numpy.arccos(((a0a1 * a0a1) + sqr_a1a2 - (a0a2 * a0a2)) / (2 * a0a1 * a1a2))
)
a1a2a3 = numpy.rad2deg(
numpy.arccos((sqr_a1a2 + (a2a3 * a2a3) - (a1a3 * a1a3)) / (2 * a1a2 * a2a3))
)
# develop coord_space matrix for 1st 3 atoms of dihedra:
# build tm translation matrix: atom1 to origin
tm = numpy.empty((dLen, 4, 4))
tm[...] = numpy.identity(4)
tm[:, 0:3, 3] = -dha[:, 1, 0:3]
# directly translate a2 into new space using a1
p = dha[:, 2] - dha[:, 1]
# get spherical coords of translated a2 (p)
r = numpy.linalg.norm(p, axis=1)
azimuth = numpy.arctan2(p[:, 1], p[:, 0])
polar_angle = numpy.arccos(numpy.divide(p[:, 2], r, where=r != 0))
# build rz rotation matrix: translated a2 -azimuth around Z
# (enables next step rotating around Y to align with Z)
rz = multi_rot_Z(-azimuth)
# build ry rotation matrix: translated a2 -polar_angle around Y
ry = multi_rot_Y(-polar_angle)
# mt completes a1-a2 on Z-axis, still need to align a0 with XZ plane
mt = numpy.matmul(ry, numpy.matmul(rz, tm))
# transform a0 to mt space
p = numpy.matmul(mt, dha[:, 0].reshape(-1, 4, 1)).reshape(-1, 4)
# print("mt[0]:\n", mt[0], "\ndha[0][0] (a0):\n", dha[0][0], "\np[0]:\n", p[0])
# get azimuth of translated a0
azimuth2 = numpy.arctan2(p[:, 1], p[:, 0])
# build rotation matrix rz2 to rotate a0 -azimuth about Z to align with X
rz2 = multi_rot_Z(-azimuth2)
# update mt to be complete transform into hedron coordinate space
mt = numpy.matmul(rz2, mt[:])
# now put atom 4 into that coordinate space and read dihedral as azimuth
do4 = numpy.matmul(mt, dha[:, 3].reshape(-1, 4, 1)).reshape(-1, 4)
numpy.arctan2(do4[:, 1], do4[:, 0], out=self.dihedraICr)
numpy.rad2deg(self.dihedraICr, out=self.dihedraIC)
# build hedra arrays
hIC = self.hedraIC
hNdx = self.hedraNdx
for k, d in self.dihedra.items():
dndx = dhai[k]
# d.angle = dh1d[dndx]
rev, hed1, hed2 = (d.reverse, d.hedron1, d.hedron2)
h1ndx, h2ndx = (hNdx[d.h1key], hNdx[d.h2key])
if not rev:
hIC[h1ndx, :] = (a0a1[dndx], a0a1a2[dndx], a1a2[dndx])
hIC[h2ndx, :] = (a1a2[dndx], a1a2a3[dndx], a2a3[dndx])
# hed1.len12 = a0a1[dndx]
# hed1.len23 = hed2.len12 = a1a2[dndx]
# hed2.len23 = a2a3[dndx]
else:
hIC[h1ndx, :] = (a1a2[dndx], a0a1a2[dndx], a0a1[dndx])
hIC[h2ndx, :] = (a2a3[dndx], a1a2a3[dndx], a1a2[dndx])
# hed1.len23 = a0a1[dndx]
# hed1.len12 = hed2.len23 = a1a2[dndx]
# hed2.len12 = a2a3[dndx]
hed1.lal = hIC[h1ndx]
hed2.lal = hIC[h2ndx]
# hed1.angle = a0a1a2[dndx]
# hed2.angle = a1a2a3[dndx]
for gCBd in gCBdihedra:
gCBd.ic_residue.build_glyCB(gCBd)
@staticmethod
def _write_mtx(fp: TextIO, mtx: numpy.array) -> None:
fp.write("[ ")
rowsStarted = False
for row in mtx:
if rowsStarted:
fp.write(", [ ")
else:
fp.write("[ ")
rowsStarted = True
colsStarted = False
for col in row:
if colsStarted:
fp.write(", " + str(col))
else:
fp.write(str(col))
colsStarted = True
fp.write(" ]") # close row
fp.write(" ]")
@staticmethod
def _writeSCAD_dihed(
fp: TextIO, d: "Dihedron", hedraNdx: Dict, hedraSet: Set[EKT]
) -> None:
fp.write(
"[ {:9.5f}, {}, {}, {}, ".format(
d.angle, hedraNdx[d.h1key], hedraNdx[d.h2key], (1 if d.reverse else 0)
)
)
fp.write(
"{}, {}, ".format(
(0 if d.h1key in hedraSet else 1), (0 if d.h2key in hedraSet else 1)
)
)
fp.write(
" // {} [ {} -- {} ] {}\n".format(
d.id, d.hedron1.id, d.hedron2.id, ("reversed" if d.reverse else "")
)
)
fp.write(" ")
IC_Chain._write_mtx(fp, d.rcst)
fp.write(" ]") # close residue array of dihedra entry
def write_SCAD(self, fp: TextIO, backboneOnly: bool) -> None:
"""Write self to file fp as OpenSCAD data matrices.
Works with write_SCAD() and embedded OpenSCAD routines in SCADIO.py.
The OpenSCAD code explicitly creates spheres and cylinders to
represent atoms and bonds in a 3D model. Options are available
to support rotatable bonds and magnetic hydrogen bonds.
Matrices are written to link, enumerate and describe residues,
dihedra, hedra, and chains, mirroring contents of the relevant IC_*
data structures.
The OpenSCAD matrix of hedra has additional information as follows:
* the atom and bond state (single, double, resonance) are logged
so that covalent radii may be used for atom spheres in the 3D models
* bonds and atoms are tracked so that each is only created once
* bond options for rotation and magnet holders for hydrogen bonds
may be specified
Note the application of IC_Chain attribute MaxPeptideBond: missing
residues may be linked (joining chain segments with arbitrarily long
bonds) by setting this to a large value.
All ALTLOC (disordered) residues and atoms are written to the output model.
"""
fp.write(f' "{self.chain.id}", // chain id\n')
# generate dict for all hedra to eliminate redundant references
hedra = {}
for ric in self.ordered_aa_ic_list:
respos, resicode = ric.residue.id[1:]
for k, h in ric.hedra.items():
hedra[k] = h
atomSet: Set[AtomKey] = set()
bondDict: Dict = {} # set()
hedraSet: Set[EKT] = set()
ndx = 0
hedraNdx = {}
for hk in sorted(hedra):
hedraNdx[hk] = ndx
ndx += 1
# write residue dihedra table
fp.write(" [ // residue array of dihedra")
resNdx = {}
dihedraNdx = {}
ndx = 0
chnStarted = False
for ric in self.ordered_aa_ic_list:
if "O" not in ric.akc:
if ric.lc != "G" and ric.lc != "A":
print(
f"Unable to generate complete sidechain for {ric} {ric.lc} missing O atom"
)
resNdx[ric] = ndx
if chnStarted:
fp.write("\n ],")
else:
chnStarted = True
fp.write(
"\n [ // "
+ str(ndx)
+ " : "
+ str(ric.residue.id)
+ " "
+ ric.lc
+ " backbone\n"
)
ndx += 1
# assemble with no start position, return transform matrices
ric.clear_transforms()
ric.assemble(resetLocation=True)
ndx2 = 0
started = False
for i in range(1 if backboneOnly else 2):
if i == 1:
cma = "," if started else ""
fp.write(
f"{cma}\n // {str(ric.residue.id)} {ric.lc} sidechain\n"
)
started = False
for dk, d in sorted(ric.dihedra.items()):
if d.h2key in hedraNdx and (
(i == 0 and d.is_backbone()) or (i == 1 and not d.is_backbone())
):
if d.rcst is not None:
if started:
fp.write(",\n")
else:
started = True
fp.write(" ")
IC_Chain._writeSCAD_dihed(fp, d, hedraNdx, hedraSet)
dihedraNdx[dk] = ndx2
hedraSet.add(d.h1key)
hedraSet.add(d.h2key)
ndx2 += 1
else:
print(
f"Atom missing for {d.id3}-{d.id32}, OpenSCAD chain may be discontiguous"
)
fp.write(" ],") # end of residue entry dihedra table
fp.write("\n ],\n") # end of all dihedra table
# write hedra table
fp.write(" [ //hedra\n")
for hk in sorted(hedra):
hed = hedra[hk]
fp.write(" [ ")
fp.write(
"{:9.5f}, {:9.5f}, {:9.5f}".format(
set_accuracy_95(hed.lal[0]), # len12
set_accuracy_95(hed.lal[1]), # angle
set_accuracy_95(hed.lal[2]), # len23
)
)
atom_str = "" # atom and bond state
atom_done_str = "" # create each only once
akndx = 0
for ak in hed.aks:
atm = ak.akl[AtomKey.fields.atm]
res = ak.akl[AtomKey.fields.resname]
# try first for generic backbone/Cbeta atoms