-
Notifications
You must be signed in to change notification settings - Fork 0
/
json2cosm.py
executable file
·1640 lines (1475 loc) · 51.7 KB
/
json2cosm.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 python
# encoding: utf-8
import json
import argparse
import string
import copy
import math
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', required=True,
action='store', dest='input',
help='input cadnano json file')
parser.add_argument('-o', '--output', required=True,
action='store', dest='output',
help='output pdb file')
parser.add_argument('-r', '--restr', required=True,
action='store', dest='cnct',
help='output distance/angle restraints')
parser.add_argument('-t', '--top', required=True,
action='store', dest='top',
help='output file for ccg --> cg / fullatom convertation')
parser.add_argument('-l', '--lattice', required=True,
action='store', dest='lattice',
help='lattice type (hexagonal / square)')
parser.add_argument('-m', '--map', required=True,
action='store', dest='map',
help='2d coords map file')
parser.add_argument('--seq',
action='store', dest='seq',
help='scaffold sequence')
parser.add_argument('--oligs',
action='store', dest='oligs',
help='staple sequences exported csv')
args = parser.parse_args()
# do not 3-5 restr if additional oligs
# lattice crossovers - not only near
# other constants for olig-ssnear (hexcl)
HELIXDIST = 22.0
def honeycomb(row, col, dist=HELIXDIST):
"""Cadnano honeycomb lattice into cartesian"""
# k = distance between helixes
ANGLE = 30.0
x = col * dist * math.cos(math.radians(ANGLE))
if (row % 2) != 0:
y = (row * 3 + 1 - col % 2) * dist * math.sin(math.radians(ANGLE))
else:
y = (row * 3 + col % 2) * dist * math.sin(math.radians(ANGLE))
return x, y
def square(row, col, dist=HELIXDIST):
"""Cadnano square lattice into cartesian"""
x = col * dist
y = row * dist
return x, y
def revers(vh, scaf):
"""Directoin of scaffold or staple chain (1/-1)"""
rev = (Rows[vh] + Cols[vh]) % 2
if rev:
k = -1
else:
k = 1
if scaf:
k *= -1
return k
def get_scaffold_path(end):
"""Get coords from 5' (end) until find the 3'-end; for scaffold"""
k = revers(end[0], 0)
# rev = (Rows[end[0]] + Cols[end[0]]) % 2
if k == 1:
path = Path['scaf'][end[0]][end[1] + 1:]
else:
path = Path['scaf'][end[0]][:end[1]]
path.reverse()
cross_base = next(i for i, str in enumerate(path) if str != end[0])
cross_vh = path[cross_base]
# if not rev:
# k = 1
# else:
# k = -1
res = None
# print Path['scaf'][3][5]
# print cross_base, cross_vh
cross_base = end[1] + k * cross_base + k # + (k + 1)/2
if cross_vh == 'e3':
res = ['end', cross_base]
else:
for tr in trans_sc:
if (tr[0] == [end[0], cross_vh]) and (cross_base == tr[1][0]):
res = [cross_vh, tr[1][1]]
if (tr[0] == [cross_vh, end[0]]) and (cross_base == tr[1][1]):
res = [cross_vh, tr[1][0]]
return [[end[0], cross_base], res]
def nextbase(vh, base, seq):
""" Get next base after """
# works two times in sequence search:
# 1st iteration for next sequence negin point
# 2nd iterantion for sequence checking
global last1, last2
if seq:
lastc = last2
else:
lastc = last1
k = revers(vh, 0)
if not lastc:
for pair in trans_sc:
if pair[0][0] == vh and pair[1][0] == base:
if seq:
last2 = True
else:
last1 = True
return [pair[0][1], pair[1][1]]
if seq:
last2 = False
else:
last1 = False
return [vh, base + k]
def checkseq(vh, base):
""" Check if sequence and oligs fit on this step """
global last2
last2 = last1
beg = [vh, base]
# k = revers(vh, 0) # Commented during code cleaning
i = 0
while [vh, base] != beg or not i: # and Path['scaf'][vh][base] != 'e3':
if endtmp and Path['scaf'][vh][base] == 'e3':
return True
if seqPath[vh][base] != '-': # in ['A', 'T', 'G', 'C']:
if seq[i].upper() != compl[seqPath[vh][base]]:
return False
[vh, base] = nextbase(vh, base, True)
i += 1
return True
def findnextnot(end, pat):
global k
# print end, pat
if k == 1:
path = allPath[end[0]][end[1] + 1:]
else:
path = allPath[end[0]][:end[1]]
path.reverse()
if path:
path = [pat] + path
i = 0
cross_base = None
while i < len(path) - 1 and not cross_base:
i += 1
if path[i] not in [pat, '-']:
cross_base = i
# cross_vh = path[cross_base]
if cross_base:
# cross_base += 1
cross_base = end[1] + k * cross_base
# print cross_base
# if k == -1:
# cross_base -= 1
return [end, [end[0], cross_base]]
else:
return None
else:
return None
def outscheme(a, b):
mapf.write('L ' + str(a) + ':' + str(vhNums.index(b)) + '\n')
def pathandtype(end, s):
"""Get next duplex end or vh (chain) change"""
global k
if s == 'change':
new_chain = get_scaffold_path([end[0], end[1] - k])
else:
new_chain = get_scaffold_path(end)
new_change = findnextnot(end, allPath[end[0]][end[1]])
if new_chain[1] is None:
new_end = new_change[1]
s = 'change'
l = new_change[1][1] - k
return [([allPath[end[0]][end[1]], end[0], [end[1], l]], new_end), s]
if new_change:
if new_chain[0][1] * k <= (new_change[1][1] - k) * k:
new_end = new_chain[1]
s = 'chain'
l = new_chain[0][1]
outscheme(new_chain[0][1], new_chain[0][0])
if new_chain[1][0] != 'end':
outscheme(new_chain[1][1], new_chain[1][0])
else:
new_end = new_change[1]
s = 'change'
l = new_change[1][1] - k
else:
new_end = new_chain[1]
s = 'chain'
l = new_chain[0][1]
outscheme(new_chain[0][1], new_chain[0][0])
if new_chain[1][0] != 'end':
outscheme(new_chain[1][1], new_chain[1][0])
return [([allPath[end[0]][end[1]], end[0], [end[1], l]], new_end), s]
def prconnect(base1, base2):
"""Print crossover restraints"""
global l
template = "{0[0]:<6s}{0[1]:>5d}{0[2]:>5d}"
t = tuple(['CONECT', base1, base2])
outpdbc.append(template.format(t) + '\n')
if not (isinstance(base2, int) and isinstance(base1, int)):
raise Exception('ADMIN: PY1. Error with staple restraints')
def findconnects(vh, j, number, length, end):
"""Find crossover restraints"""
global connects, needed, add_tmp
if end == 's':
return None
# [x, y] = [0, 0]
k = revers(vh, 0)
seq = [j]
seq += range(j + k, j + k * length, k)
ind = []
for i in seq:
dif = (i - j) * k
if Path['stap'][vh][i] not in [vh, 'e5', 'e3', '-']:
if [vh, i] in needst:
n = needst.index([vh, i])
if i == j:
needst[n] = (number, 0)
add_tmp.append([number, 0, connst[n][0], connst[n][1]])
elif i % HC == HC - 1:
needst[n] = (number, dif)
if k == -1:
add_tmp.append([number, 1, connst[n][0], connst[n][1]])
else:
add_tmp.append(
[number, length - 1, connst[n][0], connst[n][1]])
else:
needst[n] = (number + dif, 0)
add_tmp.append(
[number + dif, 0, connst[n][0], connst[n][1]])
if [vh, i] in needed:
n = needed.index([vh, i])
if i == j:
needed[n] = number
elif i % HC == HC - 1:
if k == 1:
needed[n] = number + 1
else:
needed[n] = number
else:
ind.append(dif)
needed[n] = number + dif
for i in seq:
dif = (i - j) * k
if Path['stap'][vh][i] not in [vh, 'e5', 'e3', '-']:
if [vh, i] not in needed:
l = Path['stap'][vh][i]
for pair in trans:
if pair[0] == [vh, l] and pair[1][0] == i:
needst.append([pair[0][1], pair[1][1]])
if i == j:
connst.append((number, 0))
if number not in connects + needed:
connects.append(number)
needed.append([pair[0][1], pair[1][1]])
elif i % HC == HC - 1:
if k == -1:
connst.append((number, 1))
else:
connst.append((number, length - 1))
if [vh, i + 1] not in needed:
if k == 1:
if number + 1 not in connects + needed:
connects.append(number + 1)
needed.append([pair[0][1], pair[1][1]])
else:
if number not in connects + needed:
connects.append(number)
needed.append([pair[0][1], pair[1][1]])
else:
connst.append((number + dif, 0))
if dif not in ind:
ind.append(dif)
connects.append(number + dif)
needed.append([pair[0][1], pair[1][1]])
if ind:
return ind
return None
def checkreg(pair):
[[vh1, b1], [vh2, b2]] = pair
if not (isinstance(b1, int) and isinstance(b2, int)):
return True
c = -1
ok1 = False
ok2 = False
end = ['-']
if endtmp:
end += ['e5', 'e3']
while (Path['scaf'][vh1][b1 + c] not in end and
Path['scaf'][vh2][b2 + c] not in end and
c > lim * -1):
if Path['stap'][vh1][b1 + c] == vh2:
ok1 = True
c -= 1
c = 1
while (Path['scaf'][vh1][b1 + c] not in end and
Path['scaf'][vh2][b2 + c] not in end and
c < lim):
if Path['stap'][vh1][b1 + c] == vh2:
ok2 = True
c += 1
return ok1 | ok2
def crosscheck(one, two, thr):
'''Check if crossovers in the range'''
ok = True
# print one, two, thr
for pair in [[one, two], [two, thr]]:
ok = ok & checkreg(pair)
return ok
def TtoB(name, atom1):
if atom1 == a_sc - 1 or atom1 == 1:
return name
atom2 = atom1 + 1
atom1 = atomsh[atom1]
atom2 = atomsh[atom2]
if checkreg([atom1, atom2]):
return name
else:
if name == 'T':
return 'B'
else:
return 'B' + name[1:]
def check_circular(vh, i):
global valStap
k = revers(vh, 1)
end5 = (vh, i)
end3 = False
nextbase = None
prevcr = False
while not end3 and nextbase != end5:
valStap[vh][i] = '-'
if nextbase:
(vh, i) = nextbase
else:
(vh, i) = end5
k = revers(vh, 1)
nextbase = None
# print vh, i, Path['stap'][vh][i]
if Path['stap'][vh][i] in [vh, 'e5'] or prevcr:
nextbase = (vh, i + k)
prevcr = False
else:
if not prevcr:
for pair in trans:
if pair[0][0] == vh and pair[1][0] == i:
nextbase = (pair[0][1], pair[1][1])
prevcr = True
if not nextbase:
if Path['stap'][vh][i] == 'e3':
end3 = True
valStap[vh][i] = '-'
else:
raise Exception(
'ADMIN: PY1. Smth wrong with staple crossover paths')
if nextbase == end5:
raise Exception('ADMIN: PY1. Smth wrong with staple crossover paths')
def staplesends(vh, i, number, length):
"""Find staple ends through path"""
global needst, connst, add_ends
rev = (Rows[vh] + Cols[vh]) % 2
if not isinstance(i, int):
return False
if not rev:
k = 1
else:
k = -1
l = 0
while l < length:
a = Path['stap'][vh][i]
if a == 'e5':
add_ends.append(('e5', vh, i))
check_circular(vh, i)
elif a == 'e3':
add_ends.append(('e3', vh, i))
i += k
l += 1
def scaffoldcross(vh, i, number):
"""Find and print scaffold crossovers"""
global scconn, scneed # check for inserts!
rev = (Rows[vh] + Cols[vh]) % 2
if not rev:
k = 1
else:
k = -1
if (vh, i) in scneed: # test this
n = scneed.index((vh, i))
# t = atomsh[scconn][n]
# if number
scneed[n] = number
elif (vh, i) in scconn:
n = scconn.index((vh, i))
scconn[n] = number
else:
n = None
for pair in trans_sc:
if pair[0][0] == vh and pair[1][0] == i:
if Path['scaf'][vh][i + k] not in [vh, '-']:
if Path['scaf'][vh][i - k] in [vh, '-']:
if (vh, i + k) in atomsh:
n = atomsh.index((vh, i + k))
if n != number - 1:
scneed.append((vh, i + k))
scconn.append(number)
else:
raise Exception(
'ADMIN: PY1. Error with scaffold '
'restraints (2bp duplex)')
elif Path['scaf'][vh][i - k] not in [vh, '-']:
if (vh, i - k) in atomsh:
n = atomsh.index((vh, i - k))
if n != number - 1:
scconn.append((vh, i - k))
scneed.append(number)
def outatom(atom):
"""Print atom in pdb"""
global a_sc
if len(atom) > 1:
template = ("{0[0]:<6s}{0[1]:>5d} {0[2]:<4s}{0[3]:<3s} "
"{0[4]:>1s}{0[5]:>4d} "
"{0[6]:>8.3f}{0[7]:>8.3f}{0[8]:>8.3f}"
"{0[9]:>6.2f}{0[10]:>6.2f} {0[11]:<2s}"
)
t = tuple(atom[:-2])
pdb.write(template.format(t) + '\n')
else:
pdb.write(atom[0])
def addtoout(aname, tname, nlname, ox, oy, z, chain, length, mod):
global a_sc, outpdb, atomsh, anames, outmap
if tname:
t1 = [aname] + [tname] + [nlname]
t2 = [ox, oy] + [z * 3.4] + [1.00, 0.00] + [aname, chain, z]
if mod == 'I':
outpdb.append(['ATOM', a_sc] + t1 + [a_sc] + t2)
outmap.append(['T', tname, a_sc, chain, z])
staplesends(chain, z, a_sc, length)
scaffoldcross(chain, z, a_sc)
atomsh.append((chain, z))
anames.append(tname)
a_sc += 1
t1[1] = 'N'
outpdb.append(['ATOM', a_sc] + t1 + [a_sc] + t2)
outmap.append(['I', 'N', a_sc, chain, z])
atomsh.append((chain, z))
anames.append('N')
a_sc += 1
elif mod == 'Ie':
savename = tname
outpdb.append(['ATOM', a_sc] + t1 + [a_sc] + t2)
outmap.append(['I', tname, a_sc, chain, z])
atomsh.append((chain, z))
anames.append('N')
a_sc += 1
t1[1] = savename
outpdb.append(['ATOM', a_sc] + t1 + [a_sc] + t2)
outmap.append(['T', tname, a_sc, chain, z])
staplesends(chain, z, a_sc, length)
scaffoldcross(chain, z, a_sc)
atomsh.append((chain, z))
anames.append(savename)
a_sc += 1
elif not mod:
outpdb.append(['ATOM', a_sc] + t1 + [a_sc] + t2)
outmap.append(['T', tname, a_sc, chain, z])
staplesends(chain, z, a_sc, length)
scaffoldcross(chain, z, a_sc)
atomsh.append((chain, z))
anames.append(tname)
a_sc += 1
elif mod == 'D':
allPath[chain][z] = 'DELE'
else:
raise Exception('ADMIN: PY1. Wrong modification type')
def createatom(z, chain, tname, length, end, modif):
"""Print particles in the interval -- calculate coords etc"""
global a_sc, dif
[row, col] = [Rows[chain], Cols[chain]]
if not SQ:
[ox, oy] = list(honeycomb(row, col))
else:
[ox, oy] = list(square(row, col))
if a_sc == 1:
dif = None
aname = 'D'
if modif:
if modif[0] not in ['t', 'e']:
inserts = modif[0]
delet = modif[1]
instype = None
else:
instype = modif[0]
inserts = modif[1]
delet = modif[2]
else:
inserts = None
delet = None
if inserts or delet:
for i in inserts:
if i in delet:
raise Exception(
'USER: Insertion and deletion in the same place.')
k = revers(chain, 0)
if (chain, z) in ssnear:
n = ssnear.index((chain, z))
ssnear[n] = a_sc
elif (chain, z - 1) in ssnear:
n = ssnear.index((chain, z - 1))
ssnear[n] = a_sc
if (chain, z) in ssoligs:
n = ssoligs.index((chain, z))
if ssnear[n]:
add.write('scaf ; ' + str(ssnear[n]) + ' ; ' + str(a_sc) + '\n')
nlname = nls[nl]
savedif = False
if tname == 'N':
if delet:
addtoout(aname, 'N', nlname, ox, oy, z, chain, 1, 'D')
if inserts:
addtoout(aname, 'N', nlname, ox, oy, z, chain, 1, 'I')
else:
if dif and tname not in term:
tname = 'PT'
if dif and tname in term and tname[0] == 'T':
if not inserts and not delet:
tname = 'T'
else:
length = int(tname[1])
tname = 'T'
savedif = True
dif = findconnects(chain, z, a_sc, length, end)
if dif:
if tname not in term:
tname = 'PT'
if tname in term and tname[0] == 'T':
tname = 'T'
if z in inserts:
M = 'I'
elif z in delet:
M = 'D'
else:
M = None
addtoout(aname, tname, nlname, ox, oy, z, chain, 1, M)
for i in range(1, length):
if z + i * k in inserts:
M = 'I'
elif z + i * k in delet:
M = 'D'
else:
M = None
addtoout(aname, 'N', nlname, ox, oy, z + i * k, chain, 1, M)
elif inserts or delet:
if not instype:
if tname not in term:
tname = 'PT'
if tname in term and tname[0] == 'T':
tname = 'T'
if z in inserts:
M = 'I'
elif z in delet:
M = 'D'
else:
M = None
if length > 1:
addtoout(aname, tname, nlname, ox, oy, z, chain, length, M)
elif M:
addtoout(aname, tname, nlname, ox, oy,
z, chain, length, M + 'e') # first insert
else:
addtoout(
aname, tname, nlname, ox, oy, z, chain, length, None)
for i in range(1, length):
if z + i * k in inserts:
M = 'I'
elif z + i * k in delet:
M = 'D'
else:
M = None
addtoout(
aname, 'N', nlname, ox, oy, z + i * k, chain, 1, M)
dif = True
else:
if not savedif:
length = count[tname]
if z in delet and tname == 'T1':
raise Exception(
'USER: Deletion at terminal base pair') # because of T1
MT = 'D'
if z in inserts:
MT = 'I'
else:
MT = None
if instype == 't':
addtoout(aname, 'T', nlname, ox, oy, z, chain, length, MT)
for i in range(1, length):
M = None
if z + i * k in inserts:
M = 'I'
elif z + i * k in delet:
M = 'D'
addtoout(
aname, 'N', nlname, ox, oy, z + i * k, chain, 1, M)
else:
for i in range(1, length):
M = None
if z + (i - length) * k in inserts:
M = 'I'
elif z + (i - length) * k in delet:
M = 'D'
addtoout(aname, 'N', nlname, ox, oy, z + (
i - length) * k, chain, 1, M)
if MT:
addtoout(
aname, 'T', nlname, ox, oy, z,
chain, length, MT + 'e')
else:
addtoout(
aname, 'T', nlname, ox, oy, z,
chain, 1, None) # !!!
else:
addtoout(aname, tname, nlname, ox, oy, z,
chain, length, None) # quite normal atom
def findtriples(base, coords):
(row, col) = base
res = []
cpair = [None, None]
rpair1 = [None, None]
rpair2 = [None, None]
rpair3 = [None, None]
rpair4 = [None, None]
if SQ:
for i, atom in enumerate(coords):
if atom == (row, col + 1):
cpair[0] = i
elif atom == (row, col + 2):
cpair[1] = i
elif atom == (row + 1, col):
rpair1[0] = i
elif atom == (row + 2, col):
rpair1[1] = i
else:
for i, atom in enumerate(coords):
if atom == (row, col + 1):
cpair[0] = i
elif atom == (row, col + 2):
cpair[1] = i
if (row + col) % 2:
if atom == (row + 1, col):
rpair3[0] = i
rpair4[0] = i
elif atom == (row + 1, col + 1):
rpair3[1] = i
elif atom == (row + 1, col - 1):
rpair4[1] = i
else:
if atom == (row, col + 1):
rpair1[0] = i
elif atom == (row + 1, col + 1):
rpair1[1] = i
elif atom == (row, col - 1):
rpair2[0] = i
elif atom == (row + 1, col - 1):
rpair2[1] = i
for pair in [cpair, rpair1, rpair2, rpair3, rpair4]:
if None not in pair:
res += [pair]
return res
# ------------- .json analysis ----------------
outpdb = []
outpdbc = []
outmap = []
try:
file = open(args.input, 'r')
lines = file.readlines()
stringl = ""
for line in lines:
stringl += line
obj = json.loads(stringl)
strands = obj["vstrands"]
name = obj["name"]
# create dictionaries (keyed by virtual helix #) of
# row/col, scaf array, stap array
vhToScaf = {}
vhToStap = {}
vhNums = []
Rows = {}
Cols = {}
trans = []
trans_sc = []
loop = {}
skip = {}
end5scaf = None
end3scaf = None
RCvh = {}
for strand in strands:
num = strand["num"]
if num in vhNums:
raise Exception("USER: Double strand names in json file")
vhNums.append(num)
Rows[num] = strand["row"]
Cols[num] = strand["col"]
scaf = strand["scaf"]
stap = strand["stap"]
vhToScaf[num] = scaf
vhToStap[num] = stap
loop[num] = strand["loop"]
skip[num] = strand["skip"]
RCvh[(strand["row"], strand["col"])] = num
scaf5 = []
scaf3 = []
coords = []
Path = {'scaf': {}, 'stap': {}}
ends5 = []
ends3 = []
allPath = {}
seqPath = {}
for vh in vhNums:
scafPath = []
stapPath = []
scaf = vhToScaf[vh]
# scaffold path
for i in range(len(scaf)):
base = scaf[i]
if (base[0] != vh) & (base[0] != -1):
scafPath.append(base[0])
trans_sc.append([[vh, base[0]]] + [[i, base[1]]])
if (base[2] != vh) & (base[2] != -1):
scafPath.append(base[2])
trans_sc.append([[vh, base[2]]] + [[i, base[3]]])
if (base[0] == vh) & (base[2] == vh):
scafPath.append(vh)
if (base[0] == -1) & (base[2] == -1):
scafPath.append('-')
if (base[0] == -1) & (base[2] == vh):
scafPath.append('e5')
end5scaf = [vh, i]
if (base[2] == -1) & (base[0] == vh):
scafPath.append('e3')
end3scaf = [vh, i]
Path['scaf'][vh] = scafPath
# staple path
stap = vhToStap[vh]
for i in range(len(stap)):
base = stap[i]
if (base[0] == -1) & (base[2] == vh):
stapPath.append('e5')
ends5.append([vh, i])
if (base[2] == -1) & (base[0] == vh):
stapPath.append('e3')
ends3.append([vh, i])
if (base[0] != vh) & (base[0] != -1):
stapPath.append(base[0])
trans.append([[vh, base[0]]] + [[i, base[1]]])
if (base[2] != vh) & (base[2] != -1):
stapPath.append(base[2])
trans.append([[vh, base[2]]] + [[i, base[3]]])
if (base[0] == vh) & (base[2] == vh):
stapPath.append(vh)
if (base[0] == -1) & (base[2] == -1):
stapPath.append('-')
# i = 0
# k = 0
# while i == 0 and k < len(stapPath):
# if stapPath[k] != '-':
# i = 1
# k += 1
# if i == 1:
Path['stap'][vh] = stapPath
# join scaffold and staple
joinedPath = []
for i in range(len(scafPath)):
if (scafPath[i] == '-') & (stapPath[i] == '-'):
joinedPath.append('-')
elif (scafPath[i] != '-') & (stapPath[i] != '-'):
joinedPath.append('d')
elif (scafPath[i] != '-') & (stapPath[i] == '-'):
joinedPath.append('s')
else:
joinedPath.append('o')
allPath[vh] = joinedPath
seqPath[vh] = len(joinedPath) * ['-']
except Exception as e:
print(e)
raise Exception('USER: Error in input json file')
for v in allPath:
vh = allPath[v]
if 'o' in vh:
raise Exception('USER: Single-stranded staple')
# ------------- loop --------------
add = open(args.top, 'w')
insert = {}
deletion = {}
mapf = open(args.map, 'w')
for vh in loop:
for i, n in enumerate(loop[vh]):
if n != 0:
if n > 1:
raise Exception(
'USER: More than one base inserted in one place')
else:
insert[(vh, i)] = n
for vh in skip:
for i, n in enumerate(skip[vh]):
if n != 0:
if n > 1:
raise Exception(
'USER: More than one base deleted in one place')
else:
deletion[(vh, i)] = -1 * n
mapf.write('D ' + str(i) + ':' + str(vhNums.index(vh)) + '\n')
# add.write('D ' + str(i) + ';' + str((vh)) + '\n')
# ------------ lattice ------------
if args.lattice in ['h', 'hex', 'hexagonal']:
SQ = False
elif args.lattice in ['s', 'sq', 'square']:
SQ = True
else:
raise Exception('ADMIN: Wrong lattice type')
if SQ:
lim = 36 + 7
HC = 8
else:
lim = 21 + 6
HC = 7
# ------------- output files ----------
# ch = (Rows[0] + Cols[0]) % 2
# ---------------- end5 definition (if circular) ---------------
endtmp = True # indicator whether scaffold is circular
if not end5scaf:
if SQ:
dl = 36
else:
dl = 21 # length of duplex needed
k = min(vhNums)
end = 0
endtmp = False
while not end and k in allPath:
if (Rows[k] + Cols[k]) % 2:
c = len(allPath[k]) / 2
while not end and c < len(allPath[k]) - (dl - 1):
if allPath[k][c:c + dl] == ['d'] * dl:
end = c + dl / 2
else:
c += 1
c = len(allPath[k]) / 2 - 1
while not end and c >= 0:
if allPath[k][c:c + dl] == ['d'] * dl:
end = c + dl / 2
else:
c -= 1
if not end:
k += 1
else:
k += 1
end5scaf = [k, end - revers(k, 1)]
end3scaf = [k, end]
if not end:
p = min(vhNums)
while not end and p in allPath:
b = 1
while not end and b < len(Path['scaf'][p]):
if allPath[p][b - 1: b + 2] == ['d'] * 3:
end = True
end5scaf = [p, b]
end3scaf = [p, b + revers(p, 1)]
b += 1
p += 1
if not end:
raise Exception("ADMIN: PY1. 5'-end search error")
Path['scaf'][end5scaf[0]][end5scaf[1]] = 'e5'
Path['scaf'][end3scaf[0]][end3scaf[1]] = 'e3'
# ------------- sequence analysis/generation -------------
compl = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G',
'a': 'T', 't': 'A', 'g': 'C', 'c': 'G'}
if args.seq and args.oligs:
# Get sequence
seq = ''
try:
with open(args.seq, 'r') as f:
for line in f:
line = line.strip()
seq += line
last1 = False
last2 = False
except:
raise Exception('USER: Error in sequence input file')
for letter in seq:
if letter not in compl:
raise Exception('USER: Error in sequence input file')
try:
with open(args.oligs, 'r') as f:
for line in f:
if line[0] != 'S':
line = line.split(',')
line[0] = line[0].split('[')
line[1] = line[1].split('[')
if line[2][1] != '?':
seqPath[int(line[0][0])][
int(line[0][1][:-1])] = line[2][0]
if line[2][-1] != '?':
seqPath[int(line[1][0])][
int(line[1][1][:-1])] = line[2][-1]
except:
raise Exception('USER: Error in staple csv file')
for vh in seqPath:
for i in seqPath[vh]:
if i not in compl and i != '-':
raise Exception('USER: Error in staple csv file')
if endtmp:
add.write('seq: ' + seq + '\n')
if not checkseq(end5scaf[0], end5scaf[1]):
raise Exception('USER: Sequence does not match staple list')
else:
seq_end = None
[vh, base] = end5scaf
i = 0