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

10
import nbPot
cmaffeo2's avatar
cmaffeo2 committed
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
from coords import minimizeRmsd, quaternionToMatrix3, rotationAboutAxis


class HarmonicPotential():
    def __init__(self, k, r0, rRange=(0,50), resolution=0.1, maxForce=None, prefix="potentials/"):
        self.k = k
        self.r0 = r0
        self.maxForce = maxForce
        self.rRange = rRange
        self.prefix = prefix
        self.periodic = False
        self.type = "None"
        self._kscale = None
        self._init_hook()

    def filename(self):
        # raise NotImplementedError("Not implemented")
        return "%s%s-%.3f-$.3f.dat" % (self.prefix, self.type,
                                       self.k*self._kscale, self.r0)

    def write_file(self):
        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)
            f[f>maxForce] = maxForce
            f[f<-maxForce] = -maxForce
            u[0] = 0
            u[1:] = np.cumsum(f*np.diff(r))
        np.savetxt( self.filename(), np.array([r, u]).T, fmt="%f" )

    def __hash__(self):
        assert(self.type != "None")
        return hash((self.type, self.k, self.r0, self.rRange, self.resolution, self.maxForce, self.prefix, self.periodic))

    def __eq__(self, other):
        for a in ("type", "k", "r0", "rRange", "resolution", "maxForce", "prefix", "periodic"):
            if self.__dict__[a] != other.__dict__[a]:
                return False
        return True

class NonBonded(HarmonicPotential):
    def _init_hook(self):
        self.type = "nonbonded"
        self._kscale = 1.0

class Bond(HarmonicPotential):
    def _init_hook(self):
        self.type = "bond"
        self._kscale = 1.0

class Angle(HarmonicPotential):
    def _init_hook(self):
        self.type = "angle"
        self._kscale = (180.0/pi)**2

class Dihedral(HarmonicPotential):
    def _init_hook(self):
        self.periodic = True
        self.type = "dihedral"
        self._kscale = (180.0/pi)**2
83

84
85
86
class Node():
    def __init__(self, helix, pos, type="dsDNA"):
        self.helix    = helix
cmaffeo2's avatar
cmaffeo2 committed
87
        self.position = np.array(pos)
cmaffeo2's avatar
cmaffeo2 committed
88
        self.initialPosition = np.array(pos)
89
90
91
92
        self.type     = type
        self.nodeAbove = None
        self.nodeBelow = None
        self.xovers = []
93
        self.ssXovers = []
94
        self.idx = helix.model.numParticles
cmaffeo2's avatar
cmaffeo2 committed
95
        helix.model.numParticles += 1
96
97

    def addNodeAbove(self, node, separation):
98
        assert(self.nodeAbove is None)
99
100
101
        self.nodeAbove = node
        self.nodeAboveSep = separation # bp
    def addNodeBelow(self, node, separation):
102
        assert(self.nodeBelow is None)
103
104
105
        self.nodeBelow = node
        self.nodeBelowSep = separation # bp

cmaffeo2's avatar
cmaffeo2 committed
106
    def addXover(self, node, fwds, double=False):
107
        ## TODO: what is meant by polarity?
cmaffeo2's avatar
cmaffeo2 committed
108
        self.xovers.append( (node,fwds,double) )
109

cmaffeo2's avatar
cmaffeo2 committed
110
111
    def addSsXover(self, node, fwds):
        self.ssXovers.append( (node,fwds) )
112
113
    
    def getNodesAbove(self,numNodes,inclusive=False):
114
115
        assert( type(numNodes) is int and numNodes > 0 )

116
117
118
119
        nodeList,sepList = [[],[]]
        n = self
        if inclusive:
            nodeList.append(n)
120

121
122
123
124
125
126
        for i in range(numNodes):
            if n.nodeAbove is None: break
            n = n.nodeAbove
            nodeList.append(n)
            sepList.append(n.nodeBelowSep)
            
127
128
        return nodeList,sepList

129
130
131
132
133
134
135
136
137
138
139
140
141
142
    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)
            
143
        return nodeList,sepList
cmaffeo2's avatar
cmaffeo2 committed
144

cmaffeo2's avatar
cmaffeo2 committed
145
class helix():
146
147
148
    def __init__(self, model, part, hid):
        self.model = model
        self.props = part.getModelProperties().copy() # TODO: maybe move this out of here
cmaffeo2's avatar
cmaffeo2 committed
149
        self.nodes = dict()
cmaffeo2's avatar
cmaffeo2 committed
150
        self.hid = hid
cmaffeo2's avatar
cmaffeo2 committed
151
152
153
154
155
156
157
158
159
160
161

        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
cmaffeo2's avatar
cmaffeo2 committed
162
            self.zIdxToPos = lambda idx: (x*10,y*10,-3.4*idx)
cmaffeo2's avatar
cmaffeo2 committed
163

164

cmaffeo2's avatar
cmaffeo2 committed
165
166
167
168
169
170
    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]:
171
            # type = "dsDNA"
cmaffeo2's avatar
cmaffeo2 committed
172
173
            type = "ssDNA"
        else:
174
            raise Exception( "Attempt to add a node at %d where there is no DNA!\n Strand at indeces: %s" % (i,strandOccupancies) )
cmaffeo2's avatar
cmaffeo2 committed
175
176
177
        ## Add the node
        n = Node(self, self.zIdxToPos(zIdx), type)
        if zIdx in self.nodes:
178
            raise Exception("Attempted to add a node in the same location (%d:%.1f) twice!" % (self.hid,zIdx))
cmaffeo2's avatar
cmaffeo2 committed
179
        self.nodes[zIdx] = n
180

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

cmaffeo2's avatar
cmaffeo2 committed
185
        return n
cmaffeo2's avatar
cmaffeo2 committed
186
187
188
189
190

    def getOrigin(self):
        return self.origin

    def __iter__(self):
cmaffeo2's avatar
cmaffeo2 committed
191
        for x in sorted(self.nodes.items(), key=lambda x: x[0]):
cmaffeo2's avatar
cmaffeo2 committed
192
            yield x
cmaffeo2's avatar
cmaffeo2 committed
193
    
cmaffeo2's avatar
cmaffeo2 committed
194
class beadModel():
195

196
    def __init__(self, part, twistPersistenceLength=75.0, maxBpsPerDNode=4, maxNtsPerSNode=2):
197
        self.numParticles = 0
cmaffeo2's avatar
cmaffeo2 committed
198
        self.helices = dict()
199
        self.particles = None
200
        self.particleTypeCounts = None
201

202
        # self._nbParams = set()
203
204
205
206
        self._bondParams = set()
        self._angleParams = set()
        self._dihedralParams = set()

207
        self._nbParamFiles = []
208
209
210
        self._bondParamFiles = set()
        self._angleParamFiles = set()
        self._dihedralParamFiles = set()
211
212
213

        self.twistPersistenceLength = twistPersistenceLength

214
215

        self._buildModel(part, maxBpsPerDNode, maxNtsPerSNode)
cmaffeo2's avatar
cmaffeo2 committed
216
        
217
        ## Post process the model
218
        self.buildOrderedParticlesList()
219
        self._setTypes()
220
        self._countParticleTypes()
cmaffeo2's avatar
cmaffeo2 committed
221
        self.buildOrderedParticlesList()
222

cmaffeo2's avatar
cmaffeo2 committed
223
    def __iter__(self):
cmaffeo2's avatar
cmaffeo2 committed
224
        for x in sorted(self.helices.items(), key=lambda x: x[0]):
cmaffeo2's avatar
cmaffeo2 committed
225
            yield x
226

227
    def buildOrderedParticlesList(self):
228
        ## Create ordered list
cmaffeo2's avatar
cmaffeo2 committed
229
        particles = [(n,hid,zid) for hid,hlx in self for zid,n in hlx]        
230
231
232
233
234
        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
cmaffeo2's avatar
cmaffeo2 committed
235
            
cmaffeo2's avatar
cmaffeo2 committed
236
        self.initialCoords = np.array([p[0].initialPosition for p in self.particles])
cmaffeo2's avatar
cmaffeo2 committed
237
        self._nodeHids = np.array([p[1] for p in self.particles])
238

239
240
241
242
243
244
245
246
247
248
249
250
251
252
    def _setTypes(self):
        for p,hid,zid in self.particles:
            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)

253
254
255
256
257
258
259
260
261
    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
cmaffeo2's avatar
cmaffeo2 committed
262

cmaffeo2's avatar
cmaffeo2 committed
263
    def addHelix(self, part, hid):
264
        h = helix(self,part,hid)
cmaffeo2's avatar
cmaffeo2 committed
265
266
        self.helices[hid] = h
        return h
cmaffeo2's avatar
cmaffeo2 committed
267
    
268
269
    def _helixStrandsToEnds(self, helixStrands):

cmaffeo2's avatar
cmaffeo2 committed
270
271
272
273
        """Utility method to convert cadnano strand lists into list of
        indices of terminal points"""

        endLists = [[],[]]
274
275
276
277
278
279
280
281
282
283
        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
284
285
            if lastStrand is not None:
                endList.append(lastStrand[1])
286
        return endLists
cmaffeo2's avatar
cmaffeo2 committed
287
    
288
    def simulate(self, outputPrefix, outputDirectory='output', numSteps=100000000, timestep=100e-6, gpu=0, arbd=None):
cmaffeo2's avatar
cmaffeo2 committed
289
        assert(type(gpu) is int)
290
        # assert(type(numSteps) is int)
cmaffeo2's avatar
cmaffeo2 committed
291
292
        if outputDirectory == '': outputDirectory='.'
            
cmaffeo2's avatar
cmaffeo2 committed
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
        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")

cmaffeo2's avatar
cmaffeo2 committed
308
309
310
311
312
313
        if not os.path.exists(outputDirectory):
            os.makedirs(outputDirectory)
        elif not os.path.isdir(outputDirectory):
            raise Exception("outputDirectory '%s' is not a directory!" % outputDirectory)
            

cmaffeo2's avatar
cmaffeo2 committed
314
315
        self.writePdb( outputPrefix + ".pdb" )
        self.writePsf( outputPrefix + ".psf" )
316
        self.writeArbdFiles( outputPrefix, numSteps=numSteps, timestep=timestep )
cmaffeo2's avatar
cmaffeo2 committed
317

318
319
320
        env = os.environ.copy()
        env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"

cmaffeo2's avatar
cmaffeo2 committed
321
        ## http://stackoverflow.com/questions/18421757/live-output-from-subprocess-command
cmaffeo2's avatar
cmaffeo2 committed
322
323
324
325
326
327
        # 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))
328
        process = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, universal_newlines=True)
cmaffeo2's avatar
cmaffeo2 committed
329
        for line in process.stdout:
cmaffeo2's avatar
cmaffeo2 committed
330
331
        # for line in iter(process.stdout.readline, b''):
            sys.stdout.write(line)
332
            sys.stdout.flush()
cmaffeo2's avatar
cmaffeo2 committed
333
            # sys.stdout.write(line.decode(sys.stdout.encoding))
cmaffeo2's avatar
cmaffeo2 committed
334
    
335
336
337
    # -------------------------- #
    # Methods for building model #
    # -------------------------- #
338
    def _buildModel(self, part, maxBpsPerDNode, maxNtsPerSNode):
cmaffeo2's avatar
cmaffeo2 committed
339
340
341
        # maxVhelixId = part.getIdNumMax()
        
        props = part.getModelProperties().copy()
342
        # print(props)
cmaffeo2's avatar
cmaffeo2 committed
343
344
345
346
347
348

        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()
349
            # print(' VIRTUAL HELICES:', vh_props)
cmaffeo2's avatar
cmaffeo2 committed
350
351
352
353
            # # print(' ORIGINS:', origins)
            # group_props['virtual_helices'] = vh_props
            # group_props['origins'] = origins
            
cmaffeo2's avatar
cmaffeo2 committed
354
355
        ## TODO: compartmentalize following
        ## Loop over virtual helices and build lists of strands 
cmaffeo2's avatar
cmaffeo2 committed
356
357
358
359
360
361
362
363
        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
364
                vh_list.append((id_num, 0))
cmaffeo2's avatar
cmaffeo2 committed
365
                strand_list.append(None)
366
                # prop_list.append(None)
cmaffeo2's avatar
cmaffeo2 committed
367
368
369
370
371
372
373
374
375
376
            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))

377
378
379
380
381
                # if id_num < 2:
                #     print( fwd_idxs )
                #     for s in fwd_ss:
                #         print( s.insertionsOnStrand() )
                
cmaffeo2's avatar
cmaffeo2 committed
382
383
384
                ## prop_list.append((fwd_colors, rev_colors))
                # for s in strand_list:
                #     print( s )
385
                
386
387
388
389

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

390
391
392
393
        ## Expand strand_lists for crossover filtering 
        expandedStrandList = []
        for fwdRevStrands in strand_list:
            tmp = []
394
395
396
397
398
            if fwdRevStrands is not None:
                for strands in fwdRevStrands:
                    fwdOrRev = []
                    for a,b in strands: fwdOrRev.extend(range(a,b+1))
                    tmp.append(fwdOrRev)
399
            expandedStrandList.append(tmp)
400

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

409
410
            ds1 = z1 in expandedStrandList[h1][0] and z1 in expandedStrandList[h1][1]
            ds2 = z2 in expandedStrandList[h2][0] and z2 in expandedStrandList[h2][1]
411
412
413
414
415
416
417
418
419
420
421
422

            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:
423
424
                    dsXoList.append(entry)
                else:
425
                    ssXoList.append(entry)
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

        ## 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
cmaffeo2's avatar
cmaffeo2 committed
457
        xoDicts = [dict() for i in range(numHID)]
458
459
        for hid1 in range(numHID):
            tmp = xoDicts[hid1]
460
461
462
            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} )
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
                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)
cmaffeo2's avatar
cmaffeo2 committed
479
            
480
481
482
483
484
                ## Set dictionary entry
                xos = list(xos)
                if len(xos) > 0:
                    tmp[hid2] = xos

485
486
487
488
489
490
491
492
493
494
495
496
        ## 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

cmaffeo2's avatar
cmaffeo2 committed
497
        ## Build helices 
cmaffeo2's avatar
cmaffeo2 committed
498
        for hid in range(numHID):
499
500
            # print("Working on helix",hid)
            
cmaffeo2's avatar
cmaffeo2 committed
501
            helixStrands = strand_list[hid]
502
503
            if helixStrands is None: 
                continue
504
505
506
507
508

            ## 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] )
            
cmaffeo2's avatar
cmaffeo2 committed
509
            ## Build list of strand ends and list of mandatory node locations
510
            ends1,ends2 = self._helixStrandsToEnds(helixStrands)
511
512
513
            # xoZids = [x for x in xoDicts2[hid].keys()]

            ## Find crossovers for this helix
514
            xoZids = [x[1] for h0 in range(hid) if hid in xoDicts[h0] for x in xoDicts[h0][hid]]
515
            xoZids.extend([x[0] for hid2,xos in xoDicts[hid].items() for x in xos])
516
            xoZids.extend([x[1] for h0 in range(hid) if hid in ssXoDicts[h0] for x in ssXoDicts[h0][hid]])
517
            xoZids.extend([x[0] for hid2,xos in ssXoDicts[hid].items() for x in xos])
518
            reqNodeZids = sorted(list(set( ends1 + ends2 + xoZids ) ) )
cmaffeo2's avatar
cmaffeo2 committed
519
520
521
522
523
524
525
526
            
            ## 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
cmaffeo2's avatar
cmaffeo2 committed
527
            beadHelix = self.addHelix(part,hid)
528
529
530
531
532
533
            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])
534
535
536

            prevNode = None
            for i in range( len(reqNodeZids)-1 ):
537
                zid1,zid2 = reqNodeZids[i:i+2]
538
539
540
                
                ## Check that there are nts between zid1 and zid2 before adding nodes
                zMid = int(0.5*(zid1+zid2))
cmaffeo2's avatar
cmaffeo2 committed
541
542
                if zMid in strandOccupancies[0] and zMid in strandOccupancies[1]:
                    ## dsDNA
543
                    maxBpsPerNode = maxBpsPerDNode
cmaffeo2's avatar
cmaffeo2 committed
544
545
                if zMid in strandOccupancies[0] or zMid in strandOccupancies[1]:
                    ## ssDNA
546
                    maxBpsPerNode = maxNtsPerSNode
547
                else:
cmaffeo2's avatar
cmaffeo2 committed
548
                    continue
cmaffeo2's avatar
cmaffeo2 committed
549

cmaffeo2's avatar
cmaffeo2 committed
550
                numBps = zid2-zid1
551
552
                # if numBps < 2:
                #     print(hid,zid1,zid2)
553
                # assert(numBps >= 1)
554

555
556
557
558
559
560
561
562
                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
563

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

cmaffeo2's avatar
cmaffeo2 committed
568
                nodesBetween = round( float(numBps-1)/maxBpsPerNode )
569
570
                if nodesBetween < 0: 
                    nodesBetween = 0
cmaffeo2's avatar
cmaffeo2 committed
571
                bpsPerNode = float(numBps)/(nodesBetween+1)
572
573
                if bpsPerNode == 0: 
                    bpsPerNode = 0.1
574
                zidPerNode = float(zid2-zid1)/(nodesBetween+1)
cmaffeo2's avatar
cmaffeo2 committed
575

576
577
                try:
                    if prevNode is None:
cmaffeo2's avatar
cmaffeo2 committed
578
                        prevNode = beadHelix.addNode( zid1, strandOccupancies )
cmaffeo2's avatar
cmaffeo2 committed
579

580
                    for i in range(nodesBetween):
cmaffeo2's avatar
cmaffeo2 committed
581
                        node = beadHelix.addNode( zid1+(i+1)*zidPerNode, strandOccupancies )
582
583
                        self._connectNodes(prevNode, node, bpsPerNode)
                        prevNode = node
cmaffeo2's avatar
cmaffeo2 committed
584

cmaffeo2's avatar
cmaffeo2 committed
585
                    node = beadHelix.addNode( zid2, strandOccupancies )
586
587
                    self._connectNodes(prevNode, node, bpsPerNode)
                except:
588
                    print(hid,zid1,zid2,nodesBetween,bpsPerNode)
589
                    raise Exception("ERROR")
cmaffeo2's avatar
cmaffeo2 committed
590

cmaffeo2's avatar
cmaffeo2 committed
591
                prevNode = None
592
593
                if (int(floor(zid2+1)) in strandOccupancies[0]) or \
                   (int(floor(zid2+1)) in strandOccupancies[1]):
cmaffeo2's avatar
cmaffeo2 committed
594
                    prevNode = node
595
596
597
598
599

        ## Add extra intrahelical bonds
        ## Add crossovers
        for entry in extraInterhelicalBondList:
            h1,f1,z1,h2,f2,z2 = entry
600
601
602
603
604
605
606
607
608
609
610
            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)
611
612
                    

cmaffeo2's avatar
cmaffeo2 committed
613
614
        ## Add crossovers
        for hid1 in range(numHID):
615
616
            for hid2, xos in xoDicts[hid1].items():
                for xo in xos:
617
618
                    self._addCrossover(hid1,hid2,xo)

cmaffeo2's avatar
cmaffeo2 committed
619
        ## Add ssDNA xovers    
620
621
622
623
624
        for hid1 in range(numHID):
            for hid2, xos in ssXoDicts[hid1].items():
                for xo in xos:
                    self._addSsCrossover(hid1,hid2,xo)

cmaffeo2's avatar
cmaffeo2 committed
625

cmaffeo2's avatar
cmaffeo2 committed
626
        return
cmaffeo2's avatar
cmaffeo2 committed
627

628
629
630
    def _connectNodes(self, below, above, sep):
        below.addNodeAbove(above, sep)
        above.addNodeBelow(below, sep)
cmaffeo2's avatar
cmaffeo2 committed
631
        
632
633
    def _addCrossover(self, hid1, hid2, xo):
        zid1, zid2, isFwd1, isFwd2 = xo
cmaffeo2's avatar
cmaffeo2 committed
634
635
636
637
638
        node1 = self.helices[hid1].nodes[zid1]
        node2 = self.helices[hid2].nodes[zid2]

        ## TODO add polarity
        polarity = 0
cmaffeo2's avatar
cmaffeo2 committed
639
640
        node1.addXover(node2, (isFwd1, isFwd2))
        node2.addXover(node1, (isFwd2, isFwd1))
cmaffeo2's avatar
cmaffeo2 committed
641

642
643
644
645
646
647
648
649
650
651
    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)

652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
    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()


667
668
669
670
    def backmap(self, simplerModel, simplerModelCoords, 
                dsDnaHelixNeighborDist=50, dsDnaAllNeighborDist=30,
                ssDnaHelixNeighborDist=20, ssDnaAllNeighborDist=15):

cmaffeo2's avatar
cmaffeo2 committed
671
        ## Assign each bead to a bead in simplerModel
cmaffeo2's avatar
cmaffeo2 committed
672
673
674
675
676
677
        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

cmaffeo2's avatar
cmaffeo2 committed
678
            zIdxs = np.array( sorted([i for i,b in cgH]) )
cmaffeo2's avatar
cmaffeo2 committed
679
            for i,b in h:
cmaffeo2's avatar
cmaffeo2 committed
680
681
                cgi = np.searchsorted(zIdxs,i,side='left',sorter=None)
                cgi, = [zIdxs[x] if x < len(zIdxs) else zIdxs[-1] for x in (cgi,)]
cmaffeo2's avatar
cmaffeo2 committed
682
                mapToSimplerModel[b.idx] = [cgH.nodes[x] for x in (cgi,)]
cmaffeo2's avatar
cmaffeo2 committed
683
                
cmaffeo2's avatar
cmaffeo2 committed
684
        ## Find new axis and position of each bead using neighborhood
cmaffeo2's avatar
cmaffeo2 committed
685
        beads = [b for h in self for i,b in h[1].nodes.items()]
cmaffeo2's avatar
cmaffeo2 committed
686
687
688

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

693
694
695
696
697
698
            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

699
700
            ids = []
            attempts = 0
701
702
            posOld = []
            while len(ids) <= 3 or not positionsAreLinear(posOld):
703
704
                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)
705
                posOld = np.array( [simplerModel.particles[i][0].initialPosition for i in ids] )
706
707
                allCutoff *= 1.2
                attempts+=1
708
709
710
711

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

cmaffeo2's avatar
cmaffeo2 committed
712
            posNew = np.array( [simplerModelCoords[i] for i in ids] )
713
            trans[b.idx] = minimizeRmsd( posOld, posNew )
cmaffeo2's avatar
cmaffeo2 committed
714
715
716
717

        ## Optionally smooth orientations
            
        ## Apply transformation to each bead of self
cmaffeo2's avatar
cmaffeo2 committed
718
719
720
        for b in beads:
            cgb, = mapToSimplerModel[b.idx]
            cgi = cgb.idx
721
            r0 = simplerModel.particles[cgi][0].initialPosition
cmaffeo2's avatar
cmaffeo2 committed
722
            R,c0,c1 = trans[cgi]
cmaffeo2's avatar
cmaffeo2 committed
723
            b.position = (b.initialPosition - r0).dot(R) + simplerModelCoords[cgi]
cmaffeo2's avatar
cmaffeo2 committed
724
            assert( np.all(np.isreal( b.position )) )
cmaffeo2's avatar
cmaffeo2 committed
725
        
cmaffeo2's avatar
cmaffeo2 committed
726

727
    def _getNeighborhoodIds(self, bead, coords, helixCutoff=50, allCutoff=np.sqrt(35)):
cmaffeo2's avatar
cmaffeo2 committed
728
729
730
731
732
733
734
        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)
cmaffeo2's avatar
cmaffeo2 committed
735
        
cmaffeo2's avatar
cmaffeo2 committed
736
737
        ## 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] )
738
        ret = list( np.where( (dr2Final < helixCutoff**2) * (self._nodeHids == bead.helix.hid) * (dr2Initial < 100**2) )[0] )
cmaffeo2's avatar
cmaffeo2 committed
739
740

        ## Include all within 3.5 nm both before AND after simulation
741
        ret.extend( list( np.where( (dr2Final < allCutoff**2) * (dr2Initial < allCutoff**2) )[0] ) )
cmaffeo2's avatar
cmaffeo2 committed
742
743
        return sorted(list(set(ret)))

744
745
746
747
    # -------------------------- #
    # Methods for querying model #
    # -------------------------- #
    def _getIntrahelicalNodeSeries(self,seriesLen):
cmaffeo2's avatar
cmaffeo2 committed
748
749
        nodeSeries = set() 
        for hid,hlx in self:
750
            for zid,n in hlx:
751
                nodeList,sepList = n.getNodesAbove(seriesLen-1, inclusive = True)
752
                if len(nodeList) == seriesLen:
753
754
                    nodeList = tuple(nodeList)
                    sepList = tuple(sepList)
755
756
757
758
759
760
761
762
763
764
                    nodeSeries.add( tuple((nodeList,sepList)) )
        return nodeSeries

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

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

    def _getCrossoverBonds(self):
cmaffeo2's avatar
cmaffeo2 committed
765
        return { ((n, xo[0]), xo[1])
cmaffeo2's avatar
cmaffeo2 committed
766
                 for hid,hlx in self
767
768
                 for zid,n in hlx for xo in n.xovers if n.idx < xo[0].idx }

769
    def _getSsCrossoverBonds(self):
cmaffeo2's avatar
cmaffeo2 committed
770
        return { ((n, xo[0]), xo[1]) 
cmaffeo2's avatar
cmaffeo2 committed
771
                 for hid,hlx in self
772
773
774
                 for zid,n in hlx for xo in n.ssXovers if n.idx < xo[0].idx }


775
776
    def _getCrossoverAnglesAndDihedrals(self):
        angles,dihedrals = [set(),set()]
777
        contiguousCrossovers = []
cmaffeo2's avatar
cmaffeo2 committed
778

779
        for hid,hlx in self.helices.items():
780
            crossovers = []
781
782
            bpsBetween = 0
            for zid,n in hlx:
783
                ## Search for contiguous crossovers
784
                if n.nodeBelow is None or n.type[0] != "d":
785
                    ## Found ssDNA or a gap; reset search
786
787
788
                    if len(crossovers) > 0:
                        contiguousCrossovers.append(crossovers)
                    crossovers = []
789
790
                    bpsBetween = 0

791
792
793
794
                if n.nodeBelow is not None:
                    bpsBetween += n.nodeBelowSep
                if len(n.xovers) > 0:
                    crossovers.append( (n,bpsBetween) )
cmaffeo2's avatar
cmaffeo2 committed
795

796
797
798
799
800
801
802
803
            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)):
804
                for j in range(i+1,i+2): # Just look at adjacent crossovers
805
                    assert(j == i+1)
806
807
808
809
810
                    nj,bpj = crossovers[j]
                    bpsBetween = bpj-bpi
                    if bpsBetween < 60:
                        for xo1 in ni.xovers:
                            for xo2 in nj.xovers:
811
                                assert( bpsBetween != 0 )
812
813
814
815
816
                                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
817
        return angles, dihedrals
818
819
        

820
    def _removeIntrahelicalConnectionsBeyond(self, cutoff):
821
822
823
824
825
        bonds = self._getIntrahelicalBonds()
        for b in bonds:
            n1,n2 = b[0]
            r2 = np.sum( (n1.position - n2.position)**2 )
            if r2 > cutoff**2:
826
827
828
829
830
831
832
833
                if n1.nodeAbove == n2:
                    assert(n2.nodeBelow == n1)
                    n1.nodeAbove = None
                    n2.nodeBelow = None
                elif n2.nodeAbove == n1:
                    assert(n1.nodeBelow == n2)
                    n1.nodeBelow = None
                    n2.nodeAbove = None
834
835
836
                else:
                    raise

837
    def _removeCrossoversBeyond(self, cutoff):
838
839
840
841
842
843
844
845
846
        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
847

848
849
850
851
852
853
854
855
856
857
        for hid,hlx in self:
            for zid,n1 in hlx:
                newXovers = []
                for xo in n1.ssXovers:
                    n2 = xo[0]
                    r2 = np.sum( (n1.position - n2.position)**2 )
                    if r2 < cutoff**2:
                        newXovers.append(xo)
                n1.ssXovers = newXovers

858
859
860
    def _getBonds(self):
        bonds = self._getIntrahelicalBonds()
        bonds.update( self._getCrossoverBonds() )
861
        bonds.update( self._getSsCrossoverBonds() )
862
863
864
865
        return bonds


    # -------------------------- #
cmaffeo2's avatar
cmaffeo2 committed
866
    # Methods for prinitng model #
867
    # -------------------------- #
cmaffeo2's avatar
cmaffeo2 committed
868
869
870
    def writePdb(self, filename):
        with open(filename,'w') as fh:
            ## Write header
871
            fh.write("CRYST1    1000.    1000.    1000.  90.00  90.00  90.00 P 1           1\n")
cmaffeo2's avatar
cmaffeo2 committed
872
873

            ## Write coordinates
874
            formatString = "ATOM  {:>5d} {:^4s}{:1s}{:3s} {:1s}{:>5s}   {:8.3f}{:8.3f}{:8.3f}{:6.2f}{:6.2f}{:2s}{:2f}\n"
875
876
877
878
879
880
881
882
883
            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
cmaffeo2's avatar
cmaffeo2 committed
884
                x,y,z = [x for x in n.position]
cmaffeo2's avatar
cmaffeo2 committed
885
                
886
                assert(idx < 1e5)
cmaffeo2's avatar
cmaffeo2 committed
887
                resid = "{:<4d}".format(idx)
888

889
                fh.write( formatString.format(
890
                    idx, name[:1], "", resname, chain, resid, x, y, z, occ, beta, "", charge ))
cmaffeo2's avatar
cmaffeo2 committed
891
892
        return
        
cmaffeo2's avatar
cmaffeo2 committed
893
894
895
    def writePsf(self, filename):
        with open(filename,'w') as fh:
            ## Write header
896
            fh.write("PSF NAMD\n\n") # create NAMD formatted psf
cmaffeo2's avatar
cmaffeo2 committed
897
898
899
            
            ## ATOMS section
            idx=1
cmaffeo2's avatar
cmaffeo2 committed
900
            for hid,hlx in self:
901
                for x in hlx:
902
                    idx += 1
cmaffeo2's avatar
cmaffeo2 committed
903

904
905
906
907
908
909
910
            fh.write("{:>8d} !NATOM\n".format(idx-1))

            ## From vmd/plugins/molfile_plugin/src/psfplugin.c
            ## "%d %7s %10s %7s %7s %7s %f %f"
            formatString = "{idx:>8d} {segname:7s} {resid:<10s} {resname:7s}" + \
                           " {name:7s} {type:7s} {charge:f} {mass:f}\n"
            for n,hid,zid in self.particles:
911
                idx = n.idx + 1
912
                data = dict(
913
                    idx     = idx,
914
                    segname = "A",
915
                    resid   = "%d%c%c" % (idx," "," "), # TODO: work with large indeces
916
917
918
919
920
921
922
923
924
925
926
                    name    = n.type[:1],
                    resname = n.type[:3],
                    type    = n.type[:1],
                    charge  = 0,
                    mass    = 100,
                )
                fh.write(formatString.format( **data ))
            fh.write("\n")

            ## Write out bonds
            bonds = self._getBonds()
927
            fh.write("{:>8d} !NBOND\n".format(len(bonds)))
928
929
930
            counter = 0
            for n,seps in bonds:
                fh.write( "{:d} {:d} ".format(n[0].idx+1,n[1].idx+1) )
931
                counter += 1
932
933
934
                if counter == 3:
                    fh.write("\n")
                    counter = 0
cmaffeo2's avatar
cmaffeo2 committed
935
            fh.write("\n")
936

cmaffeo2's avatar
cmaffeo2 committed
937
        return
938

939
    def writeArbdFiles(self, prefix, numSteps=100000000, timestep=100e-6):
940
941
942
943
944
945
946
947
        ## TODO: save and reference directories and prefixes using member data
        d = "potentials"
        self._writeArbdCoordFile( prefix + ".coord.txt" )
        self._writeArbdBondFile(  prefix, directory = d )
        self._writeArbdAngleFile( prefix, directory = d )
        self._writeArbdDihedralFile( prefix, directory = d )
        self._writeArbdExclFile(  prefix + ".excludes.txt" )
        self._writeArbdPotentialFiles( prefix, directory = d )
948
        self._writeArbdConf( prefix, numSteps, timestep )
949
        
950
951
952
    def _writeArbdCoordFile(self, filename):
        with open(filename,'w') as fh:
            for n,hid,zid in self.particles:
cmaffeo2's avatar
cmaffeo2 committed
953
                fh.write("%f %f %f\n" % tuple(x for x in n.position))
cmaffeo2's avatar
cmaffeo2 committed
954
        
955
    def _writeArbdConf(self, prefix, numSteps=100000000, timestep=100e-6 ):
956
        ## TODO: raise exception if _writeArbdPotentialFiles has not been called
957
        filename = "%s.bd" % prefix
958
        with open(filename,'w') as fh:
959
            fh.write("""# seed 1234
960
timestep %f
cmaffeo2's avatar
cmaffeo2 committed
961
steps %d
962
963
964
965
966
967
968
969
970
971
972
numberFluct 0
interparticleForce 1
fullLongRange 0
temperature 291
electricField 0.0

outputPeriod 10000
outputEnergyPeriod 10000
outputFormat dcd

decompPeriod 100000
973
cutoff 40.0
974
pairlistDistance 80
975
""" % (timestep, numSteps))
976
            
cmaffeo2's avatar
cmaffeo2 committed
977
            for x in self.getParticleTypesAndCounts():
978
                fh.write("\nparticle %s\nnum %d\n" % x)
979
980
981
                ## TODO: look up better values in dictionary for particle types
                fh.write("gridFile null.dx\ndiffusion 100\n")

982
            fh.write("\ninputCoordinates %s.coord.txt\n"  % prefix )
983
984
            if os.path.exists("test.0.restart"):
                fh.write("restartCoordinates test.0.restart\n" )
985
986
            fh.write("""\n## Interaction potentials
tabulatedPotential  1
987
## The i@j@file syntax means particle type i will have NB interactions with particle type j using the potential in file
988
""")
989
990
991
992
            for pair,f in zip(self._particleTypePairIter(), self._nbParamFiles):
                i,j,t1,t2 = pair
                fh.write("tabulatedFile %d@%d@%s\n" % (i,j,f))

993
994
995
996
997
998
999
1000

            fh.write("\n")
            for f in self._bondParamFiles:
                fh.write("tabulatedBondFile %s\n" % f)

            fh.write("\n")
            for f in self._angleParamFiles:
                fh.write("tabulatedAngleFile %s\n" % f)
For faster browsing, not all history is shown. View entire blame