beadModelTwist.py 55.6 KB
Newer Older
cmaffeo2's avatar
cmaffeo2 committed
1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding: utf-8 -*-
from datetime import datetime
from cadnano.cnenum import PointType
from math import pi,sqrt,exp,floor
import numpy as np
from scipy.special import erf
import scipy.optimize as opt
import os, sys, subprocess

import nbPot
from coords import minimizeRmsd, quaternionToMatrix3, rotationAboutAxis


14
15
class HarmonicPotential:
    def __init__(self, k, r0, rRange=(0,50), resolution=0.1, maxForce=None, maxPotential=None):
cmaffeo2's avatar
cmaffeo2 committed
16
17
18
        self.k = k
        self.r0 = r0
        self.maxForce = maxForce
19
        self.maxPotential = maxPotential
cmaffeo2's avatar
cmaffeo2 committed
20
        self.rRange = rRange
21
        self.resolution = resolution
cmaffeo2's avatar
cmaffeo2 committed
22
23
24
25
        self.periodic = False
        self.type = "None"
        self._kscale = None

26
    def filename(self, prefix='potentials/'):
cmaffeo2's avatar
cmaffeo2 committed
27
        # raise NotImplementedError("Not implemented")
28
        return "%s%s-%.3f-%.3f.dat" % (prefix, self.type,
cmaffeo2's avatar
cmaffeo2 committed
29
30
                                       self.k*self._kscale, self.r0)

31
    def write_file(self, prefix='potentials/'):
cmaffeo2's avatar
cmaffeo2 committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
        r = np.arange( self.rRange[0], 
                       self.rRange[1]+self.resolution, 
                       self.resolution )
        dr = r-self.r0

        if self.periodic == True:
            rSpan = self.rRange[1]-self.rRange[0]
            assert(rSpan > 0)
            dr = np.mod( dr+0.5*rSpan, rSpan) - 0.5*rSpan 

        u = 0.5*self.k*dr**2

        if self.maxForce is not None:
            assert(self.maxForce > 0)
            f = np.diff(u)/np.diff(r)
47
48
            f[f >  self.maxForce] =  self.maxForce
            f[f < -self.maxForce] = -self.maxForce            
cmaffeo2's avatar
cmaffeo2 committed
49
50
            u[0] = 0
            u[1:] = np.cumsum(f*np.diff(r))
51
52
53
54

        u = u - np.min(u)
        
        if self.maxPotential is not None:
55
56
57
58
59
60
61
62
63
64
65
            f = np.diff(u)/np.diff(r)
            ids = np.where( 0.5*(u[1:]+u[:-1]) > self.maxPotential )[0]

            w = np.sqrt(2*self.maxPotential/self.k)
            drAvg = 0.5*(np.abs(dr[ids]) + np.abs(dr[ids+1]))

            f[ids] = f[ids] * np.exp(-(drAvg-w)/(w))
            u[0] = 0
            u[1:] = np.cumsum(f*np.diff(r))

        u = u - np.min(u)
66
67

        np.savetxt( self.filename(prefix), np.array([r, u]).T, fmt="%f" )
cmaffeo2's avatar
cmaffeo2 committed
68
69
70

    def __hash__(self):
        assert(self.type != "None")
71
        return hash((self.type, self.k, self.r0, self.rRange, self.resolution, self.maxForce, self.maxPotential, self.periodic))
cmaffeo2's avatar
cmaffeo2 committed
72
73

    def __eq__(self, other):
74
        for a in ("type", "k", "r0", "rRange", "resolution", "maxForce", "maxPotential", "periodic"):
cmaffeo2's avatar
cmaffeo2 committed
75
76
77
78
79
            if self.__dict__[a] != other.__dict__[a]:
                return False
        return True

class NonBonded(HarmonicPotential):
80
81
    def __init__(self, k, r0, rRange=(0,50), resolution=0.1, maxForce=None, maxPotential=None):
        super().__init__(k,r0,rRange,resolution,maxForce,maxPotential)
cmaffeo2's avatar
cmaffeo2 committed
82
83
84
85
        self.type = "nonbonded"
        self._kscale = 1.0

class Bond(HarmonicPotential):
86
87
    def __init__(self, k, r0, rRange=(0,800), resolution=0.1, maxForce=5, maxPotential=None):
        super().__init__(k,r0,rRange,resolution,maxForce,maxPotential)
cmaffeo2's avatar
cmaffeo2 committed
88
89
90
91
        self.type = "bond"
        self._kscale = 1.0

class Angle(HarmonicPotential):
92
93
    def __init__(self, k, r0, rRange=(0,180), resolution=0.5, maxForce=None, maxPotential=None):
        super().__init__(k,r0,rRange,resolution,maxForce,maxPotential)
cmaffeo2's avatar
cmaffeo2 committed
94
95
96
97
        self.type = "angle"
        self._kscale = (180.0/pi)**2

class Dihedral(HarmonicPotential):
98
99
    def __init__(self, k, r0, rRange=(-180,180), resolution=1, maxForce=None, maxPotential=None):
        super().__init__(k,r0,rRange,resolution,maxForce,maxPotential)
cmaffeo2's avatar
cmaffeo2 committed
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
        self.periodic = True
        self.type = "dihedral"
        self._kscale = (180.0/pi)**2

class Node():
    def __init__(self, helix, pos, type="dsDNA"):
        self.helix    = helix
        self.position = np.array(pos)
        self.initialPosition = np.array(pos)
        self.type     = type
        self.nodeAbove = None
        self.nodeBelow = None
        self.xovers = []
        self.ssXovers = []

        self.orientationNode = None
        self.parentNode = None

        self.idx = helix.model.numParticles
        helix.model.numParticles += 1

    def addNodeAbove(self, node, separation):
        assert(self.nodeAbove is None)
        self.nodeAbove = node
        self.nodeAboveSep = separation # bp
    def addNodeBelow(self, node, separation):
        assert(self.nodeBelow is None)
        self.nodeBelow = node
        self.nodeBelowSep = separation # bp

    def addXover(self, node, fwds, double=False):
        ## TODO: what is meant by polarity?
        self.xovers.append( (node,fwds,double) )

    def addSsXover(self, node, fwds):
        self.ssXovers.append( (node,fwds) )
    
    def getNodesAbove(self,numNodes,inclusive=False):
        assert( type(numNodes) is int and numNodes > 0 )

        nodeList,sepList = [[],[]]
        n = self
        if inclusive:
            nodeList.append(n)

        for i in range(numNodes):
            if n.nodeAbove is None: break
            n = n.nodeAbove
            nodeList.append(n)
            sepList.append(n.nodeBelowSep)
            
        return nodeList,sepList

    def getNodesBelow(self,numNodes,inclusive=False):
        assert( type(numNodes) is int and numNodes > 0 )

        nodeList,sepList = [[],[]]
        n = self
        if inclusive:
            nodeList.append(n)

        for i in range(numNodes):
            if n.nodeBelow is None: break
            n = n.nodeBelow
            nodeList.append(n)
            sepList.append(n.nodeBelowSep)
            
        return nodeList,sepList

    def addOrientationNode(self, node):
        assert(self.nodeBelow is None)
        self.orientationNode = node
        node.parentNode = self

class helix():
    def __init__(self, model, part, hid):
        self.model = model
        self.props = part.getModelProperties().copy() # TODO: maybe move this out of here
        self.nodes = dict()
        self.orientationNodes = dict()

        self.hid = hid

        if self.props.get('point_type') == PointType.ARBITRARY:
            # TODO add code to encode Parts with ARBITRARY point configurations
            raise NotImplementedError("Not implemented")
        else:
            vh_props, origins = part.helixPropertiesAndOrigins()
            for x in vh_props:
                self.props[x] = vh_props[x][hid]

            self.origin = origins[hid]
            x,y = self.origin
            self.zIdxToPos = lambda idx: (x*10,y*10,-3.4*idx)

            ## get twizt
            keys = ['bases_per_repeat',
                    'turns_per_repeat',
                    'eulerZ','z']
            bpr,tpr,eulerZ,z = [vh_props[k][hid] for k in keys] 
            twist_per_base = tpr*360./bpr
201
            self.zIdxToAngle = lambda idx: idx*twist_per_base + eulerZ + 160
cmaffeo2's avatar
cmaffeo2 committed
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

    def addNode(self, zIdx, strandOccupancies):
        ## Determine what kind of node we are making
        i = int(round(zIdx))
        if i in strandOccupancies[0] and i in strandOccupancies[1]:
            type = "dsDNA"
        elif i in strandOccupancies[0] or i in strandOccupancies[1]:
            # type = "dsDNA"
            type = "ssDNA"
        else:
            raise Exception( "Attempt to add a node at %d where there is no DNA!\n Strand at indeces: %s" % (i,strandOccupancies) )
        ## Add the node
        n = Node(self, self.zIdxToPos(zIdx), type)

        if zIdx in self.nodes:
            raise Exception("Attempted to add a node in the same location (%d:%.1f) twice!" % (self.hid,zIdx))

        self.nodes[zIdx] = n

        if type == "dsDNA":
            angle = self.zIdxToAngle(zIdx)
            pos = np.array([2.0,0,0]).dot( rotationAboutAxis([0,0,1], angle) )
            o = Node(self, np.array(self.zIdxToPos(zIdx)) + pos, "O")
            self.orientationNodes[zIdx] = o
            n.addOrientationNode(o)

        ## Update ordered list of nodes 
        if self.model.particles is not None:
            model.buildOrderedParticlesList()

        return n

    def getOrigin(self):
        return self.origin

    def __iter__(self):
        for x in sorted(self.nodes.items(), key=lambda x: x[0]):
            yield x
    
class beadModelTwist():

    def __init__(self, part, twistPersistenceLength=75.0, maxBpsPerDNode=4, maxNtsPerSNode=2):
        self.numParticles = 0
        self.helices = dict()
        self.particles = None
        self.particleTypeCounts = None

        # self._nbParams = set()
250
251
252
        self.bonds = set()
        self.angles = set()
        self.dihedrals = set()
cmaffeo2's avatar
cmaffeo2 committed
253
254

        self._nbParamFiles = []
255
256
257
        # self._bondParamFiles = set()
        # self._angleParamFiles = set()
        # self._dihedralParamFiles = set()
cmaffeo2's avatar
cmaffeo2 committed
258
259

        self.twistPersistenceLength = twistPersistenceLength
260
        self.apply_extra_crossover_potentials = False
cmaffeo2's avatar
cmaffeo2 committed
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

        self._buildModel(part, maxBpsPerDNode, maxNtsPerSNode)
        
        ## Post process the model
        self.buildOrderedParticlesList()
        self._setTypes()
        self._countParticleTypes()
        self.buildOrderedParticlesList()

    def __iter__(self):
        for x in sorted(self.helices.items(), key=lambda x: x[0]):
            yield x

    def buildOrderedParticlesList(self):
        ## Create ordered list
        particles = [(n,hid,zid) for hid,hlx in self for zid,n in hlx]        
        particles.extend( [(o,hid,zid) for hid,hlx in self for zid,o in hlx.orientationNodes.items()] )

        self.particles = sorted(particles, key=lambda x: (x[0].type, x[0].idx))
        
        ## Update node indices
        for p,i in zip(self.particles,range(self.numParticles)):
            p[0].idx = i
            
        self.initialCoords = np.array([p[0].initialPosition for p in self.particles])
        self._nodeHids = np.array([p[1] for p in self.particles])

    def _setTypes(self):
        for p,hid,zid in self.particles:
            if p.type == "O":
                p.bps = 0
                continue

            bps = []
            if p.nodeAbove is not None: bps.append(p.nodeAboveSep)
            if p.nodeBelow is not None: bps.append(p.nodeBelowSep)
            if bps == []: bps = [3]
            p.bps = 10*np.mean(bps)

            if p.type == "ssDNA":
                p.bps *= 0.5

            p.bps = int(round(p.bps))
            p.type = "%s%d" % (p.type[0], p.bps)

    def _countParticleTypes(self):
        particleTypeCounts = dict()
        for p in self.particles:
            t = p[0].type
            if t in particleTypeCounts:
                particleTypeCounts[t] += 1
            else:
                particleTypeCounts[t] = 1
        self.particleTypeCounts = particleTypeCounts

    def addHelix(self, part, hid):
        h = helix(self,part,hid)
        self.helices[hid] = h
        return h
    
    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 simulate(self, outputPrefix, outputDirectory='output', numSteps=100000000, timestep=100e-6, gpu=0, arbd=None):
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
        self._buildBonds(outputPrefix)
        self._buildAngles(outputPrefix)
        self._buildDihedrals(outputPrefix)

        ## Check that potentials don't have hash collisions
        for potSet in (self.bonds, self.angles, self.dihedrals):
            pots = [p[-1] for p in potSet]
            d = dict()
            for p in pots:
                f = p.filename
                if f not in d: d[f]=[]
                d[f].append(p)
            for f,pots in d.items():
                assert( len(set(pots)) == 1 )


cmaffeo2's avatar
cmaffeo2 committed
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
        assert(type(gpu) is int)
        assert(type(numSteps) is int)
        if outputDirectory == '': outputDirectory='.'
            
        if arbd is None:
            for path in os.environ["PATH"].split(os.pathsep):
                path = path.strip('"')
                fname = os.path.join(path, "arbd")
                if os.path.isfile(fname) and os.access(fname, os.X_OK):
                    arbd = fname
                    break

        if not os.path.exists(arbd):
            raise Exception("ARBD was not found")
        if not os.path.isfile(arbd):
            raise Exception("ARBD was not found")
        if not os.access(arbd, os.X_OK):
            raise Exception("ARBD is not executable")

        if not os.path.exists(outputDirectory):
            os.makedirs(outputDirectory)
        elif not os.path.isdir(outputDirectory):
            raise Exception("outputDirectory '%s' is not a directory!" % outputDirectory)
            

        self.writePdb( outputPrefix + ".pdb" )
        self.writePsf( outputPrefix + ".psf" )
        self.writeArbdFiles( outputPrefix, numSteps=numSteps, timestep=timestep )

387
388
389
        env = os.environ.copy()
        env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"

cmaffeo2's avatar
cmaffeo2 committed
390
391
392
393
394
395
396
        ## http://stackoverflow.com/questions/18421757/live-output-from-subprocess-command
        # cmd = "%s -g %d %s.bd %s/%s" % (arbd, gpu, outputPrefix, outputDirectory, outputPrefix)
        # cmd = (arbd, (-g %d %s.bd %s/%s" % (gpu, outputPrefix, outputDirectory, outputPrefix))
        cmd = (arbd, '-g', "%d" % gpu, "%s.bd" % outputPrefix, "%s/%s" % (outputDirectory, outputPrefix))
        cmd = tuple(str(x) for x in cmd)

        print("Running ARBD with: %s" % " ".join(cmd))
397
        process = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, universal_newlines=True)
cmaffeo2's avatar
cmaffeo2 committed
398
399
400
        for line in process.stdout:
        # for line in iter(process.stdout.readline, b''):
            sys.stdout.write(line)
401
402
            sys.stdout.flush()
           # sys.stdout.write(line.decode(sys.stdout.encoding))
cmaffeo2's avatar
cmaffeo2 committed
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
    
    # -------------------------- #
    # Methods for building model #
    # -------------------------- #
    def _buildModel(self, part, maxBpsPerDNode, maxNtsPerSNode):
        # maxVhelixId = part.getIdNumMax()
        
        props = part.getModelProperties().copy()
        # print(props)

        if props.get('point_type') == PointType.ARBITRARY:
            # TODO add code to encode Parts with ARBITRARY point configurations
            raise NotImplementedError("Not implemented")
        else:
            vh_props, origins = part.helixPropertiesAndOrigins()
            # print(' VIRTUAL HELICES:', vh_props)
            # # print(' ORIGINS:', origins)
            # group_props['virtual_helices'] = vh_props
            # group_props['origins'] = origins
            
        ## TODO: compartmentalize following
        ## Loop over virtual helices and build lists of strands 
        vh_list = []
        strand_list = []
        xover_list = []
        numHID = part.getIdNumMax() + 1
        for id_num in range(numHID):
            offset_and_size = part.getOffsetAndSize(id_num)
            if offset_and_size is None:
                # add a placeholder
                vh_list.append((id_num, 0))
                strand_list.append(None)
                # prop_list.append(None)
            else:
                offset, size = offset_and_size
                vh_list.append((id_num, size))
                fwd_ss, rev_ss = part.getStrandSets(id_num)
                # for s in fwd_ss:
                #     print(' VHELIX %d fwd_ss:' % id_num, s)
                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))

                # if id_num < 2:
                #     print( fwd_idxs )
                #     for s in fwd_ss:
                #         print( s.insertionsOnStrand() )
                
                ## prop_list.append((fwd_colors, rev_colors))
                # for s in strand_list:
                #     print( s )
                

        ## Get dictionary of insertions 
        allInsertions = part.insertions()

        ## Expand strand_lists for crossover filtering 
        expandedStrandList = []
        for fwdRevStrands in strand_list:
            tmp = []
            if fwdRevStrands is not None:
                for strands in fwdRevStrands:
                    fwdOrRev = []
                    for a,b in strands: fwdOrRev.extend(range(a,b+1))
                    tmp.append(fwdOrRev)
            expandedStrandList.append(tmp)

        ## Find crossovers involving ssDNA and dsDNA
        ssXoList, dsXoList, extraInterhelicalBondList = [[],[],[]]
        for entry in xover_list:
            h1,f1,z1,h2,f2,z2 = entry
            if strand_list[h1] is None or strand_list[h2] is None:
                print("WARNING: crossover to empty helix")
                continue

            ds1 = z1 in expandedStrandList[h1][0] and z1 in expandedStrandList[h1][1]
            ds2 = z2 in expandedStrandList[h2][0] and z2 in expandedStrandList[h2][1]
480
481
482
483
484
485
486
487
488
489
490
491

            occ1Above = z1+1 in expandedStrandList[h1][0] or z1+1 in expandedStrandList[h1][1]
            occ2Above = z2+1 in expandedStrandList[h2][0] or z2+1 in expandedStrandList[h2][1]

            occ1Below = z1-1 in expandedStrandList[h1][0] or z1-1 in expandedStrandList[h1][1]
            occ2Below = z2-1 in expandedStrandList[h2][0] or z2-1 in expandedStrandList[h2][1]

            if ((not occ1Above) and (not occ2Below)) or \
               ((not occ1Below) and (not occ2Above)):
                extraInterhelicalBondList.append(entry)
            else:
                if ds1 and ds2:
cmaffeo2's avatar
cmaffeo2 committed
492
493
                    dsXoList.append(entry)
                else:
494
                    ssXoList.append(entry)
cmaffeo2's avatar
cmaffeo2 committed
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

        ## Build dictionary of dsDNA crossovers
        xoDicts = [dict() for i in range(numHID)]
        for hid1 in range(numHID):
            tmp = xoDicts[hid1]
            for hid2 in range(numHID):
                allXos       = {(z1,z2,f1,f2) for h1,f1,z1,h2,f2,z2 in dsXoList if h1 == hid1 and h2 == hid2}
                allXos.update( {(z2,z1,f2,f1) for h1,f1,z1,h2,f2,z2 in dsXoList if h2 == hid1 and h1 == hid2} )
                allXos = sorted(list(allXos), key = lambda x: (x[0],x[1]))

                ## Replace each double-crossover with a single one
                excludedXos, extraXos = [set(),set()]
                for i in range(len(allXos)):
                    xoi = allXos[i]
                    for j in range(i+1,len(allXos)):
                        xoj = allXos[j]
                        if xoj[0] - xoi[0] > 2: break
                        if xoi[0]+1 == xoj[0] and xoi[1]+1 == xoj[1] and \
                           xoi[2]   == xoj[2] and xoi[3]   == xoj[3]:
                            excludedXos.add(xoi)
                            excludedXos.add(xoj)
                            extraXos.add( (xoi[0]+0.5,xoi[1]+0.5,xoi[2],xoi[3]) )
                xos = {xo for xo in allXos if xo not in excludedXos}
                xos.update(extraXos)
            
                ## Set dictionary entry
                xos = list(xos)
                if len(xos) > 0:
                    tmp[hid2] = xos

        ## Build dictionary of dsDNA crossovers
        xoDicts = [dict() for i in range(numHID)]
        for hid1 in range(numHID):
            tmp = xoDicts[hid1]
            for hid2 in range(numHID):
                allXos       = {(z1,z2,f1,f2) for h1,f1,z1,h2,f2,z2 in dsXoList if h1 == hid1 and h2 == hid2}
                allXos.update( {(z2,z1,f2,f1) for h1,f1,z1,h2,f2,z2 in dsXoList if h2 == hid1 and h1 == hid2} )
                allXos = sorted(list(allXos), key = lambda x: (x[0],x[1]))

                ## Replace each double-crossover with a single one
                excludedXos, extraXos = [set(),set()]
                for i in range(len(allXos)):
                    xoi = allXos[i]
                    for j in range(i+1,len(allXos)):
                        xoj = allXos[j]
                        if xoj[0] - xoi[0] > 2: break
                        if xoi[0]+1 == xoj[0] and xoi[1]+1 == xoj[1] and \
                           xoi[2]   == xoj[2] and xoi[3]   == xoj[3]:
                            excludedXos.add(xoi)
                            excludedXos.add(xoj)
                            extraXos.add( (xoi[0]+0.5,xoi[1]+0.5,xoi[2],xoi[3]) )
                xos = {xo for xo in allXos if xo not in excludedXos}
                xos.update(extraXos)
            
                ## Set dictionary entry
                xos = list(xos)
                if len(xos) > 0:
                    tmp[hid2] = xos

        ## Build dictionary of ssDNA crossovers
        ssXoDicts = [dict() for i in range(numHID)]
        for hid1 in range(numHID):
            tmp = ssXoDicts[hid1]
            for hid2 in range(numHID):
                xos       = {(z1,z2,f1,f2) for h1,f1,z1,h2,f2,z2 in ssXoList if h1 == hid1 and h2 == hid2}
                xos.update( {(z2,z1,f2,f1) for h1,f1,z1,h2,f2,z2 in ssXoList if h2 == hid1 and h1 == hid2} )
                xos = sorted(list(xos), key = lambda x: (x[0],x[1]))
                ## Set dictionary entry
                if len(xos) > 0:
                    tmp[hid2] = xos

        ## Build helices 
        for hid in range(numHID):
            # print("Working on helix",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] )
            
            ## Build list of strand ends and list of mandatory node locations
            ends1,ends2 = self._helixStrandsToEnds(helixStrands)
            # xoZids = [x for x in xoDicts2[hid].keys()]

            ## Find crossovers for this helix
            xoZids = [x[1] for h0 in range(hid) if hid in xoDicts[h0] for x in xoDicts[h0][hid]]
            xoZids.extend([x[0] for hid2,xos in xoDicts[hid].items() for x in xos])
            xoZids.extend([x[1] for h0 in range(hid) if hid in ssXoDicts[h0] for x in ssXoDicts[h0][hid]])
            xoZids.extend([x[0] for hid2,xos in ssXoDicts[hid].items() for x in xos])
            reqNodeZids = sorted(list(set( ends1 + ends2 + xoZids ) ) )
            
            ## 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) ]
            
           
            ## Build helix by adding nodes
            beadHelix = self.addHelix(part,hid)
            if hid in ():
                print("%d nodes:" %hid,reqNodeZids)
                print("orig xos:",[xo for xo in xover_list if xo[0] == hid or xo[3] == hid])
                print("xosZids:", sorted(xoZids) )
                print("strandOccupancy1:",strandOccupancies[0])
                print("strandOccupancy2:",strandOccupancies[1])

            prevNode = None
            for i in range( len(reqNodeZids)-1 ):
                zid1,zid2 = reqNodeZids[i:i+2]
                
                ## Check that there are nts between zid1 and zid2 before adding nodes
                zMid = int(0.5*(zid1+zid2))
                if zMid in strandOccupancies[0] and zMid in strandOccupancies[1]:
                    ## dsDNA
                    maxBpsPerNode = maxBpsPerDNode
                if zMid in strandOccupancies[0] or zMid in strandOccupancies[1]:
                    ## ssDNA
                    maxBpsPerNode = maxNtsPerSNode
                else:
                    continue

                numBps = zid2-zid1
                # if numBps < 2:
                #     print(hid,zid1,zid2)
                # assert(numBps >= 1)

                for ins_idx,length in insertions:
                    ## TODO: ensure placement of insertions is correct
                    ##   (e.g. are insertions at the ends handled correctly?)
                    if ins_idx < zid1:
                        continue
                    if ins_idx >= zid2:
                        break
                    numBps += length

                # if numBps = 0:
                #     print("WARNING: found stretch of DNA with 0 length; skipping")
                #     next

                nodesBetween = round( float(numBps-1)/maxBpsPerNode )
                if nodesBetween < 0: 
                    nodesBetween = 0
                bpsPerNode = float(numBps)/(nodesBetween+1)
                if bpsPerNode == 0: 
                    bpsPerNode = 0.1
                zidPerNode = float(zid2-zid1)/(nodesBetween+1)

                try:
                    if prevNode is None:
                        prevNode = beadHelix.addNode( zid1, strandOccupancies )

                    for i in range(nodesBetween):
                        node = beadHelix.addNode( zid1+(i+1)*zidPerNode, strandOccupancies )
                        self._connectNodes(prevNode, node, bpsPerNode)
                        prevNode = node

                    node = beadHelix.addNode( zid2, strandOccupancies )
                    self._connectNodes(prevNode, node, bpsPerNode)
                except:
                    print(hid,zid1,zid2,nodesBetween,bpsPerNode)
                    raise Exception("ERROR")

                prevNode = None
                if (int(floor(zid2+1)) in strandOccupancies[0]) or \
                   (int(floor(zid2+1)) in strandOccupancies[1]):
                    prevNode = node

        ## Add extra intrahelical bonds
        ## Add crossovers
        for entry in extraInterhelicalBondList:
            h1,f1,z1,h2,f2,z2 = entry
669
670
671
672
673
674
675
676
677
678
679
            n1 = self.helices[h1].nodes[z1]
            n2 = self.helices[h2].nodes[z2]

            try:
                self._connectNodes(n1,n2,1)
            except:
                assert(True)
            try:
                self._connectNodes(n2,n1,1)
            except:
                assert(True)
cmaffeo2's avatar
cmaffeo2 committed
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

        ## Add crossovers
        for hid1 in range(numHID):
            for hid2, xos in xoDicts[hid1].items():
                for xo in xos:
                    self._addCrossover(hid1,hid2,xo)

        ## Add ssDNA xovers    
        for hid1 in range(numHID):
            for hid2, xos in ssXoDicts[hid1].items():
                for xo in xos:
                    self._addSsCrossover(hid1,hid2,xo)


        return

    def _connectNodes(self, below, above, sep):
        below.addNodeAbove(above, sep)
        above.addNodeBelow(below, sep)
        
    def _addCrossover(self, hid1, hid2, xo):
        zid1, zid2, isFwd1, isFwd2 = xo
        node1 = self.helices[hid1].nodes[zid1]
        node2 = self.helices[hid2].nodes[zid2]

        ## TODO add polarity
        polarity = 0
        node1.addXover(node2, (isFwd1, isFwd2))
        node2.addXover(node1, (isFwd2, isFwd1))

    def _addSsCrossover(self, hid1, hid2, xo):
        zid1, zid2, isFwd1, isFwd2 = xo
        node1 = self.helices[hid1].nodes[zid1]
        node2 = self.helices[hid2].nodes[zid2]

        ## TODO add polarity
        polarity = 0
        node1.addSsXover(node2, isFwd1)
        node2.addSsXover(node1, isFwd2)

720
721
722
723
724
725
726
727
728
729
730
731
732
733
    def addModel(self, model):
        assert( isinstance(model, type(self)) )

        hidOffset = max( self.helices.keys() ) + 1
        # nidOffset = self.numParticles
        for hid,h in model:
            self.helices[hid+hidOffset] = h

        self.numParticles += model.numParticles

        self.buildOrderedParticlesList()
        self._setTypes()
        self._countParticleTypes()

cmaffeo2's avatar
cmaffeo2 committed
734
735
    def backmap(self, simplerModel, simplerModelCoords, 
                dsDnaHelixNeighborDist=50, dsDnaAllNeighborDist=30,
736
                ssDnaHelixNeighborDist=25, ssDnaAllNeighborDist=25):
cmaffeo2's avatar
cmaffeo2 committed
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

        ## Assign each bead to a bead in simplerModel
        mapToSimplerModel = dict()
        cgWeight = dict()
        for hDict,cgHDict in zip(self,simplerModel):
            assert(hDict[0] == cgHDict[0])
            h,cgH = [x[1] for x in (hDict,cgHDict)] # get helix

            zIdxs = np.array( sorted([i for i,b in cgH]) )
            for i,b in h:
                cgi = np.searchsorted(zIdxs,i,side='left',sorter=None)
                cgi, = [zIdxs[x] if x < len(zIdxs) else zIdxs[-1] for x in (cgi,)]
                mapToSimplerModel[b.idx] = [cgH.nodes[x] for x in (cgi,)]

            for i,b in h.orientationNodes.items():
                cgi = np.searchsorted(zIdxs,i,side='left',sorter=None)
                cgi, = [zIdxs[x] if x < len(zIdxs) else zIdxs[-1] for x in (cgi,)]
                mapToSimplerModel[b.idx] = [cgH.nodes[x] for x in (cgi,)]
                
        ## Find new axis and position of each bead using neighborhood
        beads = [b for h in self for i,b in h[1].nodes.items()]

        ## Find transformation for each bead of simplerModel
        trans = dict()
        for b in list(set([b for i,bs in mapToSimplerModel.items() for b in bs])):
            helixCutoff = dsDnaHelixNeighborDist if b.type[0] in ('d','O') else ssDnaHelixNeighborDist
            allCutoff = dsDnaAllNeighborDist if  b.type[0] in ('d','O') else ssDnaAllNeighborDist

765
766
767
768
769
770
            def positionsAreLinear(pos):
                if len(pos) == 0: return False
                center = np.mean(pos,axis=0)
                cPos = pos-center
                return np.sum( np.abs( np.linalg.eig( cPos.T.dot(cPos) )[0] ) > 1e-3 ) == 3

cmaffeo2's avatar
cmaffeo2 committed
771
772
            ids = []
            attempts = 0
773
774
            posOld = []
            while len(ids) <= 3 or not positionsAreLinear(posOld):
cmaffeo2's avatar
cmaffeo2 committed
775
776
                if attempts > 15: raise Exception("Too many attempts to find a neighborhood for backmaping bead %d" % b.idx)
                ids = simplerModel._getNeighborhoodIds(b, simplerModelCoords, helixCutoff, allCutoff)
777
                posOld = np.array( [simplerModel.particles[i][0].initialPosition for i in ids] )
cmaffeo2's avatar
cmaffeo2 committed
778
779
                allCutoff *= 1.2
                attempts+=1
780
781
782
783

            if attempts > 1:
                print("Warning, increased allCutoff to",allCutoff)

cmaffeo2's avatar
cmaffeo2 committed
784
            posNew = np.array( [simplerModelCoords[i] for i in ids] )
785
            trans[b.idx] = minimizeRmsd( posOld, posNew )
cmaffeo2's avatar
cmaffeo2 committed
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

        ## Optionally smooth orientations
            
        ## Apply transformation to each bead of self
        beads.extend( [b for h in self for i,b in h[1].orientationNodes.items()] )
        for b in beads:
            cgb, = mapToSimplerModel[b.idx]
            cgi = cgb.idx
            r0 = simplerModel.particles[cgi][0].initialPosition
            R,c0,c1 = trans[cgi]
            b.position = (b.initialPosition - r0).dot(R) + simplerModelCoords[cgi]
            assert( np.all(np.isreal( b.position )) )
        

    def _getNeighborhoodIds(self, bead, coords, helixCutoff=50, allCutoff=np.sqrt(35)):
        i = bead.idx

        coords0 = self.initialCoords
        # print(coords0[i,:])
        coordsI = np.outer(coords0[i,:],np.ones([len(coords0),1])).T
        dr2Initial = np.sum((coords0 - coordsI)**2, axis=-1)
        dr2Final = np.sum((coords - coords[i,:])**2, axis=-1)
        
        ## Include all in same helix within 5 nm of bead after simulation        
        ret = list( np.where( (dr2Final < helixCutoff**2) * (self._nodeHids == bead.helix.hid) )[0] )
        ret = list( np.where( (dr2Final < helixCutoff**2) * (self._nodeHids == bead.helix.hid) * (dr2Initial < 100**2) )[0] )

        ## Include all within 3.5 nm both before AND after simulation
        ret.extend( list( np.where( (dr2Final < allCutoff**2) * (dr2Initial < allCutoff**2) )[0] ) )
        return sorted(list(set(ret)))

    # -------------------------- #
    # Methods for querying model #
    # -------------------------- #
    def _getIntrahelicalNodeSeries(self,seriesLen):
        nodeSeries = set() 
        for hid,hlx in self:
            for zid,n in hlx:
                nodeList,sepList = n.getNodesAbove(seriesLen-1, inclusive = True)
                if len(nodeList) == seriesLen:
                    nodeList = tuple(nodeList)
                    sepList = tuple(sepList)
                    nodeSeries.add( tuple((nodeList,sepList)) )
        return nodeSeries

    def _getIntrahelicalBonds(self):
        return self._getIntrahelicalNodeSeries(2)

    def _getIntrahelicalAngles(self):
        return self._getIntrahelicalNodeSeries(3)

    def _getOrientationBonds(self):
        nodeSeries = set() 
        for hid,hlx in self:
            for zid,n in hlx:
                if n.orientationNode is not None:
                    nodeSeries.add( tuple(((n.orientationNode,n),(0.2,))) )
        return nodeSeries

    def _getOrientationAngles(self):
        nodeSeries = set() 
        for hid,hlx in self:
            for zid,n in hlx:
                if n.orientationNode is not None and n.nodeAbove is not None:
                    nodeSeries.add( tuple(((n.orientationNode,n,n.nodeAbove),(0.2, n.nodeAboveSep))) )
        return nodeSeries

    def _getOrientationDihedrals(self):
        nodeSeries = set() 
        for hid,hlx in self:
            for zid,n1 in hlx:
                if n1.nodeAbove is not None:
                    n2 = n1.nodeAbove
                    if n1.orientationNode is not None and n2.orientationNode is not None:
                        nodeSeries.add( tuple(((n1.orientationNode,n1,n2,n2.orientationNode),
                                              (0.2, n1.nodeAboveSep, 0.2))) )
        return nodeSeries
                                    


    def _getCrossoverBonds(self):
        return { ((n, xo[0]), xo[1])
                 for hid,hlx in self
                 for zid,n in hlx for xo in n.xovers if n.idx < xo[0].idx }

    def _getSsCrossoverBonds(self):
        return { ((n, xo[0]), xo[1]) 
                 for hid,hlx in self
                 for zid,n in hlx for xo in n.ssXovers if n.idx < xo[0].idx }


    def _getCrossoverAnglesAndDihedrals(self):
        angles,dihedrals = [set(),set()]
        contiguousCrossovers = []

        for hid,hlx in self.helices.items():
            crossovers = []
            bpsBetween = 0
            for zid,n in hlx:
                ## Search for contiguous crossovers
                if n.nodeBelow is None or n.type[0] != "d":
                    ## Found ssDNA or a gap; reset search
                    if len(crossovers) > 0:
                        contiguousCrossovers.append(crossovers)
                    crossovers = []
                    bpsBetween = 0

                if n.nodeBelow is not None:
                    bpsBetween += n.nodeBelowSep
                if len(n.xovers) > 0:
                    crossovers.append( (n,bpsBetween) )

            if len(crossovers) > 0:
                contiguousCrossovers.append(crossovers)

        ## Process contiguousCrossovers
        for crossovers in contiguousCrossovers:
            for i in range(len(crossovers)-1):
                ni,bpi = crossovers[i]
                # for j in range(i+1,len(crossovers)):
                for j in range(i+1,i+2): # Just look at adjacent crossovers
                    assert(j == i+1)
                    nj,bpj = crossovers[j]
                    bpsBetween = bpj-bpi
                    if bpsBetween < 60:
                        for xo1 in ni.xovers:
                            for xo2 in nj.xovers:
                                assert( bpsBetween != 0 )
                                angles.add( ((xo1[0], ni, nj), bpsBetween) )
                                angles.add( ((ni, nj, xo2[0]), bpsBetween) )
                                dihedrals.add( ((xo1[0], ni, nj, xo2[0]), bpsBetween, xo1[1], xo2[1]) )
                    else:
                        break
        return angles, dihedrals
        

    def _removeIntrahelicalConnectionsAbove(self, cutoff):
        bonds = self._getIntrahelicalBonds()
        for b in bonds:
            n1,n2 = b[0]
            r2 = np.sum( (n1.position - n2.position)**2 )
            if r2 > cutoff**2:
                if n1.above == n2:
                    assert(n2.below == n1)
                    n1.above = None
                    n2.below = None
                elif n2.above == n1:
                    assert(n1.below == n2)
                    n1.below = None
                    n2.above = None
                else:
                    raise

    def _removeCrossoversAbove(self, cutoff):
        # bonds = self._getCrossoverBonds()
        for hid,hlx in self:
            for zid,n1 in hlx:
                newXovers = []
                for xo in n1.xovers:
                    n2 = xo[0]
                    r2 = np.sum( (n1.position - n2.position)**2 )
                    if r2 < cutoff**2:
                        newXovers.append(xo)
                n1.xovers = newXovers


952
953
954
955
956
    # def _getBonds(self):
    #     bonds = self._getIntrahelicalBonds()
    #     bonds.update( self._getCrossoverBonds() )
    #     bonds.update( self._getSsCrossoverBonds() )
    #     return bonds
cmaffeo2's avatar
cmaffeo2 committed
957
958
959
960
961
962
963
964


    # -------------------------- #
    # Methods for prinitng model #
    # -------------------------- #
    def writePdb(self, filename):
        with open(filename,'w') as fh:
            ## Write header
965
            fh.write("CRYST1    1000.    1000.    1000.  90.00  90.00  90.00 P 1           1\n")
cmaffeo2's avatar
cmaffeo2 committed
966
967

            ## Write coordinates
968
            formatString = "ATOM  {:>5d} {:^4s}{:1s}{:3s} {:1s}{:>5s}   {:8.3f}{:8.3f}{:8.3f}{:6.2f}{:6.2f}{:2s}{:2f}\n"
cmaffeo2's avatar
cmaffeo2 committed
969
970
971
972
973
974
975
976
977
978
979
            for n,hid,zid in self.particles:
                ## http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#ATOM
                idx = n.idx
                name = n.type
                resname = name[:3]
                chain = "A"
                charge = 0
                occ = hid
                beta = zid
                x,y,z = [x for x in n.position]
                
980
                assert(idx < 1e5)
cmaffeo2's avatar
cmaffeo2 committed
981
982
983
                resid = "{:<4d}".format(idx)

                fh.write( formatString.format(
984
                    idx, name[:1], "", resname, chain, resid, x, y, z, occ, beta, "", charge ))
cmaffeo2's avatar
cmaffeo2 committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        return
        
    def writePsf(self, filename):
        with open(filename,'w') as fh:
            ## Write header
            fh.write("PSF NAMD\n\n") # create NAMD formatted psf
            
            ## ATOMS section
            idx=1
            for hid,hlx in self:
                for x in hlx:
                    idx += 1
                idx += len(hlx.orientationNodes)
                # for x in hlx.orientationNodes.items():
                #     idx += 1

For faster browsing, not all history is shown. View entire blame