-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.py
1861 lines (1547 loc) · 73.1 KB
/
base.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 oxDNA systems, strands and nucleotides.
base.py includes the classes: System, Strand, Nucleotide
"""
import sys, os
try:
import numpy as np
except:
import mynumpy as np
def partition(s, d):
if d in s:
sp = s.split(d, 1)
return sp[0], d, sp[1]
else:
return s, "", ""
# every defined macro in model.h must be imported in this module
def import_model_constants():
PI = np.pi
model = os.path.join(os.path.dirname(__file__), "./model.h")
f = open(model)
for line in f.readlines():
# line = line.strip().partition("//")[0].strip()
line = (partition (line.strip (), "//")[0]).strip ()
#macro = line.partition("#define ")[2].strip().split(" ", 1)
macro = (partition (line, "#define ")[2]).strip().split(" ", 1)
if len(macro) > 1:
key, val = [x.strip() for x in macro]
# the f needed by c to interpret numbers as floats must be removed
# this could be a source of bugs
val = val.replace("f", "")
# this awful exec is needed in order to get the right results out of macro definitions
exec "tmp = %s" % (val)
globals()[key] = tmp
f.close()
# if you are using the oxRNA model, then environmental variable RNA has to be set to 1. base.py then uses the constants defined in rna_model.h
def import_rna_model_constants():
PI = np.pi
model = os.path.join(os.path.dirname(__file__), "../src/Interactions/rna_model.h")
f = open(model)
for line in f.readlines():
# line = line.strip().partition("//")[0].strip()
line = (partition (line.strip (), "//")[0]).strip ()
#macro = line.partition("#define ")[2].strip().split(" ", 1)
if ('=' in line) and (not "float" in line ) and (not "KEY_FOUND" in line ) and (not 'NULL' in line) and (not 'fopen' in line):
macro = line.strip().split('=')
#macro = (partition (line, "=")[2]).strip().split(" ", 1)
if len(macro) > 1:
key, val = [x.strip() for x in macro]
# the f needed by c to interpret numbers as floats must be removed
# this could be a source of bugs
val = val.replace("f", "")
val = val.replace(";","")
# this awful exec is needed in order to get the right results out of macro definitions
#print 'Importing ',key,val
exec "tmp = %s" % (val)
globals()[key] = tmp
f.close()
import_model_constants()
number_to_base = {0 : 'A', 1 : 'G', 2 : 'C', 3 : 'T'}
base_to_number = {'A' : 0, 'a' : 0, 'G' : 1, 'g' : 1,
'C' : 2, 'c' : 2, 'T' : 3, 't' : 3,
'U' : 3, 'u' : 3, 'D' : 4}
RNA_ENV_VAR = "OXRNA"
if os.environ.get(RNA_ENV_VAR) == '1':
RNA=True
else:
RNA=False
if RNA:
import_rna_model_constants()
number_to_base = {0 : 'A', 1 : 'G', 2 : 'C', 3 : 'U'}
try:
FLT_EPSILON = np.finfo(np.float).eps
except:
FLT_EPSILON = 2.2204460492503131e-16
CM_CENTER_DS = POS_BASE + 0.2
OUT_TOM = 0
OUT_LORENZO = 1
OUT_VMD = 2
OUT_CREPY = 3
OUT_VMD_XYZ = 4
OUT_TEP_VMD_XYZ = 5
LENGTH_FACT = 8.518
BASE_BASE = 0.3897628551303122
RC2_BACK = EXCL_RC1**2
RC2_BASE = EXCL_RC2**2
RC2_BACK_BASE = EXCL_RC3**2
CREPY_COLOR_TABLE = ['red', 'blue', '0,0.502,0', '1,0.8,0', '0.2,0.8,1']
VMD_ELEMENT_TABLE = ['C', 'S', 'N', 'P', 'K', 'F', 'Si']
#INT_POT_TOTAL = 0
INT_HYDR = 4
INT_STACK = 2
INT_CROSS_STACK = 5
INT_COAX_STACK = 6
INT_FENE = 0
INT_EXC_BONDED = 1
INT_EXC_NONBONDED = 3
#H_CUTOFF = -0.5
H_CUTOFF = -0.1
GROOVE_ENV_VAR = "OXDNA_GROOVE"
if os.environ.get(GROOVE_ENV_VAR) == '1':
MM_GROOVING=True
else:
MM_GROOVING=False
# static class
class Logger(object):
debug_level = None
DEBUG = 0
INFO = 1
WARNING = 2
CRITICAL = 3
messages = ("DEBUG", "INFO", "WARNING", "CRITICAL")
@staticmethod
def log(msg, level=None, additional=None):
if level == None:
level = Logger.INFO
if level < Logger.debug_level:
return
if additional != None and Logger.debug_level == Logger.DEBUG:
print >> sys.stderr, "%s: %s (additional info: '%s')" % (Logger.messages[level], msg, additional)
else: print >> sys.stderr, "%s: %s" % (Logger.messages[level], msg)
@staticmethod
def die(msg):
Logger.log(msg, Logger.CRITICAL)
sys.exit()
class Printable(object):
def __init__(self):
self._output_callables = {OUT_TOM : self._get_tom_output,
OUT_LORENZO : self._get_lorenzo_output,
OUT_VMD : self._get_vmd_output,
OUT_CREPY : self._get_crepy_output,
OUT_VMD_XYZ : self._get_vmd_xyz_output,
OUT_TEP_VMD_XYZ : self._get_TEP_vmd_xyz_output
}
def get_output(self, type):
return self._output_callables[type]()
def _get_tom_output(self):
raise NotImplementedError
def _get_lorenzo_output(self):
raise NotImplementedError
def _get_vmd_output(self):
raise NotImplementedError
def _get_vmd_xyz_output(self):
raise NotImplementedError
def _get_TEP_vmd_xyz_output(self):
raise NotImplementedError
def _get_crepy_output(self):
raise NotImplementedError
class Nucleotide(Printable):
"""
Nucleotides compose Strands.
Args:
cm_pos: Center of mass position, e.g. [0, 0, 0]
a1: Unit vector indicating orientation of backbone with respect to base, e.g. [1, 0, 0]
a3: Unit vector indicating orientation (tilting) of base with respect to backbone, e.g. [0, 0, 1]
base: Identity of base, which must be designated with either numbers or \
letters (this is called type in the c++ code). Confusingly enough, this \
is similar to Particle.btype in oxDNA.
Number: {0,1,2,3} or any number in between (-inf,-7) and (10, inf). \
To use specific sequences (or an alphabet large than four) one should \
start from the complementary pair 10 and -7. Complementary pairs are \
such that base_1 + base_2 = 3
Letter: {A,G,T,C} (these will be translated to {0, 1, 3, 2}). \
These are set in the dictionaries: number_to_base, base_to_number
btype: Identity of base. Unused at the moment.
L: Angular velocity
v: Velocity
Attributes:
cm_pos: Position of the center of mass.
index: Index of the nucleotide.
pos_back: Position of the backbone centroid.
pos_base: Position of the base centroid.
pos_stack: Position of the stacking site centroid.
"""
index = 0
def __init__(self, cm_pos, a1, a3, base, btype=None, L=np.array([0., 0., 0.]), v=np.array([0., 0., 0.]), n3=-1):
Printable.__init__(self)
self.index = Nucleotide.index
Nucleotide.index += 1
self.cm_pos = np.array(cm_pos)
self._a1 = np.array (a1)
self._a3 = np.array (a3)
#self._a2 = np.cross (a3, a1) # implemented as property
# _base should be a number
if isinstance(base, int):
pass
else:
try:
base = base_to_number[base]
except KeyError:
Logger.log("Invalid base (%s)" % base, level=Logger.WARNING)
self._base = base
if btype is None:
self._btype = base
else:
self._btype = btype
self._L = L
self._v = v
self.n3 = n3
self.next = -1
self.interactions = [] #what other nucleotide this nucleotide actually interacts with
self.init_interactions()
def get_pos_base (self):
#Note that cm_pos is the centroid of the backbone and base.
return self.cm_pos + self._a1 * POS_BASE
pos_base = property(get_pos_base)
def get_pos_stack (self):
#Note that cm_pos is the centroid of the backbone and base.
return self.cm_pos + self._a1 * POS_STACK
pos_stack = property (get_pos_stack)
def get_pos_back (self):
#Note that cm_pos is the centroid of the backbone and base.
if os.environ.get(GROOVE_ENV_VAR) == '1':
return self.cm_pos + self._a1 * POS_MM_BACK1 + self._a2 * POS_MM_BACK2
elif RNA:
return self.cm_pos + self._a1 * RNA_POS_BACK_a1 + self._a2 * RNA_POS_BACK_a2 + self._a3 * RNA_POS_BACK_a3
else:
return self.cm_pos + self._a1 * POS_BACK
pos_back = property (get_pos_back)
def get_pos_back_rel (self):
"""
Returns the position of the backbone centroid relative to the centre of mass,
i.e. it will be a vector pointing from the c.o.m. to the backbone.
"""
return self.get_pos_back() - self.cm_pos
def get_a2 (self):
return np.cross (self._a3, self._a1)
_a2 = property (get_a2)
def copy(self, disp=None, rot=None):
"""
Returns a copy of the nucleotide, with optional translation and/or rotation.
Args:
disp: displacement vector to translate the copied nucleotide
rot: rotation matrix to rotate the copied nucleotide
"""
copy = Nucleotide(self.cm_pos, self._a1, self._a3, self._base, self._btype, self._L, self._v, self.n3)
if disp is not None:
copy.translate(disp)
if rot is not None:
copy.rotate(rot)
return copy
def translate(self, disp):
"""
Translates the nucleotide.
Args:
disp: displacement vector to translate the nucleotide
"""
self.cm_pos += disp
#self.pos_base += disp
#self.pos_stack += disp
#self.pos_back += disp
try: self.cm_pos_box += disp
except: pass
def rotate(self, R, origin=None):
"""
Rotates the nucleotide.
Args:
R: rotation matrix to rotate the nucleotide
origin: the point around which the nucleotide rotates; defaults to be self.cm_pos
"""
if origin is None:
origin = self.cm_pos
self.cm_pos = np.dot(R, self.cm_pos - origin) + origin
self._a1 = np.dot(R, self._a1)
self._a3 = np.dot(R, self._a3)
# the following have been removed
#self._a2 = np.dot(R, self._a2)
#self.pos_base = self.cm_pos + self._a1 * POS_BASE
#self.pos_stack = self.cm_pos + self._a1 * POS_STACK
#self.pos_back = self.cm_pos + self._a1 * POS_BACK
def distance (self, other, PBC=True, box=None):
"""
Returns the distance to another nucleotide.
Args:
other: the other Nucleotide object
PBC: boolean. If true, considers periodic boundary conditions and returns the minimum image distance.
box: box dimensions in a numpy array
"""
if PBC and box is None:
if not (isinstance (box, np.ndarray) and len(box) == 3):
Logger.die ("distance between nucleotides: if PBC is True, box must be a numpy array of length 3");
dr = other.pos_back - self.pos_back
if PBC:
dr -= box * np.rint (dr / box)
return dr
def get_base(self):
"""
Returns the base id.
If the base is in ["A", "G", "C", "T", 0, 1, 2, 3], returns a string containing the letter of the base id.
Otherwise, returns a string containing the number of the base id.
"""
if type(self._base) is not int:
try:
b = number_to_base[self._base] # b is unused, this is just a check
except KeyError:
Logger.log("Nucleotide.get_base(): nucleotide %d: unknown base type '%d', defaulting to 12 (A)" % (self.index, self._base), Logger.WARNING)
if self._base in [0,1,2,3]:
return number_to_base[self._base]
else:
return str(self._base)
def _get_lorenzo_output(self):
a = np.concatenate((self.cm_pos, self._a1, self._a3, self._v, self._L))
return " ".join(str(x) for x in a)
def _get_crepy_output(self):
s1 = self.cm_pos_box + self.get_pos_back_rel()
return "%lf %lf %lf" % tuple(s1)
def _get_ribbon_output(self):
s1 = self.cm_pos_box + self.get_pos_back_rel()
return "%lf %lf %lf %lf %lf %lf %lf %lf %lf" % (tuple(s1) + tuple (self._a1) + tuple (self._a2))
def _get_tcl_detailed_output(self):
s1 = self.cm_pos_box + self.get_pos_back_rel()
return "%lf %lf %lf" % tuple(s1)
def _get_tcl_output(self):
s1 = self.cm_pos_box + self.get_pos_back_rel()
return "%lf %lf %lf" % tuple(s1)
def _get_vmd_xyz_output(self):
s1 = self.cm_pos_box + self.get_pos_back_rel()
s2 = self.cm_pos_box + POS_BASE * self._a1
res = "C %lf %lf %lf\n" % tuple(s1)
res += "O %lf %lf %lf\n" % (s2[0], s2[1], s2[2])
return res
# This prints a sphere with a line around it, hopefully.
def _get_TEP_vmd_xyz_output(self):
s1 = self.cm_pos_box
s2 = self.cm_pos_box + 0.3*self._a2
s3 = self.cm_pos_box + 0.15*self._a1
res = "C %lf %lf %lf\n" %tuple(s1)
res += "H %lf %lf %lf\n" %tuple(s2)
res += "He %lf %lf %lf\n" %tuple(s3)
return res
def get_pdb_output(self, strtype, strsubid):
s1 = self.cm_pos_box + self.get_pos_back_rel()
s2 = self.cm_pos_box + POS_BASE*self._a1
res = "ATOM %5d %4s %3s %c%4d%c %8.3f%8.3f%8.3f%6.2f%6.2f\n" % (2 * self.index + 1,"C",strtype,'C',self.index,' ',s1[0],s1[1],s1[2],1,7.895)
res += "ATOM %5d %4s %3s %c%4d%c %8.3f%8.3f%8.3f%6.2f%6.2f\n" % (2 * self.index + 2,"O",strtype,'C',self.index,' ',s2[0],s2[1],s2[2],1,6.316)
return res
def get_pdb_output_chimera(self, strtype, strsubid):
# the s# holds the position vector of each nucleotide element
s1 = self.cm_pos_box + self.get_pos_back_rel()
if os.environ.get(GROOVE_ENV_VAR) == '1':
s2 = self.cm_pos_box
index_jump = 3
else:
index_jump = 2
s3 = self.cm_pos_box + (POS_BACK + 0.68)*self._a1
if RNA:
#s1 = self_cm_pos_box + self.get_pos_back_rel()
s2 = self.cm_pos_box
s3 = self.cm_pos_box + (POS_BASE-0.1)*self._a1
index_jump = 3
# some magic to get the nice ellipse for the base particle
#s1 = self.cm_pos_box + POS_BACK* self._a1
#s2 = self.cm_pos_box + (POS_BACK + 0.68)*self._a1
I_b = np.matrix( ((1.1,0,0),(0,1.5,0),(0,0,2.2)) )
R = np.matrix( (self._a1,self._a2,self._a3) )
I_l = R.T*I_b*R
anis = np.multiply(-1,I_l)
anis[0,0] = (I_l[1,1]+I_l[2,2]-I_l[0,0])/2.0
anis[1,1] = (I_l[0,0]+I_l[2,2]-I_l[1,1])/2.0
anis[2,2] = (I_l[0,0]+I_l[1,1]-I_l[2,2])/2.0
# print the backbone site
res = "ATOM %5d %4s %3s %c%4d%c %8.3f%8.3f%8.3f%6.2f%6.2f\n" % (index_jump * self.index + 1,"A",strtype,'A',self.index % 10000,' ',s1[0],s1[1],s1[2],1,7.895)
res += "ANISOU%5d %4s %3s %c%4d%c %7i%7i%7i%7i%7i%7i\n" % (index_jump * self.index + 1,"A",strtype,'A',self.index % 10000,' ',1000,1000,1000,0,0,0)
# print the centre of mass site (if grooving is on)
if os.environ.get(GROOVE_ENV_VAR) == '1' or RNA:
res += "ATOM %5d %4s %3s %c%4d%c %8.3f%8.3f%8.3f%6.2f%6.2f\n" % (index_jump * self.index + 2,"B",strtype,'B',self.index % 10000,' ',s2[0],s2[1],s2[2],1,7.895)
res += "ANISOU%5d %4s %3s %c%4d%c %7i%7i%7i%7i%7i%7i\n" % (index_jump * self.index + 2,"B",strtype,'B',self.index % 10000,' ',250,250,250,0,0,0)
if self._base == 0:
atomtype = 'O'
elif self._base == 1:
atomtype = 'S'
elif self._base == 2:
atomtype = 'K'
elif self._base == 3:
atomtype = 'N'
else:
print >> sys.stderr, "Should not happen..."
atomtype = 'H'
# print the base site
res += "ATOM %5d %4s %3s %c%4d%c %8.3f%8.3f%8.3f%6.2f%6.2f\n" % (index_jump * self.index + 3, atomtype, strtype, 'C', self.index % 10000,' ',s3[0],s3[1],s3[2],1,6.316)
res += "ANISOU%5d %4s %3s %c%4d%c %7i%7i%7i%7i%7i%7i\n" % (index_jump * self.index + 3, atomtype, strtype, 'C', self.index % 10000, ' ' , anis[0,0]*1000, anis[1,1]*1000, anis[2,2]*1000, anis[0,1]*1000, anis[0,2]*1000, anis[1,2]*1000)
return res
def add_H_interaction (self,nucleotide):
self.interactions.append(nucleotide)
def check_H_interaction(self, nucleotide):
#print self.index, self.interactions
if (nucleotide in self.interactions):
return True
else:
return False
def check_interaction(self,interaction_type,nucleotide):
if(nucleotide in self.all_interactions[interaction_type].keys()):
return True
else:
return False
def get_interaction(self,nucleotide,interaction_type):
if(nucleotide in self.all_interactions[interaction_type].keys()):
return self.all_interactions[interaction_type][nucleotide]
else:
return False
def add_interaction(self,interaction_type,nucleotide,interaction_value):
self.all_interactions[interaction_type][nucleotide] = interaction_value
def init_interactions(self):
self.all_interactions = {}
for i in range(8):
self.all_interactions[i] = {}
def _get_cylinder_output(self):
# assume up to 1 interaction (h bond) per nucleotide
if self.interactions == []:
return np.zeros(3)
else:
r1 = self.get_pos_base()
r2 = self.interactions[0]
class Strand(Printable):
"""
Strands are composed of Nucleotides. Access nucleotide objects of Strand strand1 by strand1._nucleotides[nucleotide_index].
Strands can be contained in a System.
Attributes:
N: Length of the strand (i.e. the number of nucleotides).
sequence: Sequence of the strand.
cm_pos: Center of mass of the strand.
index: Index of the strand.
"""
index = 0
def __init__(self):
Printable.__init__(self)
self.index = Strand.index
Strand.index += 1
self._first = -1
self._last = -1
self._nucleotides = []
self._cm_pos = np.array([0., 0., 0.])
self._cm_pos_tot = np.array([0., 0., 0.])
self._sequence = []
self.visible = True
self.H_interactions = {} #shows what strands it has H-bonds with
self._circular = False #bool on circular DNA
def get_length(self):
return len(self._nucleotides)
def get_sequence(self):
return self._sequence
def _prepare(self, si, ni):
self.index = si
self._first = ni
for n in range(self.N):
self._nucleotides[n].index = ni + n
self._last = ni + n
return ni + n + 1
def copy(self):
"""
Returns a copy of the strand.
"""
copy = Strand()
for n in self._nucleotides:
copy.add_nucleotide(n.copy())
return copy
def get_cm_pos(self):
return self._cm_pos
def set_cm_pos(self, new_pos):
"""
Sets the center of mass of the strand to a new position by moving all the nucleotides.
Args:
new_pos: new center of mass position
"""
diff = new_pos - self._cm_pos
for n in self._nucleotides: n.translate(diff)
self._cm_pos = new_pos
def translate(self, amount):
"""
Translates the strand.
Args:
amount: displacement vector to translate the strand
"""
new_pos = self._cm_pos + amount
self.set_cm_pos(new_pos)
def rotate(self, R, origin=None):
"""
Rotates the strand.
Args:
R: rotation matrix to rotate the system
origin: the point around which the strand rotates; defaults to be self.cm_pos (NB this does not exist at the moment, perhaps a bug)
"""
if origin is None:
origin = self.cm_pos
for n in self._nucleotides: n.rotate(R, origin)
self._cm_pos = np.dot(R, self._cm_pos - origin) + origin
def append (self, other):
"""
Returns an extended strand which is formed by appending another strand to the current strand.
Note that the current strand is not changed.
Args:
other: the other Strand object
"""
if not isinstance (other, Strand):
raise ValueError
dr = self._nucleotides[-1].distance (other._nucleotides[0], PBC=False)
if np.sqrt(np.dot (dr, dr)) > (0.7525 + 0.25):
print >> sys.stderr, "WARNING: Strand.append(): strands seem too far apart. Assuming you know what you are doing."
ret = Strand()
for n in self._nucleotides:
ret.add_nucleotide(n)
for n in other._nucleotides:
ret.add_nucleotide(n)
return ret
def get_slice(self, start=0, end=None):
"""
Returns a slice of the strand.
Args:
start: starting point of the slice (default is 0)
end: ending point of the slice (default is end of strand)
"""
if end is None: end = len(self._nucleotides)
ret = Strand()
for i in range(start, end):
ret.add_nucleotide(self._nucleotides[i].copy())
return ret
def set_sequence(self, seq):
"""
Sets the sequence of the strand.
Args:
seq: either a string of letters (A,T,C,G), or a list of ints (0,1,2,3). Should have the same length as the strand.
"""
if isinstance (seq, str):
seq = [base_to_number[x] for x in seq]
if len(seq) != len(self._nucleotides):
Logger.log ("Cannot change sequence: lengths don't match", Logger.WARNING)
return
i = 0
for n in self._nucleotides:
n._base = seq[i]
i += 1
self._sequence = seq
def bring_in_box_nucleotides(self, box):
"""
Brings nucleotides of the strand back into the box.
Args:
box: box dimensions in a numpy array
"""
diff = np.rint(self.cm_pos / box ) * box
for n in self._nucleotides:
n.cm_pos_box = n.cm_pos - diff
def add_nucleotide(self, n):
"""
Adds a nucleotide to the strand.
Args:
n: Nucleotide object to be added.
"""
if len(self._nucleotides) == 0:
self._first = n.index
n.strand = self.index
self._nucleotides.append(n)
self._last = n.index
self._cm_pos_tot += n.cm_pos
self._cm_pos = self._cm_pos_tot / self.N
self.sequence.append(n._base)
def overlaps_with (self, other, box):
"""
Returns True if this strand overlaps with the other strand, False otherwise.
Args:
other: the other Strand object
box: box dimensions in a numpy array
"""
import energies as en
EXC_VOL_CUTOFF = 2.0
for n1 in self._nucleotides:
for n2 in other._nucleotides:
if en.excluded_volume (n1, n2, box, nearest=False) > EXC_VOL_CUTOFF:
#print en.excluded_volume (n1, n2, box, nearest=False)
return True
return False
def _get_lorenzo_output(self):
if not self.visible:
return ""
conf = "\n".join(n.get_output(OUT_LORENZO) for n in self._nucleotides) + "\n"
top = ""
for n in self._nucleotides:
if self._circular:
if n.index == self._first:
n3 = self._last
else:
n3 = n.index - 1
if n.index == self._last:
n5 = self._first
else:
n5 = n.index + 1
else:
if n.index == self._first:
n3 = -1
else:
n3 = n.index - 1
if n.index == self._last:
n5 = -1
else:
n5 = n.index + 1
top += "%d %s %d %d\n" % (self.index+1, n.get_base(), n3, n5)
return conf, top
def _get_crepy_output(self):
if not self.visible:
return ""
v = [n.get_output(OUT_CREPY) for n in self._nucleotides]
v.insert(1, "@ 0.3 C[red] DNA")
return " ".join(v)
def _get_ribbon_output(self):
if not self.visible:
return ""
v = [n._get_ribbon_output() for n in self._nucleotides]
v.insert(0, "0. 0. 0. @ 0.3 C[red] RIB")
return " ".join(v)
def get_tcl_detailed_output (self, labels=True, index=None):
if not self.visible:
return ""
v = [n._get_tcl_detailed_output() for n in self._nucleotides]
ret = ""
# label
# ret += "graphics 0 color black\n"
if labels:
if index == None:
index = self.index
ret += 'graphics 0 text {%lf %lf %lf}' % tuple(self._nucleotides[0].cm_pos_box)
ret += ' "%s" size 0.75\n' % (index)
# backbone
for i in range (0, self.N):
ret += "graphics 0 sphere "
ret += "{%s} " % v[i]
ret += "radius 0.35 resolution 20\n"
# backbone-backbone
for i, n in enumerate(self._nucleotides):
if n.n3 != -1:
ret += "graphics 0 cylinder "
ret += "{%s} " % v[i]
j = (i - 1) % (len(self._nucleotides))
ret += "{%s} radius 0.25 resolution 20 filled yes\n" % v[j]
ret += "graphics 0 sphere {%s} radius 0.35 resolution 20\n" % v[self.N-1]
bdir = self._nucleotides[-1].cm_pos - self._nucleotides[-2].cm_pos
bdir /= np.sqrt (np.dot (bdir, bdir))
bdir2 = self._nucleotides[-1].cm_pos_box + bdir / 2.
start = self._nucleotides[-1].cm_pos_box + self._nucleotides[-1].get_pos_back_rel()
end = self._nucleotides[-1].cm_pos_box + self._nucleotides[-1].get_pos_back_rel() + bdir * 2. / 3.
ret += "graphics 0 cone {%lf %lf %lf} {%lf %lf %lf} radius 0.35 resolution 20\n" % (start[0], start[1], start[2], end[0], end[1], end[2])
# bases
for n in self._nucleotides:
ii = self._nucleotides.index(n)
rb = n.cm_pos_box + n._a1 * POS_BASE
if os.environ.get(GROOVE_ENV_VAR) == '1':
rcm = n.cm_pos_box
ret += "graphics 0 cylinder {%s} {%lf %lf %lf} radius 0.15 resolution 20 filled yes\n" % (v[ii], rcm[0], rcm[1], rcm[2])
ret += "graphics 0 sphere {%lf %lf %lf} radius 0.15 resolution 20\n" % (rcm[0], rcm[1], rcm[2])
ret += "graphics 0 cylinder {%lf %lf %lf} {%lf %lf %lf} radius 0.15 resolution 20 filled yes\n" % (rcm[0], rcm[1], rcm[2], rb[0], rb[1], rb[2])
else:
# backbone-base
rB = n.cm_pos_box + n._a1 * POS_BACK
ret += "graphics 0 cylinder {%lf %lf %lf} {%lf %lf %lf} radius 0.15 resolution 20 filled yes\n" % (rB[0], rB[1], rB[2], rb[0], rb[1], rb[2])
#base
ret += "graphics 0 sphere {%lf %lf %lf} radius 0.20 resolution 20\n" % (rb[0], rb[1], rb[2])
#print ret
return ret
def get_tcl_output (self, labels=True, index=None):
if not self.visible:
return ""
v = [n._get_tcl_output() for n in self._nucleotides]
ret = ""
# label
# ret += "graphics 0 color black\n"
if labels:
if index == None:
index = self.index
ret += 'graphics 0 text {%lf %lf %lf}' % tuple(self._nucleotides[0].cm_pos_box)
ret += ' "%s" size 0.75\n' % (index)
# backbone
for i in range (0, self.N - 1):
if self._nucleotides[i].n3 != -1:
ret += "graphics 0 cylinder "
ret += "{%s} " % v[i]
ret += "{%s} radius 0.25 resolution 20 filled yes\n" % v[(i - 1)%self.N]
ret += "graphics 0 sphere "
ret += "{%s} " % v[i]
ret += "radius 0.30 resolution 20\n"
ret += "graphics 0 sphere {%s} radius 0.35 resolution 20\n" % v[self.N-1]
if self._nucleotides[self.N - 1].n3 != -1:
ret += "graphics 0 cylinder "
ret += "{%s} " % v[i]
ret += "{%s} radius 0.25 resolution 20 filled yes\n" % v[i + 1]
return ret
def get_pdb_output(self, domain=[],strand=0):
if not self.visible:
return ""
strtypes = ["ALA","GLY","CYS","TYR","ARG","PHE","LYS","SER","PRO","VAL","ASN","ASP","CYX","HSP","HSD","MET","LEU"]
strid = strtypes[( (self.index + 1) % len(strtypes) )]
atomoutput = ""
nid = 0
for nucleo in self._nucleotides:
nid += 1
atomoutput += nucleo.get_pdb_output(strid,nid)
return atomoutput
def get_pdb_output_chimera(self,domain=[],strand=0):
if not self.visible:
return ""
if len(domain) >0:
strtypes = ["ALA","GLY","CYS","TYR","ARG","PHE","LYS","SER","PRO","VAL","ASN","ASP","CYX","HSP","HSD","MET","LEU"]
nid=0
atomoutput = ""
for nucleo in self._nucleotides:
try:
domid = domain[strand][nid]
if domid<0:
domid = len(strtypes)+domid
except:
domid=0
domname = strtypes[(domid)%len(strtypes)]
nid += 1
atomoutput += nucleo.get_pdb_output_chimera(domname,nid)
return atomoutput
else:
strtypes = ["ALA","GLY","CYS","TYR","ARG","PHE","LYS","SER","PRO","VAL","ASN","ASP","CYX","HSP","HSD","MET","LEU"]
strid = strtypes[( (self.index + 1) % len(strtypes) )]
atomoutput = ""
nid = 0
for nucleo in self._nucleotides:
nid += 1
atomoutput += nucleo.get_pdb_output_chimera(strid,nid)
return atomoutput
def _get_vmd_xyz_output(self):
if not self.visible:
return ""
return "".join(n.get_output(OUT_VMD_XYZ) for n in self._nucleotides)
def _get_TEP_vmd_xyz_output(self):
if not self.visible:
return ""
return "".join(n.get_output(OUT_TEP_VMD_XYZ) for n in self._nucleotides)
cm_pos = property(get_cm_pos, set_cm_pos)
N = property(get_length)
sequence = property(get_sequence)
def add_H_interaction(self,other_strand):
if other_strand in self.H_interactions.keys():
self.H_interactions[other_strand] += 1
else:
self.H_interactions[other_strand] = 1
def get_H_interactions(self):
return self.H_interactions
def make_circular(self, check_join_len=False):
"""
Connect the ends of the strand to make it circular.
Args:
check_join_len: boolean. If true, checks whether the ends of the strand are close enough.
"""
if check_join_len:
dr = self._nucleotides[-1].distance (self._nucleotides[0], PBC=False)
if np.sqrt(np.dot (dr, dr)) > (0.7525 + 0.25):
Logger.log("Strand.make_circular(): ends of the strand seem too far apart. \
Assuming you know what you are doing.", level=Logger.WARNING)
self._circular = True
def make_noncircular(self):
"""
Disconnect the ends of a circular strand.
"""
self._circular = False
def parse_visibility(path):
try:
inp = open (path, 'r')
except:
Logger.log ("Visibility file `" + path + "' not found. Assuming default visibility", Logger.WARNING)
return []
output = []
for linea in inp.readlines():
linea = linea.strip().lower()
# remove everything that comes after '#'
linea = linea.split('#')[0]
if len(linea) > 0: output.append(linea)
return output
class System(object):
"""
Object representing an oxDNA system. Contains strands. Access strand objects of System system1 by system1._strands[strand_index].
Args:
box: Box size of the system, e.g. box = [50, 50, 50]
time: Time of the system
E_pot: Potential energy
E_kin: Kinetic energy
Attributes:
N: Number of nucleotides in the system.
N_strands: Number of strands in the system.
E_pot: Potential energy
E_kin: Kinetic energy
E_tot: Total energy
"""
chimera_count = 1
def __init__(self, box, time=0, E_pot=0, E_kin=0):
self._time = time
self._ready = False
self._box = np.array(box,np.float64)
self._N = 0
self._N_strands = 0
self._strands = []
self._nucleotide_to_strand = []
self._N_cells = np.array(np.floor (self._box / 3.), np.int)
for kk in [0, 1, 2]:
if self._N_cells[kk] > 100:
self._N_cells[kk] = 100
self._cellsides = box / self._N_cells
self._head = [False,] * int(self._N_cells[0] * self._N_cells[1] * self._N_cells[2])
self.E_pot = E_pot
self.E_kin = E_kin
self.E_tot = E_pot + E_kin
self.cells_done = False
def get_sequences (self):
"""
Returns the sequence of the system as a list of lists containing strand sequences.
"""
return [x._sequence for x in self._strands]
_sequences = property (get_sequences)
def get_N_Nucleotides(self):
return self._N
def get_N_strands(self):
return self._N_strands
def _prepare(self, visibility):
sind = 0
nind = 0
for sind in range(self._N_strands):