__init__.py 59 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
3
4
5
6
from pathlib import Path

from .version import get_version
__version__ = get_version() 

7
8
9
10
import numpy as np
from copy import copy, deepcopy
from inspect import ismethod
import os, sys, subprocess
11
import shutil
12

13
14
15
_RESOURCE_DIR = Path(__file__).parent / 'resources'
def get_resource_path(relative_path):
    return _RESOURCE_DIR / relative_path
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

## Abstract classes
class Transformable():
    def __init__(self, position, orientation=None):
        self.position = np.array(position)
        if orientation is not None:
            orientation = np.array(orientation)
        self.orientation = orientation

    def transform(self, R = ((1,0,0),(0,1,0),(0,0,1)),
                  center = (0,0,0), offset = (0,0,0)):

        R,center,offset = [np.array(x) for x in (R,center,offset)]

        self.position = R.dot(self.position-center)+center+offset
                
        if self.orientation is not None:
            ## TODO: what if self.orientation is taken from parent?!
            self.orientation = self.orientation.dot(R)
        ...        

    def collapsedPosition(self):
        # print("collapsedPosition called", type(self), self.name)
        if isinstance(self, Child):
            # print(self.parent, isinstance(self.parent,Transformable))
            if isinstance(self.parent, Transformable):
                return self.applyOrientation(self.position) + self.parent.collapsedPosition()
            
                # if self.parent.orientation is not None:
                #     return self.parent.collapsedOrientation().dot(self.position) + self.parent.collapsedPosition()
        return np.array(self.position) # return a copy
                
    def applyOrientation(self,obj):
        # print("applyOrientation called", self.name, obj)
        if isinstance(self, Child):
            # print( self.orientation, self.orientation is not None, None is not None )
            # if self.orientation is not None:
            #     # print("applyOrientation applying", self, self.name, self.orientation)
            #     obj = self.orientation.dot(obj)
            if isinstance(self.parent, Transformable):
                if self.parent.orientation is not None:
                    obj = self.parent.orientation.dot(obj)
                obj = self.parent.applyOrientation(obj)
        # print("applyOrientation returning", self.name, obj)
        return obj

class Parent():
cmaffeo2's avatar
cmaffeo2 committed
63
    def __init__(self, children=None, remove_duplicate_bonded_terms=False):
64
        self.children = []
cmaffeo2's avatar
cmaffeo2 committed
65
66
67
        if children is not None:
            for x in children:
                self.add(x)
68
69
        
        self.remove_duplicate_bonded_terms = remove_duplicate_bonded_terms
70
71
72
        self.bonds = []
        self.angles = []
        self.dihedrals = []
cmaffeo2's avatar
cmaffeo2 committed
73
        self.impropers = []
74
        self.exclusions = []
75
        self.bond_angles = []
76
        self.product_potentials = []
cmaffeo2's avatar
cmaffeo2 committed
77
78
        self.group_sites = []
        
79
        self.rigid = False
80

81
        ## TODO: self.cacheInvalid = True # What will be in the cache?
82
83
84
85
86
87
88
89
90
91
92

    def add(self,x):
        ## TODO: check the parent-child tree to make sure there are no cycles
        if not isinstance(x,Child):
            raise Exception('Attempted to add an object to a group that does not inherit from the "Child" type')

        if x.parent is not None and x.parent is not self:
            raise Exception("Child {} already belongs to some group".format(x))
        x.parent = self
        self.children.append(x)

93
94
95
96
97
98
99
100
101
102
103
104
105
    def insert(self,idx,x):
        ## TODO: check the parent-child tree to make sure there are no cycles
        if not isinstance(x,Child):
            raise Exception('Attempted to add an object to a group that does not inherit from the "Child" type')

        if x.parent is not None and x.parent is not self:
            raise Exception("Child {} already belongs to some group".format(x))
        x.parent = self
        self.children.insert(idx,x)

    def index(self, x):
        return self.children.index(x)

106
107
108
109
110
111
112
113
    def clear_all(self, keep_children=False):
        if keep_children == False:
            for x in self.children:
                x.parent = None
            self.children = []
        self.bonds = []
        self.angles = []
        self.dihedrals = []
cmaffeo2's avatar
cmaffeo2 committed
114
        self.impropers = []
115
116
        self.exclusions = []

117
118
119
    def remove(self,x):
        if x in self.children:
            self.children.remove(x)
120
121
            if x.parent is self:
                x.parent = None
122
123

    def add_bond(self, i,j, bond, exclude=False):
124
        assert( i is not j )
125
        ## TODO: how to handle duplicating and cloning bonds
126
127
        # beads = [b for b in self]
        # for b in (i,j): assert(b in beads)
128
129
130
        self.bonds.append( (i,j, bond, exclude) )

    def add_angle(self, i,j,k, angle):
131
        assert( len(set((i,j,k))) == 3 )
132
133
        # beads = [b for b in self]
        # for b in (i,j,k): assert(b in beads)
134
135
136
        self.angles.append( (i,j,k, angle) )

    def add_dihedral(self, i,j,k,l, dihedral):
137
138
        assert( len(set((i,j,k,l))) == 4 )

139
140
        # beads = [b for b in self]
        # for b in (i,j,k,l): assert(b in beads)
141
142
        self.dihedrals.append( (i,j,k,l, dihedral) )

cmaffeo2's avatar
cmaffeo2 committed
143
    def add_improper(self, i,j,k,l, dihedral):
144
145
        # beads = [b for b in self]
        # for b in (i,j,k,l): assert(b in beads)
cmaffeo2's avatar
cmaffeo2 committed
146
147
        self.impropers.append( (i,j,k,l, dihedral) )

148
149
    def add_exclusion(self, i,j):
        ## TODO: how to handle duplicating and cloning bonds
150
151
152
        ## TODO: perform following check elsewhere
        # beads = [b for b in self]
        # for b in (i,j): assert(b in beads)
153
154
        self.exclusions.append( (i,j) )

155
156
    def add_bond_angle(self, i,j,k,l, bond_angle, exclude=False):
        assert( len(set((i,j,k,l))) == 4 )
157
158
159
        ## TODO: how to handle duplicating and cloning bonds
        # beads = [b for b in self]
        # for b in (i,j): assert(b in beads)
160
        self.bond_angles.append( (i,j,k,l, bond_angle) )
161

cmaffeo2's avatar
cmaffeo2 committed
162
    def add_product_potential(self, potential_list):
163
        """ potential_list: list of tuples of form (particle_i, particle_j,..., TabulatedPotential) """
cmaffeo2's avatar
cmaffeo2 committed
164
        if len(potential_list) < 2: raise ValueError("Too few potentials")
165
166
167
168
169
170
171
172
173
        for elem in potential_list:
            beads = elem[:-1]
            pot = elem[-1]
            if len(beads) < 2: raise ValueError("Too few particles specified in product_potential")
            if len(beads) > 4: raise ValueError("Too many particles specified in product_potential")

        self.product_potentials.append(potential_list)
        ## TODO: how to handle duplicating and cloning bonds

174
175
    def get_restraints(self):
        ret = []
cmaffeo2's avatar
cmaffeo2 committed
176
        for c in self.children +  self.group_sites:
177
178
179
            ret.extend( c.get_restraints() )
        return ret

180
181
182
183
    def get_bonds(self):
        ret = self.bonds
        for c in self.children:
            if isinstance(c,Parent): ret.extend( c.get_bonds() )
184
185
186
187
188
        if self.remove_duplicate_bonded_terms:
            return list(set(ret))
        else:
            return ret

189
190
191
192
193

    def get_angles(self):
        ret = self.angles
        for c in self.children:
            if isinstance(c,Parent): ret.extend( c.get_angles() )
194
195
196
197
        if self.remove_duplicate_bonded_terms:
            return list(set(ret))
        else:
            return ret
198
199
200
201
202

    def get_dihedrals(self):
        ret = self.dihedrals
        for c in self.children:
            if isinstance(c,Parent): ret.extend( c.get_dihedrals() )
203
204
205
206
        if self.remove_duplicate_bonded_terms:
            return list(set(ret))
        else:
            return ret
207

cmaffeo2's avatar
cmaffeo2 committed
208
209
210
211
    def get_impropers(self):
        ret = self.impropers
        for c in self.children:
            if isinstance(c,Parent): ret.extend( c.get_impropers() )
212
213
214
215
        if self.remove_duplicate_bonded_terms:
            return list(set(ret))
        else:
            return ret
cmaffeo2's avatar
cmaffeo2 committed
216

217
218
219
220
    def get_exclusions(self):
        ret = self.exclusions
        for c in self.children:
            if isinstance(c,Parent): ret.extend( c.get_exclusions() )
221
222
223
224
225
        if self.remove_duplicate_bonded_terms:
            return list(set(ret))
        else:
            return ret

226
227
228
229
230
231
232
233
234
    def get_bond_angles(self):
        ret = self.bond_angles
        for c in self.children:
            if isinstance(c,Parent): ret.extend( c.get_bond_angles() )
        if self.remove_duplicate_bonded_terms:
            return list(set(ret))
        else:
            return ret

235
236
237
238
239
240
241
242
243
    def get_product_potentials(self):
        ret = self.product_potentials
        for c in self.children:
            if isinstance(c,Parent): ret.extend( c.get_product_potentials() )
        if self.remove_duplicate_bonded_terms:
            return list(set(ret))
        else:
            return ret

244
245
    def _get_bond_potentials(self):
        bonds =  [b for i,j,b,ex in self.get_bonds()]
246
247
        bondangles1 = [b[1] for i,j,k,l,b in self.get_bond_angles()]
        return list(set( bonds+bondangles1 ))
248
249
250

    def _get_angle_potentials(self):
        angles =  [b for i,j,k,b in self.get_angles()]
251
252
253
        bondangles1 = [b[0] for i,j,k,l,b in self.get_bond_angles()]
        bondangles2 = [b[2] for i,j,k,l,b in self.get_bond_angles()]
        return list(set( angles+bondangles1+bondangles2 ))
254
255


256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
    ## Removed because prohibitively slow
    # def remove_duplicate_terms(self):
    #     for key in "bonds angles dihedrals impropers exclusions".split():
    #         self.remove_duplicate_item(key)

    # def remove_duplicate_item(self, dict_key, existing=None):
    #     if existing is None: existing = []
    #     ret = [i for i in list(set(self.__dict__[dict_key])) if i not in existing]
    #     self.__dict__[dict_key] = ret
    #     existing.extend(ret)
    #     for c in self.children:
    #         if isinstance(c,Parent): 
    #             ret = ret + c.remove_duplicate_item(dict_key, existing)
    #     return ret
        
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

    def __iter__(self):
        ## TODO: decide if this is the nicest way to do it!
        """Depth-first iteration through tree"""
        for x in self.children:
            if isinstance(x,Parent):
                if isinstance(x,Clone) and not isinstance(x.get_original_recursively(),Parent):
                    yield x
                else:
                    for y in x:
                        yield y
            else:
                yield x    

    def __len__(self):
        l = 0
        for x in self.children:
            if isinstance(x,Parent):
                l += len(x)
            else:
                l += 1
        return l
        
    def __getitem__(self, i):
        return self.children[i]
    
    def __setitem__(self, i, val):
        x = self.children[i]
        x.parent = None
        val.parent = self
        self.children[i] = val
        
class Child():
    def __init__(self, parent=None):
        self.parent = parent
306
307
308
        if parent is not None:
            assert( isinstance(parent, Parent) )
            parent.children.append(self)
309
310
311
312

    def __getattr__(self, name):
        """
        Try to get attribute from the parent
313

314
315
        """
        # if self.parent is not None:
316
        if "parent" not in self.__dict__ or self.__dict__["parent"] is None or name == "children":
317
            raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))
cmaffeo2's avatar
cmaffeo2 committed
318

319
320
321
322
323

        excluded_attributes = ['parent','rigid']
        if name in excluded_attributes:
            raise AttributeError("'{}' object has no attribute '{}' and cannot look it up from the parent".format(type(self).__name__, name))

cmaffeo2's avatar
cmaffeo2 committed
324
325
326
327
328
329
330
331
332
        ## TODO: determine if there is a way to avoid __getattr__ if a method is being looked up  
        try:
            ret = getattr(self.parent,name)
        except:
            raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))
        if ismethod(ret):
            raise AttributeError("'{}' object has no method '{}'".format(type(self).__name__, name))
        return ret 

333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
            
    # def __getstate__(self):
    #     print("Child getstate called", self)
    #     print(self.__dict__)
    #     return (self.__dict__,)

    # def __setstate__(self, state):
    #     self.__dict__, = state

class Clone(Transformable, Parent, Child):
    def __init__(self, original, parent=None,
                 position = None,
                 orientation = None):
        if position is None and original.position is not None:
            position = np.array( original.position )
        if orientation is None and original.orientation is not None:
            orientation = np.array( original.orientation )
        if parent is None:
            parent = original.parent
        self.original = original
        Child.__init__(self, parent)        
        Transformable.__init__(self, position, orientation)        

        ## TODO: keep own bond_list, etc, update when needed original changes

        if "children" in original.__dict__ and len(original.children) > 0:
            self.children = [Clone(c, parent = self) for c in original.children]
        else:
            self.children = []

    def get_original_recursively(self):
        if isinstance(self.original, Clone):
            return self.original.get_original_recursively()
        else:
            return self.original

    def __getattr__(self, name):
        """
        Try to get attribute from the original without descending the tree heirarchy, then look up parent

        TODO: handle PointParticle lookups into ParticleType
        """
        # print("Clone getattr",name)
        if name in self.original.__dict__:
            return self.original.__dict__[name]
        else:
            if "parent" not in self.__dict__ or self.__dict__["parent"] is None:
                raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))
            return getattr(self.parent, name)
        

## Particle classes
class ParticleType():
    """Class that hold common attributes that particles can point to"""

    excludedAttributes = ("idx","type_",
                          "position",
390
                          "children",
391
                          "parent", "excludedAttributes","rigid"
392
393
    )

394
395
    def __init__(self, name, charge=0, parent=None, **kargs):
        """ Parent type is used to fall back on for nonbonded interactions if this type is not specifically referenced """
396

397
398
399
400
401
402
        if parent is not None:
            for k,v in parent.__dict__.items():
                if k not in ParticleType.excludedAttributes:
                    self.__dict__[k] = v

        self.name   = name
403
        self.charge = charge
404
405
        self.parent = parent

406
407
408
409
410
411
        for key in ParticleType.excludedAttributes:
            assert( key not in kargs )

        for key,val in kargs.items():
            self.__dict__[key] = val

412
413
414
415
416
417
418
419
420
    def is_same_type(self, other):
        assert(isinstance(other,ParticleType))
        if self == other:
            return True
        elif self.parent is not None and self.parent == other:
            return True
        else:
            return False

421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
    def __getattr__(self, name):
        """
        Try to get attribute from the parent

        """
        if "parent" not in self.__dict__ or self.__dict__["parent"] is None or name == "children":
            raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))

        excluded_attributes = ParticleType.excludedAttributes
        if name in excluded_attributes:
            raise AttributeError("'{}' object has no attribute '{}' and cannot look it up from the parent".format(type(self).__name__, name))

        ## TODO: determine if there is a way to avoid __getattr__ if a method is being looked up
        try:
            ret = getattr(self.parent,name)
        except:
            raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))
        if ismethod(ret):
            raise AttributeError("'{}' object has no method '{}'".format(type(self).__name__, name))
        return ret 

        
443
444
445
    def __hash_key(self):
        l = [self.name,self.charge]
        for keyval in sorted(self.__dict__.items()):
446
            if isinstance(keyval[1], list): keyval = (keyval[0],tuple(keyval[1]))
447
448
449
450
451
452
453
454
455
            l.extend(keyval)
        return tuple(l)

    def __hash__(self):
        return hash(self.__hash_key())
    
    def _equal_check(a,b):
        if a.name == b.name:
            if a.__hash_key() != b.__hash_key():
456
                raise Exception("Two different ParticleTypes have same 'name' attribute")
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472

    def __eq__(a,b):
        a._equal_check(b)
        return a.name == b.name
    def __lt__(a,b):
        a._equal_check(b)
        return a.name < b.name
    def __le__(a,b):
        a._equal_check(b)
        return a.name <= b.name
    def __gt__(a,b):
        a._equal_check(b)
        return a.name > b.name
    def __ge__(a,b):
        a._equal_check(b)
        return a.name >= b.name
473
474
475
476

    def __repr__(self):
        return '<{} {}{}>'.format( type(self), self.name, '[{}]'.format(self.parent) if self.parent is not None else '' )

477
478

class PointParticle(Transformable, Child):
479
    def __init__(self, type_, position, name="A", **kwargs):
480
481
482
483
        parent = None
        if 'parent' in kwargs:
            parent = kwargs['parent']
        Child.__init__(self, parent=parent)
484
485
486
487
488
489
        Transformable.__init__(self,position)

        self.type_    = type_                
        self.idx     = None
        self.name = name
        self.counter = 0
490
        self.restraints = []
491
492
493
494

        for key,val in kwargs.items():
            self.__dict__[key] = val
        
495
496
497
498
499
500
501
    def add_restraint(self, restraint):
        ## TODO: how to handle duplicating and cloning bonds
        self.restraints.append( restraint )

    def get_restraints(self):
        return [(self,r) for r in self.restraints]

502
503
504
    def duplicate(self):
        new = deepcopy(self)
        return new
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521

    def __getattr__(self, name):
        """
        First try to get attribute from the parent, then type_
        
        Note that this data structure seems to be fragile, can result in stack overflow
        
        """
        # return Child.__getattr__(self,name)
        try:
            return Child.__getattr__(self,name)
        except Exception as e:
            if 'type_' in self.__dict__:
                return getattr(self.type_, name)
            else:
                raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))

cmaffeo2's avatar
cmaffeo2 committed
522
523
524
525
526
527
    def _get_psfpdb_dictionary(self):
        p = self
        try:
            segname = p.segname
        except:
            segname = "A"
528
529
530
531
        try:
            chain = p.chain
        except:
            chain = "A"
cmaffeo2's avatar
cmaffeo2 committed
532
533
534
535
536
537
538
539
        try:
            resname = p.resname
        except:
            resname = p.name[:3]
        try:
            resid = p.resid
        except:
            resid = p.idx+1
540
541
542
543
        try:
            mass = p.mass
        except:
            mass = 1
cmaffeo2's avatar
cmaffeo2 committed
544
545
546
547
548
549
550
551
552
553
554
555
556

        try:
            occ = p.occupancy
        except:
            occ = 0
        try:
            beta = p.beta
        except:
            beta = 0

        data = dict(segname = segname,
                    resname = resname,
                    name = str(p.name)[:4],
557
                    chain = chain[0],
cmaffeo2's avatar
cmaffeo2 committed
558
559
                    resid = int(resid),
                    idx = p.idx+1,
560
                    type = p.type_.name[:7],
cmaffeo2's avatar
cmaffeo2 committed
561
                    charge = p.charge,
562
                    mass = mass,
cmaffeo2's avatar
cmaffeo2 committed
563
564
565
566
567
                    occupancy = occ,
                    beta = beta
                )
        return data

568
569

class Group(Transformable, Parent, Child):
cmaffeo2's avatar
cmaffeo2 committed
570

cmaffeo2's avatar
cmaffeo2 committed
571
    def __init__(self, name=None, children = None, parent=None, 
572
573
                 position = np.array((0,0,0)),
                 orientation = np.array(((1,0,0),(0,1,0),(0,0,1))),
574
                 remove_duplicate_bonded_terms = False,
cmaffeo2's avatar
cmaffeo2 committed
575
576
                 **kwargs):

577
578
        Transformable.__init__(self, position, orientation)
        Child.__init__(self, parent) # Initialize Child first
579
        Parent.__init__(self, children, remove_duplicate_bonded_terms)
580
581
582
        self.name = name
        self.isClone = False

cmaffeo2's avatar
cmaffeo2 committed
583
584
585
586
        for key,val in kwargs.items():
            self.__dict__[key] = val


587
588
589
590
591
592
593
594
595
596
597
598
599
    def clone(self):
        return Clone(self)
        g = copy(self)
        g.isClone = True        # TODO: use?
        g.children = [copy(c) for c in g.children]
        for c in g.children:
            c.parent = g
        return g
        g = Group(position = self.position,
                  orientation = self.orientation)
        g.children = self.children # lists point to the same object

    def duplicate(self):
cmaffeo2's avatar
cmaffeo2 committed
600
601
602
603
        new = deepcopy(self)
        for c in new.children:
            c.parent = new
        return new
604
605
606
607
        # Group(position = self.position,
        #       orientation = self.orientation)
        # g.children = deepcopy self.children.deepcopy() # lists are the same object

608
    ## TODO override deepcopy so parent can be excluded from copying?
609
610
611
612
613
614
615
616
617
618
        
    # def __getstate__(self):
    #     return (self.children, self.parent, self.position, self.orientation)

    # def __setstate__(self, state):
    #     self.children, self.parent, self.position, self.orientation = state

        
class PdbModel(Transformable, Parent):

cmaffeo2's avatar
cmaffeo2 committed
619
    def __init__(self, children=None, dimensions=None, remove_duplicate_bonded_terms=False):
620
        Transformable.__init__(self,(0,0,0))
621
        Parent.__init__(self, children, remove_duplicate_bonded_terms)
622
623
624
625
626
627
628
        self.dimensions = dimensions
        self.particles = [p for p in self]
        self.cacheInvalid = True

    def _updateParticleOrder(self):
        pass

629
    def writePdb(self, filename, beta_from_fixed=False):
630
631
632
633
        if self.cacheInvalid:
            self._updateParticleOrder()
        with open(filename,'w') as fh:
            ## Write header
634
            fh.write("CRYST1{:>9.3f}{:>9.3f}{:>9.3f}  90.00  90.00  90.00 P 1           1\n".format( *self.dimensions ))
635
636

            ## Write coordinates
cmaffeo2's avatar
cmaffeo2 committed
637
            formatString = "ATOM {idx:>6.6s} {name:^4.4s} {resname:3.3s} {chain:1.1s}{resid:>5.5s}   {x:8.8s}{y:8.8s}{z:8.8s}{occupancy:6.2f}{beta:6.2f}  {charge:2d}{segname:>6s}\n"
638
639
            for p in self.particles:
                ## http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#ATOM
cmaffeo2's avatar
cmaffeo2 committed
640
641
642
                data = p._get_psfpdb_dictionary()
                idx = data['idx']

643
                if np.log10(idx) >= 5:
644
                    idx = " *****"
645
646
                else:
                    idx = "{:>6d}".format(idx)
cmaffeo2's avatar
cmaffeo2 committed
647
                data['idx'] = idx
648

649
650
651
                if beta_from_fixed:
                    data['beta'] = 1 if 'fixed' in p.__dict__ else 0

652
                pos = p.collapsedPosition()
653
                dig = [max(int(np.log10(np.abs(x)+1e-6)//1),0)+1 for x in pos]
654
655
656
657
                for d in dig: assert( d <= 7 )
                # assert( np.all(dig <= 7) )
                fs = ["{: %d.%df}" % (8,7-d) for d in dig]
                x,y,z = [f.format(x) for f,x in zip(fs,pos)] 
cmaffeo2's avatar
cmaffeo2 committed
658
659
660
661
662
663
664
                data['x'] = x
                data['y'] = y
                data['z'] = z
                assert(data['resid'] < 1e5)
                data['charge'] = int(data['charge'])
                data['resid'] = "{:<4d}".format(data['resid'])
                fh.write( formatString.format(**data) )
665

666
        return
cmaffeo2's avatar
cmaffeo2 committed
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697

    def write_pqr(self, filename):
        if self.cacheInvalid:
            self._updateParticleOrder()
        with open(filename,'w') as fh:
            ## Write header
            fh.write("CRYST1{:>9.3f}{:>9.3f}{:>9.3f}  90.00  90.00  90.00 P 1           1\n".format( *self.dimensions ))

            ## Write coordinates
            formatString = "ATOM {idx:>6.6s} {name:^4.4s} {resname:3.3s} {chain:1.1s} {resid:>5.5s}   {x:.6f} {y:.6f} {z:.6f} {charge} {radius}\n"
            for p in self.particles:
                data = p._get_psfpdb_dictionary()

                idx = data['idx']
                if np.log10(idx) >= 5:
                    idx = " *****"
                else:
                    idx = "{:>6d}".format(idx)
                data['idx'] = idx

                x,y,z = p.collapsedPosition()
                data['x'] = x
                data['y'] = y
                data['z'] = z
                assert(data['resid'] < 1e5)
                data['resid'] = "{:<4d}".format(data['resid'])
                if 'radius' not in data:
                    data['radius'] = 2 * (data['mass']/16)**0.333333
                fh.write( formatString.format(**data) )
        return

698
699
700
701
702
703
    def writePsf(self, filename):
        if self.cacheUpToDate == False:
            self._updateParticleOrder()
        with open(filename,'w') as fh:
            ## Write header
            fh.write("PSF NAMD\n\n") # create NAMD formatted psf
cmaffeo2's avatar
cmaffeo2 committed
704
            fh.write("{:>8d} !NTITLE\n\n".format(0))
705
706
707
708
709
710
            
            ## ATOMS section
            fh.write("{:>8d} !NATOM\n".format(len(self.particles)))

            ## From vmd/plugins/molfile_plugin/src/psfplugin.c
            ## "%d %7s %10s %7s %7s %7s %f %f"
cmaffeo2's avatar
cmaffeo2 committed
711
712
            formatString = "{idx:>8d} {segname:7.7s} {resid:<10.10s} {resname:7.7s}" + \
                           " {name:7.7s} {type:7.7s} {charge:f} {mass:f}\n"
713
            for p in self.particles:
cmaffeo2's avatar
cmaffeo2 committed
714
715
716
                data = p._get_psfpdb_dictionary()
                data['resid'] = "%d%c%c" % (data['resid']," "," ") # TODO: work with large indices
                fh.write( formatString.format(**data) )
717
718
719
720
721
722
723
            fh.write("\n")

            ## Write out bonds
            bonds = self.get_bonds()
            fh.write("{:>8d} !NBOND\n".format(len(bonds)))
            counter = 0
            for p1,p2,b,ex in bonds:
724
                fh.write( "{:>8d}{:>8d}".format(p1.idx+1,p2.idx+1) )
725
                counter += 1
726
                if counter == 4:
727
728
                    fh.write("\n")
                    counter = 0
cmaffeo2's avatar
cmaffeo2 committed
729
730
                else:
                    fh.write(" ")
731
            fh.write("\n" if counter == 0 else "\n\n")
732

cmaffeo2's avatar
cmaffeo2 committed
733
734
735
736
737
            ## Write out angles
            angles = self.get_angles()
            fh.write("{:>8d} !NTHETA\n".format(len(angles)))
            counter = 0
            for p1,p2,p3,a in angles:
738
                fh.write( "{:>8d}{:>8d}{:>8d}".format(p1.idx+1,p2.idx+1,p3.idx+1) )
cmaffeo2's avatar
cmaffeo2 committed
739
                counter += 1
740
                if counter == 3:
cmaffeo2's avatar
cmaffeo2 committed
741
742
                    fh.write("\n")
                    counter = 0
cmaffeo2's avatar
cmaffeo2 committed
743
744
                else:
                    fh.write(" ")
745
            fh.write("\n" if counter == 0 else "\n\n")
cmaffeo2's avatar
cmaffeo2 committed
746
747
748
749
750
751

            ## Write out dihedrals
            dihedrals = self.get_dihedrals()
            fh.write("{:>8d} !NPHI\n".format(len(dihedrals)))
            counter = 0
            for p1,p2,p3,p4,a in dihedrals:
752
                fh.write( "{:>8d}{:>8d}{:>8d}{:>8d}".format(p1.idx+1,p2.idx+1,p3.idx+1,p4.idx+1) )
cmaffeo2's avatar
cmaffeo2 committed
753
754
755
756
                counter += 1
                if counter == 2:
                    fh.write("\n")
                    counter = 0
cmaffeo2's avatar
cmaffeo2 committed
757
                else:
758
759
                    fh.write(" ") 
            fh.write("\n" if counter == 0 else "\n\n")
cmaffeo2's avatar
cmaffeo2 committed
760
761
762
763
764
765

            ## Write out impropers
            impropers = self.get_impropers()
            fh.write("{:>8d} !NIMPHI\n".format(len(impropers)))
            counter = 0
            for p1,p2,p3,p4,a in impropers:
766
                fh.write( "{:>8d}{:>8d}{:>8d}{:>8d}".format(p1.idx+1,p2.idx+1,p3.idx+1,p4.idx+1) )
cmaffeo2's avatar
cmaffeo2 committed
767
768
769
770
                counter += 1
                if counter == 2:
                    fh.write("\n")
                    counter = 0
cmaffeo2's avatar
cmaffeo2 committed
771
772
                else:
                    fh.write(" ")
773
774
775
776
777
778
779
780
781
782
783
            fh.write("\n" if counter == 0 else "\n\n")

            fh.write("\n{:>8d} !NDON: donors\n\n\n".format(0))
            fh.write("\n{:>8d} !NACC: acceptors\n\n\n".format(0))
            fh.write("\n       0 !NNB\n\n")
            natoms = len(self.particles)
            for i in range(natoms//8):
                fh.write("      0       0       0       0       0       0       0       0\n")
            for i in range(natoms-8*(natoms//8)):
                fh.write("      0")
            fh.write("\n\n       1       0 !NGRP\n\n")
784
785
786


class ArbdModel(PdbModel):
cmaffeo2's avatar
cmaffeo2 committed
787
788
789
790
791
792
793
794

    class _GroupSite():
        """ Class to represent a collection of particles that can be used by bond potentials """
        def __init__(self, particles, weights=None):
            if weights is not None:
                raise NotImplementedError
            self.particles = particles
            self.idx = None
cmaffeo2's avatar
cmaffeo2 committed
795
796
            self.restraints = []
            
cmaffeo2's avatar
cmaffeo2 committed
797
798
799
800
801
802
803
        def get_center(self):
            c = np.array((0,0,0))
            for p in self.particles:
                c = c + p.collapsedPosition()
            c = c / len(self.particles)
            return c

cmaffeo2's avatar
cmaffeo2 committed
804
805
806
807
808
809
        def add_restraint(self, restraint):
            self.restraints.append( restraint )
        def get_restraints(self):
            return [(self,r) for r in self.restraints]


810
811
812
    def __init__(self, children, origin=None, dimensions=(1000,1000,1000), temperature=291, timestep=50e-6,
                 particle_integrator = 'Brown',
                 cutoff=50, decomp_period=1000, pairlist_distance=None, nonbonded_resolution=0.1,
813
                 remove_duplicate_bonded_terms=True, extra_bd_file_lines=""):
814

815
        PdbModel.__init__(self, children, dimensions, remove_duplicate_bonded_terms)
816
        self.origin = origin
817
818
819
820
821
        self.temperature = temperature

        self.timestep = timestep
        self.cutoff  =  cutoff

822
823
        self.particle_integrator = particle_integrator
        
824
825
        if pairlist_distance == None:
            pairlist_distance = cutoff+30
826
        
827
828
        self.decomp_period = decomp_period
        self.pairlist_distance = pairlist_distance
829

830
831
        self.extra_bd_file_lines = extra_bd_file_lines

832
833
834
835
836
837
838
839
840
841
842
843
        self.numParticles = 0
        self.particles = []
        self.type_counts = None

        self.nbSchemes = []
        self._nbParamFiles = [] # This could be made more robust
        self.nbResolution = 0.1

        self._written_bond_files = dict()        

        self.cacheUpToDate = False

cmaffeo2's avatar
cmaffeo2 committed
844
845
846
847
848
849
850
        self.group_sites = []

    def add_group_site(self, particles, weights=None):
        g = ArbdModel._GroupSite(particles, weights)
        self.group_sites.append(g)
        return g

851
852
853
854
855
856
857
    def clear_all(self, keep_children=False):
        Parent.clear_all(self, keep_children=keep_children)
        self.particles = []
        self.numParticles = 0
        self.type_counts = None
        self._nbParamFiles = []
        self._written_bond_files = dict()
cmaffeo2's avatar
cmaffeo2 committed
858
        self.group_sites = []
859
860
861
862
863
864
865

    def _getNbScheme(self, typeA, typeB):
        scheme = None
        for s,A,B in self.nbSchemes:
            if A is None or B is None:
                if A is None and B is None:
                    return s
866
                elif A is None and typeB.is_same_type(B):
867
                    return s
868
                elif B is None and typeA.is_same_type(A):
869
                    return s
870
            elif typeA.is_same_type(A) and typeB.is_same_type(B):
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
                return s
        raise Exception("No nonbonded scheme found for %s and %s" % (typeA.name, typeB.name))

    def _countParticleTypes(self):
        ## TODO: check for modifications to particle that require
        ## automatic generation of new particle type
        type_counts = dict()
        for p in self:
            t = p.type_
            if t in type_counts:
                type_counts[t] += 1
            else:
                type_counts[t] = 1
        self.type_counts = type_counts

    def _updateParticleOrder(self):
        ## Create ordered list
888
889
        self.particles = [p for p in self]
        # self.particles = sorted(particles, key=lambda p: (p.type_, p.idx))
890
891
        
        ## Update particle indices
cmaffeo2's avatar
cmaffeo2 committed
892
        for i,p in enumerate(self.particles):
893
            p.idx = i
cmaffeo2's avatar
cmaffeo2 committed
894
895
896
897

        ## TODO recurse through childrens' group_sites
        for i,g in enumerate(self.group_sites):
            g.idx = len(self.particles)+i
898
899
900
901
            
        # self.initialCoords = np.array([p.initialPosition for p in self.particles])

    def useNonbondedScheme(self, nbScheme, typeA=None, typeB=None):
902
903
904
905
        self.add_nonbonded_scheme(nbScheme, typeA, typeB)

    def add_nonbonded_scheme(self, nonbonded_scheme, typeA=None, typeB=None):
        self.nbSchemes.append( (nonbonded_scheme, typeA, typeB) )
906
        if typeA != typeB:
907
            self.nbSchemes.append( (nonbonded_scheme, typeB, typeA) )
908

cmaffeo2's avatar
cmaffeo2 committed
909
    def simulate(self, output_name, output_directory='output', num_steps=100000000, timestep=None, gpu=0, output_period=1e4, arbd=None, directory='.', restart_file=None, replicas=1, write_pqr=False, log_file=None, dry_run = False):
910
        assert(type(gpu) is int)
911
        num_steps = int(num_steps)
912

913
914
915
916
917
        d_orig = os.getcwd()
        try:
            if not os.path.exists(directory):
                os.makedirs(directory)
            os.chdir(directory)
New Tbgl User's avatar
New Tbgl User committed
918

919
920
            if timestep is not None:
                self.timestep = timestep
921

922
923
924
925
            if self.cacheUpToDate == False: # TODO: remove cache?
                self._countParticleTypes()
                self._updateParticleOrder()

926
            if output_directory == '': output_directory='.'
927

928
929
930
931
932
933
934
935
936
937
938
939
            if dry_run:
                if arbd is None: arbd='arbd'
            else:
                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 arbd is None: raise Exception("ARBD was not found")
940

941
942
943
944
945
946
                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")
947
948


949
950
951
952
            if not os.path.exists(output_directory):
                os.makedirs(output_directory)
            elif not os.path.isdir(output_directory):
                raise Exception("output_directory '%s' is not a directory!" % output_directory)
953
954


955
            self.writePdb( output_name + ".pdb" )
cmaffeo2's avatar
cmaffeo2 committed
956
            if write_pqr: self.write_pqr( output_name + ".pqr" )
957
            self.writePsf( output_name + ".psf" )
958
            self.writeArbdFiles( output_name, numSteps=num_steps, outputPeriod=output_period, restart_file=restart_file )
959
            # os.sync()
960
961

            ## http://stackoverflow.com/questions/18421757/live-output-from-subprocess-command
cmaffeo2's avatar
cmaffeo2 committed
962
963
964
965
966

            cmd = [arbd, '-g', "%d" % gpu]
            if replicas > 1:
                cmd = cmd + ['-r',replicas]
            cmd = cmd + ["%s.bd" % output_name, "%s/%s" % (output_directory, output_name)]
967
968
            cmd = tuple(str(x) for x in cmd)

969
970
971
972
            if dry_run:
                print("Run with: %s" % " ".join(cmd))
            else:
                print("Running ARBD with: %s" % " ".join(cmd))
973
974
975
976
                if log_file is None or (hasattr(log_file,'write') and callable(log_file.write)):
                    fd = sys.stdout if log_file is None else log_file
                    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
                    for line in process.stdout:
977
978
979
980
                        try:
                            fd.write(line)
                        except:
                            print("WARNING: could not encode line; your locale might not be set correctly")
981
982
983
984
985
                        fd.flush()
                else:
                    with open(log_file,'w') as fd:
                        process = subprocess.Popen(cmd, stdout=log_file, universal_newlines=True)
                        process.communicate()
986
987
988
989
990

        except:
            raise
        finally:
            os.chdir(d_orig)
991
992
993
994
995
996


    # -------------------------- #
    # Methods for printing model #
    # -------------------------- #

997
    def writeArbdFiles(self, prefix, numSteps=100000000, outputPeriod=10000, restart_file=None):
998
        ## TODO: save and reference directories and prefixes using member data
999
        d = self.potential_directory = "potentials"
1000
        if not os.path.exists(d):