/
PDB2LEGO.py
3003 lines (2567 loc) · 105 KB
/
PDB2LEGO.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
#!/usr/bin/env python3
# Tommy Carstensen, 2011, 2015jun, 2015jul
# todo 2015nov25: rewrite function coords_to_lxfml
import os
import math
import argparse
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import urllib.request
def main():
args = argparser()
# parse PDB coordinates
# keys ATOM, HETATM; CHAIN; RESNO; ATOMNAME; element_color, coord, element_size
d_coords_PDB = parse_pdb(args)
# convert Angstrom coordinates to brick coordinates
## d_layers[layer][str(color)]['x'][x] = [y1, y2, yn]
## d_buried[layer][x][y] = {'all': i, 'excl_diagonals': i}
d_layers, l_minmax_bricks, d_buried = coordAngstrom2coordBrick(
args, d_coords_PDB)
del d_coords_PDB # save some memory
# convert brick coordinates to bricks
coordBrick2coordLDD(
args, d_layers, l_minmax_bricks, d_buried,
)
plot_layers(args, d_layers, d_buried, l_minmax_bricks)
del d_layers, l_minmax_bricks # save some memory
return
def plot_layers(args, d_layers, d_buried, l_minmax_bricks):
## N, C, O, H, P, prev layer
l_prev = []
l_curr = []
## plot previous layer with traingle
## plot C, N, O, P, H, buried
## C = black circle
## N = blue square
## O = red triangle
## H = white diamond
## P = orange circle
## buried = green triangle2
## support? = green circle
## ax.set_xlim(l_minmax_bricks[0])
## ax.set_ylim(l_minmax_bricks[1])
midx = (l_minmax_bricks[0][1]+l_minmax_bricks[0][0])/2
midy = (l_minmax_bricks[1][1]+l_minmax_bricks[1][0])/2
dmax = max(
l_minmax_bricks[0][1]-l_minmax_bricks[0][0],
l_minmax_bricks[1][1]-l_minmax_bricks[1][0],
)
## plt.xlim(midx-dmax/2, midx+dmax/2)
## plt.ylim(midy-dmax/2, midy+dmax/2)
## ax.axis('equal')
## ax.set_xlim(midx-dmax/2, midx+dmax/2)
## ax.set_ylim(midy-dmax/2, midy+dmax/2)
## ax.set_aspect(1)
## max(l_minmax_bricks[0][0], l_minmax_bricks[1][0]),
## max(l_minmax_bricks[0][1], l_minmax_bricks[1][1]),
## )
## plt.ylim(l_minmax_bricks[1])
## plt.axis(l_minmax_bricks[0]+l_minmax_bricks[1])
## plt.axis([midx-dmax/2, midx+dmax/2, midy-dmax/2, midy+dmax/2])
## plt.axis('equal')
## plt.tick_params(which='major', length=1)
## ax.axis('scaled')
## matplotlib colors
d_colors = {
'O': 'r',
'N': 'b',
'C': 'k',
'S': 'y',
'H': 'w',
'P': 'orange',
'SE': 'pink',
'CL': 'lime',
'FE': 'darkred',
'154': 'c',
'141': 'm',
'26': 'k',
'28': 'g',
'194': 'grey',
'119': 'lime',
}
## matplotlib markers.
d_markers = {
'O': 'o', 'N': 's', 'C': 'v', 'S': 'o', 'H': 'D', 'P': 'x',
'SE': 'x', 'CL': 'x', 'FE': 'x',
'154': 'x',
'141': 'x',
'26': 'v',
'28': 'x',
'194': 'x',
}
dpi = 600
if dpi == 300:
size_default = 10
else:
size_default = 4
for i, layer in enumerate(sorted(d_layers.keys())):
print('plt', i, len(d_layers.keys()))
fig, ax = plt.subplots()
for element in d_layers[layer].keys():
for x in d_layers[layer][element]['x'].keys():
for z in d_layers[layer][element]['x'][x]:
size = size_default
if d_buried[layer][x][z]['excl_diagonals'] == 7:
c = 'cyan'
marker = 'x'
else:
try:
c = d_colors[element]
except KeyError:
c = 'm'
try:
marker = d_markers[element]
except KeyError:
marker = 'x'
if i > 0:
for element2 in d_layers[layer-1].keys():
try:
l = d_layers[layer-1][element2]['x'][x]
except KeyError:
continue
if z in l:
bool_supported = True
## ax.scatter(x, z, s=32, c='grey', alpha=0.9, marker='^')
break
else:
bool_supported = False
size = 2.5*size_default
## if bool_supported:
## ax.scatter(x, z, s=32, c='g', alpha=0.9, marker='^')
ax.scatter(x, z, s=size, c=c, alpha=0.9, marker=marker)
## print(i, layer, d_layers[layer])
## print(d_buried[layer].keys())
## print(d_layers[layer]['O'])
## print(d_buried[layer][8])
## print(l_minmax_bricks)
## stop
## ax.plot(x, y)
## ax.set_xlim(midx-dmax/2, midx+dmax/2)
## ax.set_ylim(midy-dmax/2, midy+dmax/2)
ax.set_xlim(l_minmax_bricks[0])
ax.set_ylim(l_minmax_bricks[1])
ax.set_aspect(1)
ax.xaxis.set_minor_locator(MultipleLocator(2))
ax.yaxis.set_minor_locator(MultipleLocator(2))
ax.grid(visible=True, color='k', axis='both', which='major', linestyle='--')
ax.grid(visible=True, color='k', axis='both', which='minor', linestyle=':')
plt.savefig('png/{}_{:d}_{:d}'.format(args.pdb, args.sizeratio, i), dpi=600)
plt.clf()
plt.close()
return
def calculate_support_position(d_layers, l_minmax_bricks,):
#
# dictionary independent of elements
#
d_3d = {}
for z_brick in range(int(l_minmax_bricks[2][0]), int(l_minmax_bricks[2][1])+1):
d_3d[z_brick] = {}
for element in d_layers[z_brick].keys():
for x in d_layers[z_brick][element]['x'].keys():
if x not in d_3d[z_brick].keys():
d_3d[z_brick][x] = []
d_3d[z_brick][x] += d_layers[z_brick][element]['x'][x]
#
# supporters
#
d_support = {}
for z_brick_above in range(
int(l_minmax_bricks[2][0])+1,
int(l_minmax_bricks[2][1])+1,
):
d_support[z_brick_above] = {}
# loop over row/column
for x in d_3d[z_brick_above].keys():
l_above = d_3d[z_brick_above][x]
set_above = set(l_above)
for z_brick_below in range(int(l_minmax_bricks[2][0]), z_brick_above):
# nothing in position below
if x not in d_3d[z_brick_below].keys():
d_support[z_brick_above][x] = set_above
continue
l_below = d_3d[z_brick_below][x]
set_above -= set(l_below)
# everyting above is also below
if len(set_above) == 0:
break
# something above was not below
# use points for support from bottom layer
if len(set_above) > 0:
d_support[z_brick_above][x] = set_above
return d_support
def parse_pdb(args):
'''this function reads the coordinates of a PDB file and returns:
d_coords_PDB[record][chain][res_no][atom_name] = {
'coord':coord, 'element_size':element_size,
'element_color':element_color,
}
'''
pdb = args.pdb
path = 'pdb/{}.pdb'.format(pdb)
print(('reading and parsing {}'.format(path)))
if not os.path.isfile(path):
url = 'http://www.rcsb.org/pdb/files/{}.pdb'.format(pdb.upper())
print(url)
urllib.request.urlretrieve(url, path)
with open(path, 'r') as f:
lines = f.readlines()
d_coords_PDB = {'ATOM': {}, 'HETATM': {}}
l_minmax_PDB = [
[1000., -1000.], [1000., -1000.], [1000., -1000.],
]
d_helix = {}
d_sheet = {}
for line in lines:
record = line[:6].strip()
if record == 'HELIX':
chain = line[19]
res_no1 = int(line[21:25])
res_no2 = int(line[33:37])
try:
d_helix[chain] += list(range(res_no1, res_no2+1))
except KeyError:
d_helix[chain] = list(range(res_no1, res_no2+1))
continue
if record == 'SHEET':
initChainID = line[21]
initSeqNum = int(line[22:26])
endSeqNum = int(line[33:37])
try:
d_sheet[chain].extend(list(range(initSeqNum, endSeqNum+1)))
except KeyError:
d_sheet[chain] = list(range(initSeqNum, endSeqNum+1))
continue
## Only parse the first model of an NMR structure.
## Also skips transformed assymetric units of biological units.
## if record == 'ENDMDL':
## break
if record not in ['ATOM', 'HETATM']:
continue
res_name = line[17:20]
chain = line[21]
if len(args.chains) > 0 and chain not in args.chains:
continue
## Skip water.
if res_name == 'HOH':
continue
element_size = element_color = line[76:78].strip()
if args.exclude_hydrogens is True and element == 'H':
continue
x = float(line[30:38])
y = float(line[38:46])
z = float(line[46:54])
if args.rotate_x90 is True:
z = float(line[38:46])
y = -float(line[46:54])
coord = [x, y, z]
atom_name = line[12:16].strip()
res_no = int(line[22:26])
if chain not in d_coords_PDB[record].keys():
d_coords_PDB[record][chain] = {}
if res_no not in d_coords_PDB[record][chain].keys():
d_coords_PDB[record][chain][res_no] = {}
#
# color by residue instead of by atom
#
if args.bool_color_by_residue is True:
d_elements = {
' DC': 'CL', # green
' DT': '192', # reddish brown
' DA': '119', # lime
' DG': 'S', # yellow
}
element_color = d_elements[res_name]
if args.backbone_color:
if atom_name in [
## Protein
'N', 'CA', 'C', 'O',
## DNA
'P', 'OP1', 'OP2',
]:
element_color = args.backbone_color
else:
if args.backbone_only:
if any([
all([record == 'ATOM' and res_name in [
'ALA', 'CYS', 'ASP', 'GLU', 'PHE', 'GLY', 'HIS',
'ILE', 'LYS', 'LEU', 'MET', 'ASN', 'PRO', 'GLN',
'ARG', 'SER', 'THR', 'VAL', 'TRP', 'TYR',
'A', 'C', 'G', 'T',
'DA', 'DC', 'DG', 'DT',
]]),
all([record == 'HETATM' and res_name in ['MSE',]]),
]):
if not args.sidechains:
continue
if all([
str(res_no) not in args.sidechains,
str(res_no)+chain not in args.sidechains,
]):
continue
else:
element_color = 'H'
elif atom_name == 'H':
element_color = atom_name
else:
element_color = 'C'
if args.res_names:
if res_name in args.res_names:
if atom_name not in ('FE'):
assert len(args.res_name_colors) == len(args.res_names)
element_color = args.res_name_colors[
args.res_names.index(res_name)]
## ## color atoms after residues
## if atom_name in args.atom_names:
## assert len(args.atom_name_colors) == len(args.atom_names)
## element_color = args.atom_name_colors[
## args.atom_names.index(atom_name)]
## Color secondary structure elements.
if args.color_helix:
if chain in d_helix.keys():
if res_no in d_helix[chain]:
if args.sidechains:
if all([
str(res_no) not in args.sidechains,
str(res_no)+chain not in args.sidechains,
]):
element_color = args.color_helix
else:
element_color = args.color_helix
if args.color_sheet:
if chain in d_sheet.keys():
if res_no in d_sheet[chain]:
if args.sidechains:
if all([
str(res_no) not in args.sidechains,
str(res_no)+chain not in args.sidechains,
]):
element_color = args.color_sheet
else:
element_color = args.color_sheet
if args.bool_color_by_chain is True:
element_color = args.colors[args.chains.index(chain)]
d_coords_PDB[record][chain][res_no][atom_name] = {
'coord': coord, 'element_size': element_size,
'element_color': element_color,
}
if res_name == 'HEM':
print(res_name, atom_name, element_color)
for i in range(3):
if coord[i] < l_minmax_PDB[i][0]:
l_minmax_PDB[i][0] = coord[i]
if coord[i] > l_minmax_PDB[i][1]:
l_minmax_PDB[i][1] = coord[i]
return d_coords_PDB
def gcd(a, b):
'''greatest common divisor using Euclid's algorithm'''
while b > 1e-14:
a, b = b, a % b
return a
def lcm(a, b):
'''least/lowest/smallest common multiple'''
multiple = a*b // gcd(a, b)
return multiple
def calc_brick_per_Angstrom(args):
#
# find least common multiple of brick height and length
#
height = 9.6 # mm
width = 8.0 # mm
multiplier = lcm(9.6, 8.0)
# slightly slower method for finding least common multiple
multiplier = 1
height = 9.6 # mm
width = 8 # mm
while True:
if multiplier*height % width == 0:
break
multiplier += 1
multiplier *= height
# plates
bpa_x = bricks_per_angstrom_x = 4. # 8mm width
bpa_y = bricks_per_angstrom_y = 4. # 8mm width
bpa_z = bricks_per_angstrom_z = 10. # 3.2mm height
# bricks (9.6mm height) - 48mm per Angstrom = 480, 000, 000:1
bpa_x = bricks_per_angstrom_x = multiplier/width # 6, 8mm width
bpa_y = bricks_per_angstrom_y = multiplier/width # 6, 8mm width
if args.brick_or_plate == 'brick':
bpa_z = bricks_per_angstrom_z = multiplier/height # 5, 9.6mm height (brick)
elif args.brick_or_plate == 'plate':
bpa_z = bricks_per_angstrom_z = 15. # 3.2mm height (plate)
#
# additional scaling
#
bpa_x /= args.sizeratio
bpa_y /= args.sizeratio
bpa_z /= args.sizeratio
# list of scaling factors
l_bpa = [bpa_x, bpa_y, bpa_z]
return l_bpa
def coordAngstrom2coordBrick(args, d_coords_PDB):
pdb = args.pdb
print('convert PDB coordinates to brick coordinates')
#
# set i/o file path
#
fn = 'txt/{}_{}_{}_layers'.format(
pdb, args.sizeratio, args.brick_or_plate,)
if args.bool_hollow is True:
fn += '_hollow'
if args.bool_color_by_residue is True:
fn += '_colorbyresidue'
if args.bool_color_by_chain is True:
fn += '_colorbychain'
if args.backbone_only is True:
fn += '_backboneonly'
if args.backbone_color:
fn += '_backbonecolor{}'.format(args.backbone_color)
if args.bool_grained is True:
fn += '_flying1x1removal'
fn += '.txt'
#
# set i/o file path
#
fn_buried = 'txt/{}_{}_{}_buried'.format(
args.pdb, args.sizeratio, args.brick_or_plate,)
if args.bool_grained is True:
fn_buried += '_flying1x1removal'
if args.backbone_only is True:
fn += '_backboneonly'
if args.bool_hollow is True:
fn += '_hollow'
fn_buried += '.txt'
if os.path.isfile(fn) and os.path.isfile(fn_buried):
#
# read
#
print(('reading', fn))
fd = open(fn, 'r')
s = fd.read()
fd.close()
d_layers = eval(s)
del s
fd = open(fn_buried, 'r')
s = fd.read()
fd.close()
d_buried = eval(s)
del s
else:
#
# loop over PDB coordinates and check distance to surrounding grid points
#
d_vicinal = find_vicinal(args, d_coords_PDB,)
#
#
#
d_layers = append_bricks_by_atom_vicinity(d_vicinal,)
#
# remove pieces before determining what is buried and what is not
#
d_layers = remove_bricks_outside(args, d_layers)
#
# hollow option
#
if args.bool_hollow is True:
d_layers, d_buried = remove_or_replace_bricks_inside(d_layers,)
else:
d_buried = find_buried(d_layers,)
#
# write output
#
print(('writing', fn))
fd = open(fn, 'w')
fd.write(str(d_layers))
fd.close()
fd = open(fn_buried, 'w')
fd.write(str(d_buried))
fd.close()
#
#
#
l_minmax_bricks = get_dimensions(args, d_layers,)
return d_layers, l_minmax_bricks, d_buried
def remove_or_replace_bricks_inside(d_layers,):
d_buried = find_buried(d_layers,)
replace_atom = replace_atom
# either replace buried bricks with black
# or delete buried bricks
for z_brick in d_buried.keys():
if replace_atom not in d_layers[z_brick].keys():
d_layers[z_brick][replace_atom] = {'x': {}, 'y': {}}
for element in d_layers[z_brick].keys():
l_xbricks = list(d_layers[z_brick][element]['x'].keys())
l_xbricks.sort()
for x_brick in l_xbricks:
l_ybricks = list(d_layers[z_brick][element]['x'][x_brick])
l_ybricks.sort()
for y_brick in l_ybricks:
count_buried_excl_diagonals = (
d_buried[z_brick][x_brick][y_brick]['excl_diagonals']
)
count_buried = d_buried[z_brick][x_brick][y_brick]['all']
# delete
if args.bool_hollow is True and count_buried == 3*3*3:
d_layers[z_brick][element]['x'][x_brick].remove(y_brick)
d_layers[z_brick][element]['y'][y_brick].remove(x_brick)
return d_layers, d_buried
def get_dimensions(args, d_layers,):
if args.verbose is True:
print('determining brick dimensions')
l_minmax_bricks = [[1000., -1000.], [1000., -1000.], [1000., -1000.]]
for z_brick in d_layers.keys():
for element in d_layers[z_brick].keys():
for x_brick in d_layers[z_brick][element]['x'].keys():
for y_brick in d_layers[z_brick][element]['x'][x_brick]:
coord_brick = [x_brick, y_brick, z_brick]
for i in range(3):
if coord_brick[i] < l_minmax_bricks[i][0]:
l_minmax_bricks[i][0] = coord_brick[i]
if coord_brick[i] > l_minmax_bricks[i][1]:
l_minmax_bricks[i][1] = coord_brick[i]
print(('Brick dimensions (bricks)', l_minmax_bricks))
print(('Brick dimensions (model, cm)',))
print(('width', 0.8*(l_minmax_bricks[0][1]-l_minmax_bricks[0][0]),))
print(('width', 0.8*(l_minmax_bricks[1][1]-l_minmax_bricks[1][0]),))
if args.brick_or_plate == 'plate':
print(('height', 0.32*(l_minmax_bricks[2][1]-l_minmax_bricks[2][0])))
elif args.brick_or_plate == 'brick':
print(('height', 0.96*(l_minmax_bricks[2][1]-l_minmax_bricks[2][0])))
return l_minmax_bricks
def remove_bricks_outside(args, d_layers,):
print('removing "outside" bricks before determining which bricks are buried')
if args.bool_grained is True:
l_removal = []
#
# loop over sorted layers to remove bricks from the bottom and up
#
l_zbricks = list(d_layers.keys())
l_zbricks.sort()
for z_brick in l_zbricks:
# Don't remove the bottom brick no matter what.
if z_brick == min(d_layers.keys()):
continue
for element in d_layers[z_brick].keys():
for x_brick in d_layers[z_brick][element]['x'].keys():
for y_brick in d_layers[z_brick][element]['x'][x_brick]:
count_buried = 0
count_buried_excl_diagonals = 0
count_above_below = 0
count_below = 0
count_plane = 0
for z_add in [-1, 0, 1]:
z2 = z_brick+z_add
if z_brick+z_add not in d_layers.keys():
continue
# loop over all neigbouring element types
for element2 in d_layers[z_brick+z_add].keys():
for x_add in [-1, 0, 1]:
x2 = x_brick+x_add
if (
x_brick+x_add
not in
list(d_layers[z_brick+z_add][element2]['x'].keys())
):
continue
for y_add in [-1, 0, 1]:
y2 = y_brick+y_add
if (
y_brick+y_add
in
d_layers[z_brick+z_add][element2]['x'][x_brick+x_add]
):
count_buried += 1
if (
(y_add == 0 and z_add == 0) or
(x_add == 0 and z_add == 0) or
(x_add == 0 and y_add == 0)
):
count_buried_excl_diagonals += 1
if z_add == 0:
count_plane += 1
elif z_add != 0:
count_above_below += 1
if z_add == -1:
count_below += 1
continue
# "get rid of 1x1 hanging pieces"
# nothing *above or below* brick
# and only 1 brick in the plane around the brick
if count_above_below == 0 and count_plane == 1+1:
l_removal += [[z_brick, element, x_brick, y_brick]]
# "don't add 1x1s to new layers when building from the bottom and up"
# nothing in the plane around the brick
# and nothing *below* the brick
elif count_below == 0 and count_plane == 1:
d_layers[z_brick][element]['x'][x_brick].remove(y_brick)
d_layers[z_brick][element]['y'][y_brick].remove(x_brick)
print(('remove2', z_brick, element))
# "get rid of pieces sticking out otherwise troubling the use of 2 knob bricks"
# nothing above or below brick
# (*after* removal of any bricks below;
# thus sorted z_brick values necessary
# and immediate removal in previous layer happened)
elif count_above_below == 0:
d_layers[z_brick][element]['x'][x_brick].remove(y_brick)
d_layers[z_brick][element]['y'][y_brick].remove(x_brick)
print(('remove3', z_brick, element))
# end of loop over elements
for z_brick, element, x_brick, y_brick in l_removal:
d_layers[z_brick][element]['x'][x_brick].remove(y_brick)
d_layers[z_brick][element]['y'][y_brick].remove(x_brick)
print(('remove1', z_brick, element))
return d_layers
def find_vicinal(args, d_coords_PDB,):
print('find grid points vicinal to atom coordinates')
l_bpa = calc_brick_per_Angstrom(args)
d_vicinal = {}
for record in d_coords_PDB.keys():
for chain in d_coords_PDB[record].keys():
for res_no in d_coords_PDB[record][chain].keys():
if args.verbose:
print(('chain', chain, 'residue', res_no))
for atom_name in d_coords_PDB[record][chain][res_no].keys():
element_size = (
d_coords_PDB[record][chain][res_no][atom_name][
'element_size'
]
)
element_color = (
d_coords_PDB[record][chain][res_no][atom_name][
'element_color'
]
)
coord_PDB = (
d_coords_PDB[record][chain][res_no][atom_name][
'coord'
]
)
# convert Angstrom coord to grid coord
# loop over vicinal grid coords (cube)
grid_brick = []
for i in range(3):
grid_brick += [[
int(math.floor(
(coord_PDB[i]-args.d_radii[element_size])*l_bpa[i]
)),
int(math.ceil(
(coord_PDB[i]+args.d_radii[element_size])*l_bpa[i]
)),
]]
sq_radius = args.d_radii[element_size]**2
position = 0
positionok = 0
#
# loop over grid bricks and check distance from center of atom
#
for x_brick in range(grid_brick[0][0], grid_brick[0][1]+1,):
x_LEGO_Angstrom = x_brick/l_bpa[0]
for y_brick in range(grid_brick[1][0], grid_brick[1][1]+1,):
y_LEGO_Angstrom = y_brick/l_bpa[1]
for z_brick in range(grid_brick[2][0], grid_brick[2][1]+1,):
z_LEGO_Angstrom = z_brick/l_bpa[2]
coord_LEGO_Angstrom = [
x_LEGO_Angstrom,
y_LEGO_Angstrom,
z_LEGO_Angstrom,
]
position += 1
sq_dist = 0
for i in range(3):
sq_dist += (coord_LEGO_Angstrom[i]-coord_PDB[i])**2
# grid point too distant from center of sphere
if sq_dist > sq_radius:
continue
if x_brick not in d_vicinal.keys():
d_vicinal[x_brick] = {}
if y_brick not in d_vicinal[x_brick].keys():
d_vicinal[x_brick][y_brick] = {}
if z_brick not in d_vicinal[x_brick][y_brick].keys():
d_vicinal[x_brick][y_brick][z_brick] = {}
d_vicinal[x_brick][y_brick][z_brick][sq_dist] = element_color
return d_vicinal
def append_bricks_by_atom_vicinity(d_vicinal,):
print('appending bricks according to atom nearest to grid point')
d_layers = {}
l_x_bricks = list(d_vicinal.keys())
l_x_bricks.sort()
for x_brick in l_x_bricks:
l_y_bricks = list(d_vicinal[x_brick].keys())
l_y_bricks.sort()
for y_brick in l_y_bricks:
for z_brick in d_vicinal[x_brick][y_brick].keys():
dist_min = min(d_vicinal[x_brick][y_brick][z_brick].keys())
element = d_vicinal[x_brick][y_brick][z_brick][dist_min]
#
# append coordinate to dictionary of coordinates
#
if z_brick not in d_layers.keys():
d_layers[z_brick] = {}
if element not in d_layers[z_brick].keys():
d_layers[z_brick][element] = {'x': {}, 'y': {}}
if x_brick not in d_layers[z_brick][element]['x'].keys():
d_layers[z_brick][element]['x'][x_brick] = []
if y_brick not in d_layers[z_brick][element]['y'].keys():
d_layers[z_brick][element]['y'][y_brick] = []
# d_layers[z_brick][element] += [[x_brick, y_brick]]
# Why is it not redundant to add for both dimensions?
d_layers[z_brick][element]['x'][x_brick] += [y_brick]
d_layers[z_brick][element]['y'][y_brick] += [x_brick]
return d_layers
def find_buried(d_layers,):
print('preparing to remove "buried" bricks \
after removing "isolated" bricks on the outside')
d_buried = {}
for z_brick in d_layers.keys():
d_buried[z_brick] = {}
for element in d_layers[z_brick].keys():
for x_brick in d_layers[z_brick][element]['x'].keys():
if x_brick not in d_buried[z_brick].keys():
d_buried[z_brick][x_brick] = {}
for y_brick in d_layers[z_brick][element]['x'][x_brick]:
count_buried = 0
count_buried_excl_diagonals = 0
for z_add in [-1, 0, 1]:
z2 = z_brick+z_add
if z_brick+z_add not in d_layers.keys():
continue
# loop over all neigbouring element types
for element2 in d_layers[z_brick+z_add].keys():
for x_add in [-1, 0, 1]:
x2 = x_brick+x_add
if x_brick+x_add not in d_layers[z_brick+z_add][element2]['x'].keys():
continue
for y_add in [-1, 0, 1]:
y2 = y_brick+y_add
if (
y_brick+y_add
in
d_layers[z_brick+z_add][element2]['x'][x_brick+x_add]
):
count_buried += 1
if (
(y_add == 0 and z_add == 0) or
(x_add == 0 and z_add == 0) or
(x_add == 0 and y_add == 0)
):
count_buried_excl_diagonals += 1
continue
if count_buried == 3*3*3:
bool_buried = True
elif count_buried_excl_diagonals == 6+1:
bool_buried = True
else:
bool_buried = False
d_buried[z_brick][x_brick][y_brick] = {
'all': count_buried,
'excl_diagonals': count_buried_excl_diagonals,
}
return d_buried
def check_if_buried(d_layers, z_brick, xy, consecutive, k1, k2):
l_below_all_elements = check_bricks_vicinal_all_elements(
d_layers, z_brick-1, k1, xy, consecutive,
)
l_above_all_elements = check_bricks_vicinal_all_elements(
d_layers, z_brick+1, k1, xy, consecutive,
)
l_behind_all_elements = check_bricks_vicinal_all_elements(
d_layers, z_brick, k1, xy-1, consecutive,
)
l_front_all_elements = check_bricks_vicinal_all_elements(
d_layers, z_brick, k1, xy+1, consecutive,
)
l_left_all_elements = check_bricks_vicinal_all_elements(
d_layers, z_brick, k2, consecutive[0]-1, consecutive,
)
l_right_all_elements = check_bricks_vicinal_all_elements(
d_layers, z_brick, k2, consecutive[0]+1, consecutive,
)
l_yx = list(range(consecutive[0], consecutive[0]+consecutive[1]))
if (
# no bricks below
len(set(l_yx) & set(l_below_all_elements)) == 0 and
# no bricks above
len(set(l_yx) & set(l_above_all_elements)) == 0
):
print(consecutive)
print(l_below_all_elements)
print(l_above_all_elements)
print(l_yx)
stop_nothing_to_hang_on_to
# above/below
set_below_and_above = set(l_below_all_elements) & set(l_above_all_elements)
set_exposed_vertical = set(l_yx)-set_below_and_above
# behind/front
set_behind_and_front = set(l_behind_all_elements) & set(l_front_all_elements)
set_exposed_horizontal1 = set(l_yx)-set_behind_and_front
# left/right
None
set_exposed = set_exposed_horizontal1 | set_exposed_vertical
set_buried = set(l_yx)-set_exposed
l_exposed = list(set_exposed)
l_buried = list(set_buried)
l_exposed.sort()
l_buried.sort()
return l_exposed, l_buried
def coordBrick2coordLDD(
args, d_layers, l_minmax_bricks, d_buried,
):
'''convert 1x1x1 brick coordinates to bricks'''
#
#
#
d_bricks_main = coords_to_lxfml(
args, d_layers, l_minmax_bricks, d_buried,
)
if args.optimise_cost or args.optimise_stability:
d_bricks_main = check_vicinal_small_bricks(args, d_bricks_main)
# convert dic of bricks to lines of bricks
# after replacing small bricks with large bricks and after recoloring
lines_lxfml_body, refID, steps = dic2lines(args, d_bricks_main)
#
# Add 48x48 grey base plate.
#
if args.add_plate is True:
x_min = float('inf')
x_max = float('-inf')
y_min = float('inf')
y_max = float('-inf')
for layer in d_layers.keys():
for element in d_layers[layer].keys():
for x in d_layers[layer][element]['x'].keys():
x_min = min(x, x_min)
x_max = max(x, x_max)
for y in d_layers[layer][element]['x'][x]:
y_min = min(y, y_min)
y_max = max(y, y_max)
plate_size = 48
designID_baseplate = 4186
materialID_grey = 194
refID += 1
s = format_line(
refID, designID_baseplate, materialID_grey, 0, 0,
.8*(x_max+x_min-plate_size)/2, 0, .8*(y_max+y_min+plate_size)/2)
lines_lxfml_body.append(s)
#
# Add transparent supports.
#