-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorigami_utils.py
2656 lines (2302 loc) · 115 KB
/
origami_utils.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
"""
Utility functions for DNA origamis designed in cadnano and simulated in oxDNA.
origami_utils.py includes the class: Origami
"""
import base
try:
import numpy as np
except:
import mynumpy as np
import sys
import subprocess
import pickle
import os
import tempfile
PROCESSDIR = os.path.join(os.path.dirname(__file__), "process_data/")
def get_pos_midpoint(r1, r2, box):
"""
Returns the midpoint of two vectors r1 and r2.
Uses the minimum image: i.e. make sure we get a sensible answer if the
positions r1 and r2 correspond to nucleotides which were put at opposite
ends of the box due to periodic boundary conditions.
Args:
r1: first vector
r2: second vector
box: box dimensions in a numpy array
"""
assert (isinstance (box, np.ndarray) and len(box) == 3)
return r1 - min_distance(r1, r2, box)/2
def array_index(mylist, myarray):
"""
Returns the index in a list mylist of a numpy array myarray.
Args:
mylist: list
myarray: numpy array
"""
return map(lambda x: (myarray == x).all(), mylist).index(True)
def min_distance (r1, r2, box):
"""
Returns the minimum image distance in going from r1 to r2, in a box of size box.
Same as base.Nucleotide.distance().
Args:
r1: first vector
r2: second vector
box: box dimensions in a numpy array
"""
assert (isinstance (box, np.ndarray) and len(box) == 3)
dr = r2 - r1
dr -= box * np.rint (dr / box)
return dr
def vecs2spline(vecs, per):
"""
This function was not documented when it was written.
The author of this documentation believes that it returns a spline interpolating the given vectors.
Args:
vecs: list of vectors (arrays of length 3)
per: boolean. If true, forces spline to be periodic.
"""
import scipy.interpolate
# interpolate vecs by interpolating each cartesian co-ordinate in turn
xx = [vec[0] for vec in vecs]
yy = [vec[1] for vec in vecs]
zz = [vec[2] for vec in vecs]
# NB s = 0 forces interpolation through all data points
spline_xx = scipy.interpolate.splrep(range(len(xx)), xx, k = 3, s = 0, per = per)
spline_yy = scipy.interpolate.splrep(range(len(yy)), yy, k = 3, s = 0, per = per)
spline_zz = scipy.interpolate.splrep(range(len(zz)), zz, k = 3, s = 0, per = per)
return [spline_xx, spline_yy, spline_zz], (0, len(xx)-1)
def get_base_spline(strand, reverse = False):
"""
Returns a cartesian spline that represents a fit through the bases for the strand 'strand'.
Args:
strand: base.Strand object
reverse: boolean. If true, strand is reversed
"""
import scipy
base_pos = []
for nuc in strand._nucleotides:
base_pos.append(nuc.get_pos_base())
if reverse:
base_pos.reverse()
if strand._circular:
if reverse:
base_pos.append(strand._nucleotides[-1].get_pos_base())
else:
base_pos.append(strand._nucleotides[0].get_pos_base())
# interpolate bbms by interpolating each cartesian co-ordinate in turn
xx = [vec[0] for vec in base_pos]
yy = [vec[1] for vec in base_pos]
zz = [vec[2] for vec in base_pos]
# NB s = 0 forces interpolation through all data points
spline_xx = scipy.interpolate.splrep(range(len(xx)), xx, k = 3, s = 0, per = strand._circular)
spline_yy = scipy.interpolate.splrep(range(len(yy)), yy, k = 3, s = 0, per = strand._circular)
spline_zz = scipy.interpolate.splrep(range(len(zz)), zz, k = 3, s = 0, per = strand._circular)
return [spline_xx, spline_yy, spline_zz], (0, len(xx)-1)
def get_sayar_twist(s1, s2, smin, smax, npoints = 1000, circular = False, integral_type = "simple"):
"""
Returns the twist for a given pair of spline fits, one through the bases of each strand.
From Sayar et al. Phys. Rev. E, 81, 041916 (2010)
Just need to integrate along the contour parameter s that is common to both splines.
We need the normalised tangent vector to the spline formed by
the midpoint of the two input splines t(s),
the normalised normal vector formed by the vectors between the splines u(s),
and the derivative of the normalised normal vector between the splines d/ds (u(s)).
NB, the normal u(s) vector should be orthogonal to the tangent vector t(s); we ensure this by using only the component orthogonal to t(s).
Using integral_type = 'simple' and npoints = 200, it will give a correct twist, or at least one that gives a conserved linking number when combined with get_sayar_writhe.
Args:
s1: list of 3 splines corresponding to 3-D spline through strand 1's bases (e.g. use get_base_spline())
s2: list of 3 splines corresponding to 3-D spline through strand 2's bases -- NB the splines should run in the same direction, i.e. one must reverse one of the splines if they come from get_base_spline (e.g. use get_base_spline(reverse = True))
smin: minimum value for s, which parameterises the splines
smax: maximum value for s, which parameterises the splines
npoints: number of points for the discrete integration
circular: boolean. If true, spline is circular.
integral_type: "simple"
"""
import scipy.interpolate
import scipy.integrate
s1xx, s1yy, s1zz = s1
s2xx, s2yy, s2zz = s2
# bpi is the base pair index parameter that common to both splines
bpi = np.linspace(smin, smax, npoints)
# find the midpoint between the input splines, as a function of base pair index
mxx = (scipy.interpolate.splev(bpi, s1xx) + scipy.interpolate.splev(bpi, s2xx)) / 2
myy = (scipy.interpolate.splev(bpi, s1yy) + scipy.interpolate.splev(bpi, s2yy)) / 2
mzz = (scipy.interpolate.splev(bpi, s1zz) + scipy.interpolate.splev(bpi, s2zz)) / 2
# contour_len[ii] is contour length along the midpoint curve of point ii
delta_s = [np.sqrt((mxx[ii+1]-mxx[ii])**2+(myy[ii+1]-myy[ii])**2+(mzz[ii+1]-mzz[ii])**2) for ii in range(len(bpi)-1)]
contour_len = np.cumsum(delta_s)
contour_len = np.insert(contour_len, 0, 0)
# ss is a linear sequence from first contour length element (which is 0) to last contour length element inclusive
ss = np.linspace(contour_len[0], contour_len[-1], npoints)
# get the midpoint spline as a function of contour length
msxx = scipy.interpolate.splrep(contour_len, mxx, k = 3, s = 0, per = circular)
msyy = scipy.interpolate.splrep(contour_len, myy, k = 3, s = 0, per = circular)
mszz = scipy.interpolate.splrep(contour_len, mzz, k = 3, s = 0, per = circular)
# find the tangent of the midpoint spline.
# the tangent t(s) is d/ds [r(s)], where r(s) = (mxx(s), myy(s), mzz(s)). So the tangent is t(s) = d/ds [r(s)] = (d/ds [mxx(s)], d/ds [myy(s)], d/ds [mzz(s)])
# get discrete array of normalised tangent vectors; __call__(xxx, 1) returns the first derivative
# the tangent vector is a unit vector
dmxx = scipy.interpolate.splev(ss, msxx, 1)
dmyy = scipy.interpolate.splev(ss, msyy, 1)
dmzz = scipy.interpolate.splev(ss, mszz, 1)
tt = range(len(ss))
for ii in range(len(ss)):
tt[ii] = np.array([dmxx[ii], dmyy[ii], dmzz[ii]])
# we also need the 'normal' vector u(s) which points between the base pairs. (or between the spline fits through the bases in this case)
# n.b. these uxx, uyy, uzz are not normalised
uxx_bpi = scipy.interpolate.splev(bpi, s2xx) - scipy.interpolate.splev(bpi, s1xx)
uyy_bpi = scipy.interpolate.splev(bpi, s2yy) - scipy.interpolate.splev(bpi, s1yy)
uzz_bpi = scipy.interpolate.splev(bpi, s2zz) - scipy.interpolate.splev(bpi, s1zz)
# get the normal vector spline as a function of contour length
suxx = scipy.interpolate.splrep(contour_len, uxx_bpi, k = 3, s = 0, per = circular)
suyy = scipy.interpolate.splrep(contour_len, uyy_bpi, k = 3, s = 0, per = circular)
suzz = scipy.interpolate.splrep(contour_len, uzz_bpi, k = 3, s = 0, per = circular)
# evaluate the normal vector spline as a function of contour length
uxx = scipy.interpolate.splev(ss, suxx)
uyy = scipy.interpolate.splev(ss, suyy)
uzz = scipy.interpolate.splev(ss, suzz)
uu = range(len(ss))
for ii in range(len(ss)):
uu[ii] = np.array([uxx[ii], uyy[ii], uzz[ii]])
uu[ii] = uu[ii] - np.dot(tt[ii], uu[ii]) * tt[ii]
# the normal vector should be normalised
uu[ii] = norm(uu[ii])
# and finally we need the derivatives of that vector u(s). It takes a bit of work to get a spline of the normalised version of u from the unnormalised one
nuxx = [vec[0] for vec in uu]
nuyy = [vec[1] for vec in uu]
nuzz = [vec[2] for vec in uu]
nusxx = scipy.interpolate.splrep(ss, nuxx, k = 3, s = 0, per = circular)
nusyy = scipy.interpolate.splrep(ss, nuyy, k = 3, s = 0, per = circular)
nuszz = scipy.interpolate.splrep(ss, nuzz, k = 3, s = 0, per = circular)
duxx = scipy.interpolate.splev(ss, nusxx, 1)
duyy = scipy.interpolate.splev(ss, nusyy, 1)
duzz = scipy.interpolate.splev(ss, nuszz, 1)
duu = range(len(ss))
for ii in range(len(ss)):
duu[ii] = np.array([duxx[ii], duyy[ii], duzz[ii]])
ds = float(contour_len[-1] - contour_len[0]) / (npoints - 1)
# do the integration w.r.t. s
if circular:
srange = range(len(ss)-1)
else:
srange = range(len(ss))
if integral_type == "simple":
integral = 0
for ii in srange:
#print np.dot(uu[ii], tt[ii])
triple_scalar_product = np.dot(tt[ii], np.cross(uu[ii], duu[ii]))
integral += triple_scalar_product * ds
elif integral_type == "quad":
assert False, "not currently supported; shouldn't be difficult to implement if wanted"
integral, err = scipy.integrate.quad(twist_integrand, ss[0], ss[-1], args = (msxx, msyy, mszz, nusxx, nusyy, nuszz), limit = 500)
print >> sys.stderr, "error estimate:", err
twist = integral/(2 * np.pi)
return twist
def get_sayar_writhe(splines1, smin, smax, splines2 = False, npoints = 1000, debug = False, circular = False, integral_type = "simple"):
"""
Returns the writhe for a 3D spline fit through a set of duplex midpoints.
From Sayar et al. Phys. Rev. E, 81, 041916 (2010).
Using integral_type = 'simple' and npoints = 200, it will give a correct writhe, or at least one that gives a conserved linking number when combined with get_sayar_twist.
Args:
splines1: list of 3 splines corresponding to either (if not splines2) a 3D spline through the duplex or (if splines2) strand 1's bases
smin: minimum value for s, which parameterises the splines
smax: maximum value for s, which parameterises the splines
splines2: optionally, (see splines1) list of 3 splines corresponding to a 3D spline through strand2's bases
npoints: number of points for the discrete integration
debug: print a load of debugging information
circular: boolean. If true, spline is circular.
integral_type: "simple"
"""
import scipy.integrate
# bpi is the base pair index parameter that common to both strands' splines
bpi = np.linspace(smin, smax, npoints)
## get midpoint splines sxx, syy, szz
if not splines2:
# splines1 is the midpoint 3D spline as a function of base pair index
sxx_bpi, syy_bpi, szz_bpi = splines1
xx_bpi = scipy.interpolate.splev(bpi, sxx_bpi)
yy_bpi = scipy.interpolate.splev(bpi, syy_bpi)
zz_bpi = scipy.interpolate.splev(bpi, szz_bpi)
else:
# take splines1 and splines2 to be the splines through the bases of each strand; in that case we need to find the midpoint here first
s1xx_bpi, s1yy_bpi, s1zz_bpi = splines1
s2xx_bpi, s2yy_bpi, s2zz_bpi = splines2
# find the midpoint as a function of base pair index between the input splines
xx_bpi = (scipy.interpolate.splev(bpi, s1xx_bpi) + scipy.interpolate.splev(bpi, s2xx_bpi)) / 2
yy_bpi = (scipy.interpolate.splev(bpi, s1yy_bpi) + scipy.interpolate.splev(bpi, s2yy_bpi)) / 2
zz_bpi = (scipy.interpolate.splev(bpi, s1zz_bpi) + scipy.interpolate.splev(bpi, s2zz_bpi)) / 2
# contour_len[ii] is contour length along the midpoint curve of point ii
delta_s = [np.sqrt((xx_bpi[ii+1]-xx_bpi[ii])**2+(yy_bpi[ii+1]-yy_bpi[ii])**2+(zz_bpi[ii+1]-zz_bpi[ii])**2) for ii in range(len(bpi)-1)]
contour_len = np.cumsum(delta_s)
contour_len = np.insert(contour_len, 0, 0)
# ss is a linear sequence from first contour length element (which is 0) to last contour length element inclusive
ss = np.linspace(contour_len[0], contour_len[-1], npoints)
sxx = scipy.interpolate.splrep(contour_len, xx_bpi, k = 3, s = 0, per = circular)
syy = scipy.interpolate.splrep(contour_len, yy_bpi, k = 3, s = 0, per = circular)
szz = scipy.interpolate.splrep(contour_len, zz_bpi, k = 3, s = 0, per = circular)
xx = scipy.interpolate.splev(ss, sxx)
yy = scipy.interpolate.splev(ss, syy)
zz = scipy.interpolate.splev(ss, szz)
# find the tangent of the midpoint spline.
# the tangent t(s) is d/ds [r(s)], where r(s) = (mxx(s), myy(s), mzz(s)). So the tangent is t(s) = d/ds [r(s)] = (d/ds [mxx(s)], d/ds [myy(s)], d/ds [mzz(s)])
# get discrete array of tangent vectors; __call__(xxx, 1) returns the first derivative
dxx = scipy.interpolate.splev(ss, sxx, 1)
dyy = scipy.interpolate.splev(ss, syy, 1)
dzz = scipy.interpolate.splev(ss, szz, 1)
tt = range(len(ss))
for ii in range(len(ss)):
tt[ii] = np.array([dxx[ii], dyy[ii], dzz[ii]])
# do the double integration w.r.t. s and s'
if integral_type == "simple":
integral = 0
if circular:
srange = range(len(ss)-1)
ds = float(contour_len[-1] - contour_len[0]) / (npoints - 1)
else:
srange = range(len(ss))
ds = float(contour_len[-1] - contour_len[0]) / npoints
for ii in srange:
for jj in srange:
# skip ii=jj and use symmetry in {ii, jj}
if ii > jj:
diff = np.array([xx[ii]-xx[jj], yy[ii] - yy[jj], zz[ii] - zz[jj]])
diff_mag = np.sqrt(np.dot(diff, diff))
diff_frac = diff / (diff_mag ** 3)
triple_scalar_product = np.dot(np.cross(tt[ii], tt[jj]), diff_frac)
integral += triple_scalar_product * ds * ds
# multiply by 2 because we exploited the symmetry in {ii, jj} to skip half of the integral
integral *= 2
elif integral_type == "dblquad":
# contour_len[0] to contour[-1] SHOULD be a complete integral on the closed curve; i.e. sxx(contour_len[0]) = sxx(contour_len[-1]) etc.
val, err = scipy.integrate.dblquad(writhe_integrand, ss[0], ss[-1], lambda x: ss[0], lambda x: ss[-1], args = (sxx, syy, szz, ss[-1]))
print >> sys.stderr, err
integral = val
elif integral_type == "chopped dblquad":
integral = 0
for ss_coarse in np.linspace(ss[0], ss[-1], 10):
for ss_coarse_prime in np.linspace(ss[0], ss[-1], 10):
val, err = scipy.integrate.dblquad(writhe_integrand, ss_coarse, ss_coarse + float(ss[-1]-ss[0])/9, lambda x: ss_coarse_prime, lambda x: ss_coarse_prime + float(ss[-1]-ss[0])/9, args = (sxx, syy, szz, contour_len[-1]))
print err
integral += val
elif integral_type == "quad":
integral, err = scipy.integrate.quad(writhe_integrand2, ss[0], ss[-1], args = (sxx, syy, szz, ss[0], ss[-1]), limit = 100, epsabs = 1e-5, epsrel = 0)
elif integral_type == "simps":
srange = range(len(ss))
integrand = [[] for ii in srange]
for ii in srange:
for jj in srange:
# skip ii=jj
if ii == jj:
triple_scalar_product = 0
else:
diff = np.array([xx[ii]-xx[jj], yy[ii] - yy[jj], zz[ii] - zz[jj]])
diff_mag = np.sqrt(np.dot(diff, diff))
diff_frac = diff / (diff_mag ** 3)
triple_scalar_product = np.dot(np.cross(tt[ii], tt[jj]), diff_frac)
integrand[ii].append(triple_scalar_product)
integral = scipy.integrate.simps(scipy.integrate.simps(integrand, ss), ss)
else:
assert False
writhe = float(integral) / (4*np.pi)
return writhe
def get_vhelix_vis(fname):
"""
Reads the 'virtual helix visibility' from a text file and ignore any virtual helices set to invisible.
The syntax is the same as for the base.py visibility.
Modified from the base.py strand visibility parsing.
Args:
fname: path to visibility file
"""
actions = {'vis' : True, 'inv' : False}
visibility_list = []
path = fname
try:
inp = open (path, 'r')
except:
base.Logger.log ("Origami visibility file `" + path + "' not found. Assuming default visibility", base.Logger.INFO)
return False
base.Logger.log("Using origami visibility file " +path, base.Logger.INFO)
# read the visibility from a file; if we got here the file was opened
lines = []
for line in inp.readlines():
line = line.strip().lower()
# remove everything that comes after '#'
line = line.split('#')[0]
if len(line) > 0: lines.append(line)
for line in lines:
if '=' in line:
sp = line.split("=")
one, two, three = [p.strip() for p in sp[0], '=', sp[1]]
else:
one, two, three = line, "", ""
if two != '=':
base.Logger.log ("Lines in visibility must begin with one of inv=, vis= and default=. Skipping this line: --" + line + "--", base.Logger.WARNING)
continue
if one == 'default':
if three not in ['inv', 'vis']:
base.Logger.log ("Wrong default in visibility file. Assuming visible as default", base.Logger.WARNING)
three = 'vis'
if three == 'inv':
mode = 'inv'
else:
mode = 'vis'
else:
# filter removes all the empty strings
arr = [a.strip() for a in filter(None, three.split(','))]
for a in arr:
try:
ind = int(a)
except:
base.Logger.log ("Could not cast '%s' to int. Assuming 0" % a, base.Logger.WARNING)
ind = 0
try:
visibility_list.append(ind)
except:
base.Logger.log ("vhelix %i does not exist in system, cannot assign visibility. Ignoring" % ind, base.Logger.WARNING)
return mode, visibility_list
def norm(vec):
"""
Returns a normalised vector.
Args:
vec: vector
"""
return vec / np.sqrt(np.dot(vec,vec))
def parse_scanfile(infile):
"""
This function was not documented when it was written.
The author of this documentation believes that it parses a "scan file", the format and purpose of which is unclear.
Args:
infile: path to scan file
"""
try:
f = open(infile, "r")
except IOError:
base.Logger.log("could not open file %s" % infile, base.Logger.CRITICAL)
sys.exit()
for line in f.readlines():
if line.startswith('begin_vb'):
begin_vb = int(line.split()[2])
elif line.startswith('end_vb'):
end_vb = int(line.split()[2])
elif line.startswith('vh_list'):
vh_list = [int(x) for x in (line.split()[2]).split(",")]
elif line.startswith('trim'):
trim = int(line.split()[2])
try:
return begin_vb, end_vb, vh_list, trim
except NameError:
base.Logger.log("error while reading scan file %s, dying now" % infile, base.Logger.CRITICAL)
sys.exit()
def get_scaffold_index(system):
"""
Returns the index of the scaffold strand in the system.
Args:
system: base.System object. Can be obtained from readers.LorenzoReader.get_system.
"""
strand_lengths = [strand.get_length() for strand in system._strands]
return strand_lengths.index(max(strand_lengths))
def get_bb_midpoint(system, strand, n_index, interaction_list):
"""
Deprecated function, use origami_utils.Origami.get_bb_midpoint instead.
Returns the midpoint vector between 2 hybridised bases.
"""
base.Logger.log("origami_utils.get_bb_midpoint: deprecated function, use origami_utils.Origami.get_bb_midpoint", base.Logger.WARNING)
r1 = strand._nucleotides[n_index].get_pos_base()
r2 = system._nucleotides[interaction_list[strand._nucleotides[n_index].index]].get_pos_base()
vec = (r1+r2)/2
return vec
def get_nucleotide(vhelix, vbase, vhelix_indices):
"""
Deprecated function, use origami_utils.Origami.get_nucleotides instead.
Returns the system nucleotide index of a nucleotide given a position on the origami.
"""
if vhelix % 2 == 0:
dir = 1
else:
dir = -1
return vhelix_indices[vhelix] + vbase * dir
def parse_vh_data(filename, origami):
"""
Gets vhelices data from file - format is either <auto,[number of vhelices]>,
or, if a region of an origami is to be analysed,
<[region width],[list of starting nucleotide index for the region for each vhelix]>.
Args:
filename: path to vhelix data file
origami: origami_utils.Origami object
"""
scaf_index = get_scaffold_index(origami._sys)
vhelix_def_file = open(filename, "r")
data = [x for x in vhelix_def_file.readline().replace("\n","").replace(" ","").split(",")]
if data[0] == "auto":
origami.num_vh = int(data[1])
origami.width = origami._sys._strands[scaf_index].get_length() / origami.num_vh
origami.vhelix_indices = []
start_nuc_ind = -1
for i in range(origami.num_vh):
if i % 2 == 0:
start_nuc_ind += 1
else:
start_nuc_ind += origami.width*2 - 1
origami.vhelix_indices.append(start_nuc_ind)
else:
origami.width = int(data[0])
origami.vhelix_indices = [int(x) for x in data[1:]]
origami.num_vh = len(origami.vhelix_indices)
base.Logger.log("using file data.vhd, %d virtual helices found" % origami.num_vh, base.Logger.INFO)
def print_arrow_debug_line(begin, end, file):
"""
This function was not documented when it was written.
The author of this documentation believes that it is a debugging function for VMD.
"""
if file:
file.write("draw arrow {%f %f %f} {%f %f %f}\n" % (begin[0], begin[1], begin[2], end[0], end[1], end[2]))
return 0
def open_arrow_debug_file(filename, type="w"):
"""
This function was not documented when it was written.
The author of this documentation believes that it is a debugging function for VMD.
"""
f_arrow = open(filename, type)
f_arrow.write(
"color Display Background white\n" +
"set mName [mol new]\n" +
"proc vmd_draw_arrow {mol start end} {\n" +
"# an arrow is made of a cylinder and a cone\n"
"set middle [vecadd $start [vecscale 0.65 [vecsub $end $start]]]\n" +
"graphics $mol cylinder $start $middle radius 0.05\n" +
"graphics $mol cone $middle $end radius 0.15\n" +
"}\n")
return f_arrow
def print_box_debug_line(vecs, file):
"""
This function was not documented when it was written.
The author of this documentation believes that it is a debugging function for VMD.
"""
if file:
if len(vecs) == 4:
file.write("draw box {%f %f %f} {%f %f %f} {%f %f %f} {%f %f %f}\n" % (vecs[0][0], vecs[0][1], vecs[0][2], vecs[1][0], vecs[1][1], vecs[1][2], vecs[2][0], vecs[2][1], vecs[2][2], vecs[3][0], vecs[3][1], vecs[3][2]))
else:
base.Logger.log("drawing boxes only works for 4 vertices at the moment", base.Logger.WARNING)
def open_box_debug_file(filename):
"""
This function was not documented when it was written.
The author of this documentation believes that it is a debugging function for VMD.
"""
f_boxes = open(filename, "w")
f_boxes.write(
"color Display Background white\n" +
"set mName [mol new]\n" +
"proc vmd_draw_box {mol vert1 vert2 vert3 vert4} {\n" +
"# a 'box' is a plane made of 2 triangles here\n" +
"graphics $mol triangle $vert1 $vert2 $vert3\n" +
"graphics $mol triangle $vert1 $vert4 $vert3\n" +
"}\n")
return f_boxes
def angle_sense(v1, v2, axis):
"""
Returns the angle between two vectors, using a 3rd vector to determine the sense of the angle.
Args:
v1: first vector
v2: second vector
axis: third vector
"""
v1 = norm(v1)
v2 = norm(v2)
axis = norm(axis)
angle = np.arccos(np.dot(v1,v2))
if np.dot(norm(np.cross(v1,v2)),axis) < 0:
angle *= -1 # attempt to check the 'sense' of the angle w.r.t. an axis
return angle
def dihedral_angle_sense(v1, v2, axis, sanity_check = False):
"""
Returns the dihedral angle between two vectors, using a 3rd vector to determine the sense of the angle
and to define the axis normal to the plane we want the vectors in
Args:
v1: first vector
v2: second vector
axis: third vector
sanity_check: boolean. If true, check whether v1 and v2 are not too parallel to the axis, and returns false if either of them is.
"""
v1n = norm(v1)
v2n = norm(v2)
axis = norm(axis)
if sanity_check and (abs(np.dot(v1n,axis)) > 0.6 or abs(np.dot(v2n,axis)) > 0.6):
return False
# in plane
v1p = v1n - np.dot(v1n,axis)*axis
v2p = v2n - np.dot(v2n,axis)*axis
v1p = norm(v1p)
v2p = norm(v2p)
angle = np.arccos(np.dot(v1p,v2p))
if np.dot(norm(np.cross(v1p,v2p)),axis) < 0:
angle *= -1 # attempt to check the 'sense' of the angle w.r.t. an axis
return angle
class vhelix_vbase_to_nucleotide(object):
# at the moment squares with skips in have entries in the dicts but with the nucleotide list empty (rather than having no entry) - I'm not sure whether or not this is desirable. It's probably ok
def __init__(self):
self._scaf = {}
self._stap = {}
self.nuc_count = 0 # record the nucleotide count, updated only after a whole strand is added
self.strand_count = 0
def add_scaf(self, vh, vb, strand, nuc):
self._scaf[(vh, vb)] = (strand, nuc)
def add_stap(self, vh, vb, strand, nuc):
self._stap[(vh, vb)] = (strand, nuc)
# these methods use a reference vhvb2n object to make the final vhvb2n object
def add_scaf_strand(self, add_strand, reference, continue_join = False):
count = 0
size = len(self._scaf)
for (vh, vb), [strand_ind, nuc] in reference._scaf.iteritems():
if strand_ind == add_strand:
self.add_scaf(vh, vb, self.strand_count, [x + self.nuc_count for x in nuc])
count += len(nuc)
self.nuc_count += count
if len(self._scaf) == size:
return 1
else:
if continue_join == False:
self.strand_count += 1
return 0
def add_stap_strand(self, add_strand, reference, continue_join = False):
count = 0
size = len(self._stap)
for (vh, vb), [strand_ind, nuc] in reference._stap.iteritems():
if strand_ind == add_strand:
self.add_stap(vh, vb, self.strand_count, [x + self.nuc_count for x in nuc])
count += len(nuc)
self.nuc_count += count
if len(self._stap) == size:
return 1
else:
if continue_join == False:
self.strand_count += 1
return 0
def add_strand(self, add_strand, reference, continue_join = False):
if self.add_scaf_strand(add_strand, reference, continue_join) and self.add_stap_strand(add_strand, reference, continue_join):
#base.Logger.log("while adding strand %s to vhelix_vbase_to_nucleotide object; either strand already present or strand not found in reference object" % add_strand, base.Logger.WARNING)
return 1
else:
return 0
class Origami(object):
"""
Origami object.
Args:
system: base.System object. Can be obtained from readers.LorenzoReader.get_system
cad2cuda_file: path to virt2nuc file. Can be obtained from cadnano_interface.py
visibility: path to visibility file
"""
def __init__(self, system=False, cad2cuda_file = False, visibility = False):
self.width = 0
self.num_vh = 0
if not system:
base.Logger.log("origami_utils: Origami.__init__: system is False, this is no longer supported", base.Logger.CRITICAL)
sys.exit(1)
self._sys = system
self.interaction_list = [-1 for x in range(self._sys._N)]
self.vhelix_indices = []
self.vbase_indices = []
self.vec_long = np.array([0., 0., 0.])
self.vec_lat = np.array([0., 0., 0.])
self._vhelix_pattern = False
self.vh_midpoints = []
if cad2cuda_file:
self.get_cad2cudadna(cad2cuda_file, visibility = visibility)
# build list of complementary nucleotides (according to cadnano scheme)
self.complementary_list = ["na" for x in range(self._sys._N)]
for (vhelix, vbase), (strand1, nucs1) in self._cad2cudadna._scaf.iteritems():
try:
(strand2, nucs2) = self._cad2cudadna._stap[vhelix, vbase]
for i in range(len(nucs1)):
# I'm pretty sure these should always line up for any possible insertion/deletion scheme
self.complementary_list[nucs1[i]] = nucs2[i]
self.complementary_list[nucs2[i]] = nucs1[i]
except KeyError:
pass
# build a list of the vhelix indices contained in the cadnano design
self.vhelix_indices = sorted(list(set([key[0] for key in self._cad2cudadna._scaf.keys()] + [key[0] for key in self._cad2cudadna._stap.keys()])))
if len(self.vhelix_indices) == 0:
print >> sys.stderr, "WARNING: vhelix_indices member variable list is empty, this probably means the virt2nuc file you are using is out of date"
self.vbase_indices = sorted(list(set([key[1] for key in self._cad2cudadna._scaf.keys()] + [key[1] for key in self._cad2cudadna._stap.keys()])))
# build a list of the occupied virtual bases in each virtual helix
self.vh_vbase_indices = [[] for x in self.vhelix_indices]
self.vh_vbase_indices_scaf = [[] for x in self.vhelix_indices]
self.vh_vbase_indices_stap = [[] for x in self.vhelix_indices]
self.vvib = [[] for x in self.vhelix_indices] # vhelix_vbase_indices_both
# scaffold vbase occupation
for (vh, vb) in iter(self._cad2cudadna._scaf):
self.vh_vbase_indices_scaf[self.vhelix_indices.index(vh)].append(vb)
for row in self.vh_vbase_indices_scaf:
row.sort()
# staples vbase occupation
for (vh, vb) in iter(self._cad2cudadna._stap):
self.vh_vbase_indices_stap[self.vhelix_indices.index(vh)].append(vb)
for row in self.vh_vbase_indices_stap:
row.sort()
# occupation of both staple and scaffold strand
for vhi in range(len(self.vh_vbase_indices_scaf)):
for vb_scaf in self.vh_vbase_indices_scaf[vhi]:
if vb_scaf in self.vh_vbase_indices_stap[vhi]:
self.vvib[vhi].append(vb_scaf)
for row in self.vvib:
row.sort()
# occupation of either staple or scaffold strand
for vhi in range(len(self.vh_vbase_indices_scaf)):
for vb_scaf in self.vh_vbase_indices_scaf[vhi]:
if vb_scaf not in self.vh_vbase_indices[vhi]:
self.vh_vbase_indices[vhi].append(vb_scaf)
for vb_stap in self.vh_vbase_indices_stap[vhi]:
if vb_stap not in self.vh_vbase_indices[vhi]:
self.vh_vbase_indices[vhi].append(vb_stap)
for row in self.vh_vbase_indices:
row.sort()
# nicer aliases
self.vvi = self.vh_vbase_indices
self.vvisc = self.vh_vbase_indices_scaf
self.vvist = self.vh_vbase_indices_stap
self.num_vh = len(self.vhelix_indices)
self.scaf_index = get_scaffold_index(self._sys)
# self.width = self._sys._strands[scaf_index].get_length() / self.num_vh
# if self.width != len(self.vbase_indices):
# pass #this warning got annoying base.Logger.log("not a rectangular origami!", base.Logger.WARNING)
else:
self._cad2cudadna = {}
# print self.vvib[0]
# for ii in self.vvib[0]:
# print self._cad2cudadna._stap[0,ii]
# exit(1)
def update_system(self, system):
"""
This function was not documented when it was written.
The author of this documentation believes that it updates the system of the origami object.
Args:
system: base.System object. Can be obtained from readers.LorenzoReader.get_system
"""
self._sys = system
def get_corners(self):
"""
This function was not documented when it was written.
The author of this documentation believes that it returns the indices of the nucleotides in the four corners of the origami.
"""
if self._cad2cudadna == {}:
base.Logger.log("get_corners: build cad2cudadna property first", base.Logger.CRITICAL)
sys.exit()
# make sure that neighbours in the list are neighbours in the origami
a = self.get_nucleotides(self.vhelix_indices[0],self.vh_vbase_indices[0][0])[0]
b = self.get_nucleotides(self.vhelix_indices[0],self.vh_vbase_indices[0][-1])[0]
c = self.get_nucleotides(self.vhelix_indices[-1],self.vh_vbase_indices[-1][-1])[0]
d = self.get_nucleotides(self.vhelix_indices[-1],self.vh_vbase_indices[-1][0])[0]
return [a, b, c, d]
def get_nucleotides(self, vhelix, vbase, type="default"):
"""
Given a cadnano virtual helix index and a virtual base index, returns the nucleotide index
Args:
vhelix: virtual helix index in cadnano
vbase: virtual base index in cadnano
type: "scaf" for scaffold, "stap" for staple, "double" for both
"""
if self._cad2cudadna:
if type == "default" or type == "single":
try:
strand, nucs = self._cad2cudadna._scaf[(vhelix, vbase)]
except KeyError:
strand, nucs = self._cad2cudadna._stap[(vhelix, vbase)]
return nucs
elif type == "scaf":
try:
strand, nucs = self._cad2cudadna._scaf[(vhelix, vbase)]
except KeyError:
nucs = []
return nucs
elif type == "stap":
try:
strand, nucs = self._cad2cudadna._stap[(vhelix, vbase)]
except KeyError:
nucs = []
return nucs
elif type == "double":
# return double strands
strand, nucs1 = self._cad2cudadna._scaf[(vhelix, vbase)]
strand, nucs2 = self._cad2cudadna._stap[(vhelix, vbase)]
nucs = []
nucs.extend(nucs1)
nucs.extend(nucs2)
return nucs
else:
base.Logger.log("no cadnano to cudadna file detected, using old and possibly wrong get_nucleotides function", base.Logger.WARNING)
# find the system nucleotide index of a nucleotide given a position on the origami
if vhelix % 2 == 0:
dir = 1
else:
dir = -1
return self.vhelix_indices[vhelix] + vbase * dir
def get_vhelix_ds_length(self, vhi):
"""
Returns length of double helix. Requires one continuous double strand - otherwise how is double strand length defined?
Args:
vhi: virtual helix index in self.vhelix_indices
"""
nucleotide_count = 0
for vb in self.vvib[vhi]:
try:
nucs = self.get_nucleotides(self.vhelix_indices[vhi], vb, type="double")
except KeyError:
continue
for nuc in nucs:
nucleotide_count += 1
return nucleotide_count/2
def get_flat_nucs(self, vh):
"""
This function was not documented when it was written.
The author of this documentation believes that it returns a list of nucleotides in a given virtual helix.
Args:
vh: virtual helix index in cadnano
"""
vhi = self.vhelix_indices.index(vh)
nucs_flat = []
iterable = self.vh_vbase_indices[vhi]
for vb in iterable:
try:
nucs = self.get_nucleotides(vh, vb)
except:
continue #pass
nucs_flat.extend(nucs)
return nucs_flat
def vb2nuci(self, vhi, vb0):
"""
This function was not documented when it was written.
The author of this documentation believes that it returns the number of nucleotides corresponding to a given virtual helix and virtual base.
It is not always 1 because of insertions/deletions.
Args:
vhi: virtual helix index in self.vhelix_indices
vb0: virtual base index in cadnano (maybe, the author is not sure)
"""
vh = self.vhelix_indices[vhi]
nucs_count = []
vbi = self.vvib[vhi].index(vb0)
iterable = self.vvib[vhi][:vbi]
for vb in iterable:
try:
nucs = self.get_nucleotides(vh,vb)
except:
continue
nucs_count.extend(nucs)
return len(nucs_count)
def vb2vhelix_nucid(self, vh, vb, vb_nuci, mode='default'):
"""
Given a virtual helix, a virtual base, and a nucleotide id for that virtual base,
returns the index of that nucleotide in a scheme where the leftmost (lowest virtual base index) nucleotide has index 0 and all nucleotides are given a unique integer index.
Args:
vh: virtual helix index in cadnano
vb: virtual base index in cadnano
vb_nuci: index of particular nucleotide in the virtual base (if the virtual base does not have a loop there is always exactly one nucleotide, which has index 0)
mode: gets given to get_nucleotides as type; 'default' will count a vb that has either a scaffold or staple strand, while 'double' will only count vbs that have both a scaffold and staple strand.
"""
vhi = self.vhelix_indices.index(vh)
nucs_count = 0
this_vb = self.vvib[vhi][0]
# loop over all virtual bases, adding up the number of nucleotides for each virtual base, until we get to the virtual base of interest
while this_vb < vb:
nucs_count += len(self.get_nucleotides(vh, this_vb, type=mode))
this_vb += 1
# this line may look pointless, but it allows correct behaviour even if vb_nuci is -1
last_vb_nuc_index = self.get_nucleotides(vh, this_vb, type=mode).index(self.get_nucleotides(vh, this_vb, type=mode)[vb_nuci])
# add the virtual-base-nucleotide-index of the last virtual base to our running total to get the final result
vhelix_nucid = nucs_count + last_vb_nuc_index
return vhelix_nucid
def prepare_principal_axes_calc():
"""
Unsupported function. Do not use.
"""
com = np.array([0.,0.,0.])
for nuc in self._sys._nucleotides:
com += nuc.cm_pos
com /= self._sys._N
displ = range(self._sys._N)
for ii in range(self._sys._N):
rr = self._sys._nucleotides[ii].cm_pos - com
displ[ii] = np.dot(rr,rr)
minnuc = displ.index(min(displ))
self._sys.map_nucleotides_to_strands()
if minnuc+1 < self._sys._N and self._sys._nucleotide_to_strand[minnuc] == self._sys._nucleotide_to_strand[minnuc+1]:
minnucs = (minnuc, minnuc+1)
elif minnuc > 0 and self._sys._nucleotide_to_strand[minnuc] == self._sys._nucleotide_to_strand[minnuc-1]:
minnucs = (minnuc, minnuc-1)
else:
base.Logger.die("something went wrong when trying to find the reference nucleotides for the principal axes calculation")
return minnucs
def get_principal_axes(self, approxaxes, minnucs):
"""
Unsupported function. Do not use.
"""
print "origami_utils.py: Origami.get_principal_axes: unsupported function, dying"
sys.exit()
# find moment of inertia tensor I, then eigenvectors are the principal axes
# first get centre of mass
com = np.array([0.,0.,0.])
for nuc in self._sys._nucleotides:
com += nuc.cm_pos
com /= self._sys._N
# get global rotation, the rotation to ensure that a particular vector always lies on [1,0,0] for every configuration
vecref = norm(self._sys._nucleotides[minnucs[0]].cm_pos - self._sys._nucleotides[minnucs[1]].cm_pos)
globalrotcg = 0#mat3().fromToRotation([vecref[0], vecref[1], vecref[2]], [1.,0.,0.])
globalrot = np.array([np.zeros(3),np.zeros(3),np.zeros(3)])
# convert to numpy array
for ii in range(3):
for jj in range(3):
globalrot[ii][jj] = globalrotcg[ii][jj]
# find I wrt centre of mass
I = np.array([[0.,0.,0.],[0.,0.,0.],[0.,0.,0.]])
for nuc in self._sys._nucleotides:
# rotate system so that vecref along x axis
rk = np.dot(globalrot,(nuc.cm_pos - com))
I[0,0] += rk[1]*rk[1] + rk[2]*rk[2]
I[1,1] += rk[0]*rk[0] + rk[2]*rk[2]
I[2,2] += rk[0]*rk[0] + rk[1]*rk[1]
I[0,1] -= rk[0]*rk[1]
I[0,2] -= rk[0]*rk[2]
I[1,2] -= rk[1]*rk[2]
I[1,0] -= rk[0]*rk[1]
I[2,0] -= rk[0]*rk[2]
I[2,1] -= rk[1]*rk[2]
eigvals, eigvecs = np.linalg.eig(I)
# order eigenvectors by size of eigenvalue
i1 = np.where(eigvals == max(eigvals))[0][0]
i3 = np.where(eigvals == min(eigvals))[0][0]
i2 = 3 - i1 - i3
v1 = eigvecs[:,i1]
v2 = eigvecs[:,i2]
v3 = eigvecs[:,i3]
# order eigenvectors by how much they overlap with the approximate axes
eigvecsl = [eigvecs[:,i] for i in range(len(eigvecs))] # make a list of 1d arrays from a 2d array
eigvecs_ordered = []
for ii in range(len(approxaxes)):
res = range(len(eigvecsl))