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 | class cadnano_part(SegmentModel):
def __init__(self, part,
**kwargs
):
self.part = part
self.lattice_type = _get_lattice(part)
self._cadnano_part_to_segments(part)
# SegmentModel.__init__(self,...)
# self.segments = [seg for hid,segs in self.helices.items() for seg in segs]
self.segments = [seg for hid,segs in sorted(self.helices.items()) for seg in segs]
self._add_intrahelical_connections()
self._add_crossovers()
self._add_prime_ends()
SegmentModel.__init__(self, self.segments,
**kwargs)
def _get_helix_angle(self, helix_id, indices):
""" Get "start_orientation" for helix """
# import ipdb
# ipdb.set_trace()
""" FROM CADNANO2.5
+ angle is CCW
- angle is CW
Right handed DNA rotates clockwise from 5' to 3'
we use the convention the 5' end starts at 0 degrees
and it's pair is minor_groove_angle degrees away
direction, hence the minus signs. eulerZ
"""
hp, bpr, tpr, eulerZ, mgroove = self.part.vh_properties.loc[helix_id,
['helical_pitch',
'bases_per_repeat',
'turns_per_repeat',
'eulerZ',
'minor_groove_angle']]
twist_per_base = tpr*360./bpr
# angle = eulerZ - twist_per_base*indices + 0.5*mgroove + 180
angle = eulerZ + twist_per_base*indices - 0.5*mgroove
return angle
def _cadnano_part_to_segments(self,part):
try:
from cadnano.cnenum import PointType
except:
try:
from cadnano.proxies.cnenum import PointType
except:
from cadnano.proxies.cnenum import PointEnum as PointType
segments = dict()
self.helices = helices = dict()
self.helix_ranges = helix_ranges = dict()
props = part.getModelProperties().copy()
if props.get('point_type') == PointType.ARBITRARY:
# TODO add code to encode Parts with ARBITRARY point configurations
raise NotImplementedError("Not implemented")
else:
try:
vh_props, origins = part.helixPropertiesAndOrigins()
except:
origins = {hid:part.getVirtualHelixOrigin(hid)[:2] for hid in part.getidNums()}
self.origins = origins
vh_list = []
strand_list = []
xover_list = []
self.xovers_from = dict()
self.xovers_to = dict()
try:
numHID = part.getMaxIdNum() + 1
except:
numHID = part.getIdNumMax() + 1
for id_num in range(numHID):
try:
offset_and_size = part.getOffsetAndSize(id_num)
except:
offset_and_size = None
if offset_and_size is None:
## Add a placeholder for empty helix
vh_list.append((id_num, 0))
strand_list.append(None)
else:
offset, size = offset_and_size
vh_list.append((id_num, size))
fwd_ss, rev_ss = part.getStrandSets(id_num)
fwd_idxs, fwd_colors = fwd_ss.dump(xover_list)
rev_idxs, rev_colors = rev_ss.dump(xover_list)
strand_list.append((fwd_idxs, rev_idxs))
self.xovers_from[id_num] = []
self.xovers_to[id_num] = []
for xo in xover_list:
h1,f1,z1,h2,f2,z2 = xo
self.xovers_from[h1].append(xo)
self.xovers_to[h2].append(xo)
## Get lists of 5/3prime ends
strands5 = [o.strand5p() for o in part.oligos()]
strands3 = [o.strand3p() for o in part.oligos()]
self._5prime_list = [(s.idNum(),s.isForward(),s.idx5Prime()) for s in strands5]
self._3prime_list = [(s.idNum(),s.isForward(),s.idx3Prime()) for s in strands3]
## Get dictionary of insertions
self.insertions = allInsertions = part.insertions()
self.strand_occupancies = dict()
## Build helices
for hid in range(numHID):
# print("Working on helix",hid)
helices[hid] = []
helix_ranges[hid] = []
self.strand_occupancies[hid] = []
helixStrands = strand_list[hid]
if helixStrands is None: continue
## Build list of tuples containing (idx,length) of insertions/skips
insertions = sorted( [(i[0],i[1].length()) for i in allInsertions[hid].items()],
key=lambda x: x[0] )
## TODO: make the following code (until "regions = ...") more readable
## Build list of strand ends and list of mandatory node locations
ends1,ends2 = self._helixStrandsToEnds(helixStrands)
## Find crossovers for this helix
reqNodeZids = sorted(list(set( ends1 + ends2 ) ) )
## Build lists of which nt sites are occupied in the helix
strandOccupancies = [ [x for i in range(0,len(e),2)
for x in range(e[i],e[i+1]+1)]
for e in (ends1,ends2) ]
self.strand_occupancies[hid] = strandOccupancies
ends1,ends2 = [ [(e[i],e[i+1]) for i in range(0,len(e),2)] for e in (ends1,ends2) ]
regions = combineRegionLists(ends1,ends2)
## Split regions in event of ssDNA crossover
split_regions = []
for zid1,zid2 in regions:
zMid = int(0.5*(zid1+zid2))
if zMid in strandOccupancies[0] and zMid in strandOccupancies[1]:
split_regions.append( (zid1,zid2) )
else:
is_fwd = zMid in strandOccupancies[0]
ends = [z for h,f,z in self._get_crossover_locations( hid, range(zid1+1,zid2), is_fwd )]
z1 = zid1
for z in sorted(ends):
z2 = z
if z2 > z1:
split_regions.append( (z1,z2) )
z1 = z2+1
z2 = zid2
split_regions.append( (z1,z2) )
# if hid == 43:
# import pdb
for zid1,zid2 in split_regions:
zMid = int(0.5*(zid1+zid2))
assert( zMid in strandOccupancies[0] or zMid in strandOccupancies[1] )
bp_to_zidx = []
insertion_dict = {idx:length for idx,length in insertions}
for i in range(zid1,zid2+1):
if i in insertion_dict:
l = insertion_dict[i]
else:
l = 0
for j in range(i,i+1+l):
bp_to_zidx.append(i)
numBps = len(bp_to_zidx)
# print("Adding helix with length",numBps,zid1,zid2)
name = "%d-%d" % (hid,len(helices[hid]))
# "H%03d" % hid
kwargs = dict(name=name, segname=name, occupancy=hid)
posargs1 = dict( start_position = self._get_cadnano_position(hid,zid1-0.25),
end_position = self._get_cadnano_position(hid,zid2+0.25) )
posargs2 = dict( start_position = posargs1['end_position'],
end_position = posargs1['start_position'])
## TODO get sequence from cadnano api
if zMid in strandOccupancies[0] and zMid in strandOccupancies[1]:
kwargs['num_bp'] = numBps
_angle = self._get_helix_angle(hid, zid1)
start_orientation = rotationAboutAxis(np.array((0,0,1)), _angle)
seg = DoubleStrandedSegment(**kwargs,**posargs1, start_orientation = start_orientation)
elif zMid in strandOccupancies[0]:
kwargs['num_nt'] = numBps
seg = SingleStrandedSegment(**kwargs,**posargs1)
elif zMid in strandOccupancies[1]:
kwargs['num_nt'] = numBps
seg = SingleStrandedSegment(**kwargs,**posargs2)
else:
raise Exception("Segment could not be found")
seg._cadnano_helix = hid
seg._cadnano_start = zid1
seg._cadnano_end = zid2
seg._cadnano_bp_to_zidx = bp_to_zidx
def callback(segment):
for b in segment.beads:
bp = int(round(b.get_nt_position(segment)))
if bp < 0: bp = 0
if bp >= segment.num_nt: bp = segment.num_nt-1
try:
b.beta = segment._cadnano_bp_to_zidx[bp]
if 'orientation_bead' in b.__dict__:
b.orientation_bead.beta = segment._cadnano_bp_to_zidx[bp]
except:
pass
seg._generate_bead_callbacks.append(callback)
def atomic_callback(nucleotide, bp_to_zidx=bp_to_zidx):
nt = nucleotide
segment = nucleotide.parent.segment
bp = int(round(segment.contour_to_nt_pos( nt.contour_position )))
if bp < 0: bp = 0
if bp >= segment.num_nt: bp = segment.num_nt-1
try:
nt.beta = bp_to_zidx[bp]
nt.parent.occupancy = segment.occupancy
except:
pass
seg._generate_nucleotide_callbacks.append(atomic_callback)
helices[hid].append( seg )
helix_ranges[hid].append( (zid1,zid2) )
def _get_cadnano_position(self, hid, zid):
return [10*a for a in self.origins[hid]] + [-3.4*zid]
def _helixStrandsToEnds(self, helixStrands):
"""Utility method to convert cadnano strand lists into list of
indices of terminal points"""
endLists = [[],[]]
for endList, strandList in zip(endLists,helixStrands):
lastStrand = None
for s in strandList:
if lastStrand is None:
## first strand
endList.append(s[0])
elif lastStrand[1] != s[0]-1:
assert( s[0] > lastStrand[1] )
endList.extend( [lastStrand[1], s[0]] )
lastStrand = s
if lastStrand is not None:
endList.append(lastStrand[1])
return endLists
def _helix_strands_to_segment_ranges(self, helix_strands):
"""Utility method to convert cadnano strand lists into list of
indices of terminal points"""
def _join(strands):
ends = []
lastEnd = None
for start,end in strands:
if lastEnd is None:
ends.append([start])
elif lastEnd != start-1:
ends[-1].append(lastEnd)
ends.append([start])
lastEnd = end
if lastEnd is not None:
ends[-1].append(lastEnd)
return ends
s1,s2 = [_join(s) for s in helix_strands]
i = j = 0
## iterate through strands
while i < len(s1) and j < len(s2):
min(s1[i][0],s2[j][0])
def _get_segment(self, hid, zid):
## TODO: rename these variables to segments
segs = self.helices[hid]
ranges = self.helix_ranges[hid]
for i in range(len(ranges)):
zmin,zmax = ranges[i]
if zmin <= zid and zid <= zmax:
return segs[i]
raise Exception("Could not find segment in helix %d at position %d" % (hid,zid))
def _get_nucleotide(self, hid, zid):
raise Exception("Deprecated")
seg = self._get_segment(hid,zid)
sid = self.helices[hid].index(seg)
zmin,zmax = self.helix_ranges[hid][sid]
nt = zid-zmin
## Find insertions
# TODO: for i in range(zmin,zid+1): ?
for i in range(zmin,zid):
if i in self.insertions[hid]:
nt += self.insertions[hid][i].length()
return nt
def _get_segment_nucleotide(self, hid, zid, get_forward_location=False):
""" returns segments and zero-based nucleotide index """
seg = self._get_segment(hid,zid)
sid = self.helices[hid].index(seg)
zmin,zmax = self.helix_ranges[hid][sid]
zMid = int(0.5*(zmin+zmax))
occ = self.strand_occupancies[hid]
ins = self.insertions[hid]
## TODO combine if/else when nested TODO is resolved
# if zid in self.insertions[hid]:
# import pdb
# pdb.set_trace()
if (zMid not in occ[0]) and (zMid in occ[1]):
## reversed ssDNA strand
nt = zmax-zid
# TODO: for i in range(zmin,zid+1): ?
for i in range(zid,zmax+1):
if i in self.insertions[hid]:
nt += self.insertions[hid][i].length()
else:
## normal condition
if get_forward_location:
while zid in ins and ins[zid].length() < 0 and zid <= zmax:
zid+=1
# else:
# while zid in ins and ins[zid].length() > 0 and zid >= zmax:
# zid-=1
nt = zid-zmin
for i in range(zmin,zid):
if i in ins:
nt += ins[i].length()
if not get_forward_location and zid in ins:
nt += ins[zid].length()
## Find insertions
return seg, nt
""" Routines to add connnections between helices """
def _add_intrahelical_connections(self):
for hid,segs in self.helices.items():
occ = self.strand_occupancies[hid]
for i in range(len(segs)-1):
seg1,seg2 = [segs[j] for j in (i,i+1)]
if isinstance(seg1,SingleStrandedSegment) and isinstance(seg2,SingleStrandedSegment):
continue
r1,r2 = [self.helix_ranges[hid][j] for j in (i,i+1)]
if r1[1]+1 == r2[0]:
## TODO: handle nicks that are at intrahelical connections(?)
zmid1 = int(0.5*(r1[0]+r1[1]))
zmid2 = int(0.5*(r2[0]+r2[1]))
## TODO: validate
if zmid1 in occ[0] and zmid2 in occ[0]:
seg1.connect_end3(seg2.start5)
if zmid1 in occ[1] and zmid2 in occ[1]:
if zmid1 in occ[0]:
end = seg1.end5
else:
end = seg1.start5
if zmid2 in occ[0]:
seg2.connect_start3(end)
else:
seg2.connect_end3(end)
def _get_crossover_locations(self, helix_idx, nt_idx_range, fwd_strand=None):
xos = []
def append_if_in_range(h,f,z):
if fwd_strand in (None,f) and z in nt_idx_range:
xos.append((h,f,z))
for xo in self.xovers_from[helix_idx]:
## h1,f1,z1,h2,f2,z2 = xo[3:]
append_if_in_range(*xo[:3])
for xo in self.xovers_to[helix_idx]:
append_if_in_range(*xo[3:])
return xos
def _add_crossovers(self):
for hid,xos in self.xovers_from.items():
for h1,f1,z1,h2,f2,z2 in xos:
seg1, nt1 = self._get_segment_nucleotide(h1,z1,not f1)
seg2, nt2 = self._get_segment_nucleotide(h2,z2,f2)
## TODO: use different types of crossovers
## fwd?
## 5'-to-3' direction
if isinstance(seg1, SingleStrandedSegment): f1 = True
if isinstance(seg2, SingleStrandedSegment): f2 = True
seg1.add_crossover(nt1,seg2,nt2,[f1,f2])
def _add_prime_ends(self):
for h,fwd,z in self._5prime_list:
seg, nt = self._get_segment_nucleotide(h,z, fwd)
if isinstance(seg, SingleStrandedSegment): fwd = True
# print("adding 5prime",seg.name,nt,fwd)
seg.add_5prime(nt,fwd)
for h,fwd,z in self._3prime_list:
seg, nt = self._get_segment_nucleotide(h,z, not fwd)
if isinstance(seg, SingleStrandedSegment): fwd = True
# print("adding 3prime",seg.name,nt,fwd)
seg.add_3prime(nt,fwd)
def get_bead(self, hid, zid):
# get segment, get nucleotide,
seg, nt = self._get_segment_nucleotide(h,z)
# return seg.get_nearest_bead(seg,nt / seg.num_nt)
return seg.get_nearest_bead(seg,nt / (seg.num_nt-1))
|