Collections.py 38.6 KB
Newer Older
Jamie Hall's avatar
Jamie Hall committed
1
2
3
4
5
6
7
8
9
10
11
# This module defines collections of chemical objects.
#
# Written by Konrad Hinsen
#

"""
Collections of chemical objects
"""

__docformat__ = 'restructuredtext'

12
13
import numpy

Jamie Hall's avatar
Jamie Hall committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
from MMTK import Utility, Units, ParticleProperties, Visualization
from MMTK.Geometry import superpositionFit
from Scientific.Geometry import Vector, Tensor, Objects3D
from Scientific.Geometry import Transformation
import copy, itertools, types

#
# This class defines groups of atoms. It is used as a base class
# for anything containing atoms, including chemical objects, collections,
# universes etc., but it can't be used directly. All its subclasses
# must define a method atomList() that returns a list of all their atoms.
#
class GroupOfAtoms(object):

    """
    Anything that consists of atoms

    A mix-in class that defines a large set of operations which are
    common to all objects that consist of atoms, i.e. any subset of
    a chemical system. Examples are atoms, molecules, collections,
    or universes.
    """
    
    def numberOfAtoms(self):
        """
        :returns: the number of atoms
        :rtype: int
        """
        return len(self.atomList())

    def numberOfPoints(self):
        """
        :returns: the number of geometrical points that define the
                  object. It is currently equal to the number of atoms,
                  but could be different e.g. for quantum systems, in which
                  each atom is described by a wave function or a path integral.
        :rtype: int
        """
        return sum([a.numberOfPoints() for a in self.atomIterator()])

    numberOfCartesianCoordinates = numberOfPoints

    def numberOfFixedAtoms(self):
        """
        :returns: the number of atoms that are fixed, i.e. that cannot move
        :rtype: int
        """
        n = 0
        for a in self.atomIterator():
            try:
                if a.fixed: n = n + 1
            except AttributeError: pass
        return n

    def degreesOfFreedom(self):
        """
        :returns: the number of mechanical degrees of freedom
        :rtype: int
        """
        return 3*(self.numberOfAtoms()-self.numberOfFixedAtoms())

    def atomCollection(self):
        """
        :returns: a collection containing all atoms in the object
        """
        return Collection(self.atomList())

    def atomsWithDefinedPositions(self, conf = None):
        """
        :param conf: a configuration object, or None for the
                     current configuration
        :type conf: :class:`~MMTK.ParticleProperties.Configuration` or NoneType
        :returns: a collection of all atoms that have a position in the
                  given configuration
        """
        return Collection([a for a in self.atomIterator()
                           if Utility.isDefinedPosition(a.position(conf))])

    def mass(self):
        """
        :returns: the total mass
        :rtype: float
        """
        return sum(a._mass for a in self.atomIterator())

    def centerOfMass(self, conf = None):
        """
        :param conf: a configuration object, or None for the
                     current configuration
        :type conf: :class:`~MMTK.ParticleProperties.Configuration` or NoneType
        :returns: the center of mass in the given configuration
        :rtype: Scientific.Geometry.Vector
        """
        offset = None
        universe = self.universe()
        if universe is not None:
            offset = universe.contiguousObjectOffset([self], conf)
        m = 0.
        mr = Vector(0.,0.,0.)
        if offset is None:
            for a in self.atomIterator():
                m += a._mass
                mr += a._mass * a.position(conf)
        else:
            for a in self.atomIterator():
                m += a._mass
                mr += a._mass * (a.position(conf)+offset[a])
        return mr/m

    position = centerOfMass

    def centerAndMomentOfInertia(self, conf = None):
        """
        :param conf: a configuration object, or None for the
                     current configuration
        :type conf: :class:`~MMTK.ParticleProperties.Configuration` or NoneType
        :returns: the center of mass and the moment of inertia tensor
                  in the given configuration
        """
        from Scientific.Geometry import delta
        offset = None
        universe = self.universe()
        if universe is not None:
            offset = universe.contiguousObjectOffset([self], conf)
        m = 0.
        mr = Vector(0.,0.,0.)
        t = Tensor(3*[3*[0.]])
        for a in self.atomIterator():
            ma = a._mass
            if offset is None:
                r = a.position(conf)
            else:
                r = a.position(conf)+offset[a]
            m += ma
            mr += ma*r
            t += ma*r.dyadicProduct(r)
        cm = mr/m
        t -= m*cm.dyadicProduct(cm)
        t = t.trace()*delta - t
        return cm, t

    def rotationalConstants(self, conf=None):
        """
        :param conf: a configuration object, or None for the
                     current configuration
        :type conf: :class:`~MMTK.ParticleProperties.Configuration` or NoneType
        :returns: a sorted array of rotational constants A, B, C
                  in internal units
        """
        com, i = self.centerAndMomentOfInertia(conf)
        pmi = i.eigenvalues()
165
        return numpy.sort(Units.h / (8.*numpy.pi*numpy.pi*pmi))[::-1]
Jamie Hall's avatar
Jamie Hall committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181

    def boundingBox(self, conf = None):
        """
        :param conf: a configuration object, or None for the
                     current configuration
        :type conf: :class:`~MMTK.ParticleProperties.Configuration` or NoneType
        :returns: two opposite corners of a bounding box around the
                  object. The bounding box is the smallest rectangular
                  bounding box with edges parallel to the coordinate axes.
        :rtype: tuple of two Scientific.Geometry.Vector
        """
        atoms = self.atomList()
        min = atoms[0].position(conf).array
        max = min
        for a in atoms[1:]:
            r = a.position(conf).array
182
183
            min = numpy.minimum(min, r)
            max = numpy.maximum(max, r)
Jamie Hall's avatar
Jamie Hall committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
        return Vector(min), Vector(max)

    def boundingSphere(self, conf = None):
        """
        :param conf: a configuration object, or None for the
                     current configuration
        :type conf: :class:`~MMTK.ParticleProperties.Configuration` or NoneType
        :returns: a sphere that contains all atoms in the object.
                  This is B{not} the minimal bounding sphere, just B{some}
                  bounding sphere.
        :rtype: Scientific.Geometry.Objects3D.Sphere
        """
        atoms = self.atomList()
        center = sum((a.position(conf) for a in atoms),
                     Vector(0., 0., 0.)) / len(atoms)
        r = 0.
        for a in atoms:
            r = max(r, (a.position(conf)-center).length())
        return Objects3D.Sphere(center, r)

    def rmsDifference(self, conf1, conf2 = None):
        """
        :param conf1: a configuration object
        :type conf1: :class:`~MMTK.ParticleProperties.Configuration`
        :param conf2: a configuration object, or None for the
                      current configuration
        :type conf2: :class:`~MMTK.ParticleProperties.Configuration` or NoneType
        :returns: the RMS (root-mean-square) difference between the
                  conformations of the object in two universe configurations,
                  conf1 and conf2
        :rtype: float
        """
        universe = conf1.universe
        m = 0.
        rms = 0.
        for a in self.atomIterator():
            ma = a._mass
            dr = universe.distanceVector(a.position(conf1), a.position(conf2))
            m += ma
            rms += ma*dr*dr
224
        return numpy.sqrt(rms/m)
Jamie Hall's avatar
Jamie Hall committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322

    def findTransformationAsQuaternion(self, conf1, conf2 = None):
        universe = self.universe()
        if universe.is_periodic:
            raise ValueError("superposition in periodic universe "
                             "is not defined")
        if conf1.universe != universe:
            raise ValueError("conformation is for a different universe")
        if conf2 is None:
            conf2 = conf1
            conf1 = universe.configuration()
        else:
            if conf2.universe != universe:
                raise ValueError("conformation is for a different universe")
        weights = universe.masses()
        return superpositionFit([(weights[a], conf1[a], conf2[a])
                                 for a in self.atomIterator()])

    def findTransformation(self, conf1, conf2 = None):
        """
        :param conf1: a configuration object
        :type conf1: :class:`~MMTK.ParticleProperties.Configuration`
        :param conf2: a configuration object, or None for the
                      current configuration
        :type conf2: :class:`~MMTK.ParticleProperties.Configuration` or NoneType
        :returns: the linear transformation that, when applied to
                  the object in configuration conf1, minimizes the
                  RMS distance to the conformation in conf2, and the
                  minimal RMS distance.
                  If conf2 is None, returns the transformation from the
                  current configuration to conf1 and the associated
                  RMS distance.
        """
        q, cm1, cm2, rms = self.findTransformationAsQuaternion(conf1, conf2)
        return Transformation.Translation(cm2) * \
               q.asRotation() * \
               Transformation.Translation(-cm1), \
               rms

    def translateBy(self, vector):
        """
        Translate the object by a displacement vector
        
        :param vector: the displacement vector
        :type vector: Scientific.Geometry.Vector
        """
        for a in self.atomIterator():
            a.translateBy(vector)

    def translateTo(self, position):
        """
        Translate the object such that its center of mass is at position
        :param position: the final position
        :type position: Scientific.Geometry.Vector
        """
        self.translateBy(position-self.centerOfMass())

    def normalizePosition(self):
        """
        Translate the center of mass to the coordinate origin
        """
        self.translateTo(Vector(0., 0., 0.))

    def normalizeConfiguration(self, repr=None):
        """
        Apply a linear transformation such that the center of mass of
        the object is translated to the coordinate origin and its
        principal axes of inertia become parallel to the three
        coordinate axes.

        :param repr: the specific representation for axis alignment:
          - Ir    : x y z <--> b c a
          - IIr   : x y z <--> c a b
          - IIIr  : x y z <--> a b c
          - Il    : x y z <--> c b a
          - IIl   : x y z <--> a c b
          - IIIl  : x y z <--> b a c        
        """
        transformation = self.normalizingTransformation(repr)
        self.applyTransformation(transformation)

    def normalizingTransformation(self, repr=None):
        """
        Calculate a linear transformation that shifts the center of mass
        of the object to the coordinate origin and makes its
        principal axes of inertia parallel to the three coordinate
        axes.

        :param repr: the specific representation for axis alignment:
          Ir    : x y z <--> b c a
          IIr   : x y z <--> c a b
          IIIr  : x y z <--> a b c
          Il    : x y z <--> c b a
          IIl   : x y z <--> a c b
          IIIl  : x y z <--> b a c
        :returns: the normalizing transformation
        :rtype: Scientific.Geometry.Transformation.RigidBodyTransformation
        """
eric pellegrini's avatar
eric pellegrini committed
323
        from numpy.linalg.linalg import det
Jamie Hall's avatar
Jamie Hall committed
324
325
        cm, inertia = self.centerAndMomentOfInertia()
        ev, diag = inertia.diagonalization()
eric pellegrini's avatar
eric pellegrini committed
326
        if det(diag.array) < 0:
Jamie Hall's avatar
Jamie Hall committed
327
328
            diag.array[0] = -diag.array[0]
        if repr != None:
329
            seq = numpy.argsort(ev)
Jamie Hall's avatar
Jamie Hall committed
330
            if repr == 'Ir':
331
                seq = numpy.array([seq[1], seq[2], seq[0]])
Jamie Hall's avatar
Jamie Hall committed
332
            elif repr == 'IIr':
333
                seq = numpy.array([seq[2], seq[0], seq[1]])
Jamie Hall's avatar
Jamie Hall committed
334
            elif repr == 'Il':
335
                seq = seq[2::-1]
Jamie Hall's avatar
Jamie Hall committed
336
            elif repr == 'IIl':
337
                seq[1:3] = numpy.array([seq[2], seq[1]])
Jamie Hall's avatar
Jamie Hall committed
338
            elif repr == 'IIIl':
339
                seq[0:2] = numpy.array([seq[1], seq[0]])
Jamie Hall's avatar
Jamie Hall committed
340
341
            elif repr != 'IIIr':
                print 'unknown representation'
342
            diag.array = numpy.take(diag.array, seq)                
Jamie Hall's avatar
Jamie Hall committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
        return Transformation.Rotation(diag)*Transformation.Translation(-cm)

    def applyTransformation(self, t):
        """
        Apply a transformation to the object

        :param t: the transformation to be applied
        :type t: Scientific.Geometry.Transformation
        """
        for a in self.atomIterator():
            a.setPosition(t(a.position()))

    def displacementUnderTransformation(self, t):
        """
        :param t: the transformation to be applied
        :type t: Scientific.Geometry.Transformation
        :returns: the displacement vectors for the atoms in the object
                  that correspond to the transformation t.
        :rtype: :class:`~MMTK.ParticleProperties.ParticleVector`
        """
        d = ParticleProperties.ParticleVector(self.universe())
        for a in self.atomIterator():
            r = a.position()
            d[a] = t(r)-r
        return d

    def rotateAroundCenter(self, axis_direction, angle):
        """
        Rotate the object around an axis that passes through its center
        of mass.

        :param axis_direction: the direction of the axis of rotation
        :type axis_direction: Scientific.Geometry.Vector
        :param angle: the rotation angle (in radians)
        :type angle: float
        """
        cm = self.centerOfMass()
        t = Transformation.Translation(cm) * \
            Transformation.Rotation(axis_direction, angle) * \
            Transformation.Translation(-cm)
        self.applyTransformation(t)

    def rotateAroundOrigin(self, axis_direction, angle):
        """
        Rotate the object around an axis that passes through the
        coordinate origin.

        :param axis_direction: the direction of the axis of rotation
        :type axis_direction: Scientific.Geometry.Vector
        :param angle: the rotation angle (in radians)
        :type angle: float
        """
        self.applyTransformation(Transformation.Rotation(axis_direction, angle))

    def rotateAroundAxis(self, point1, point2, angle):
        """
        Rotate the object arond an axis specified by two points

        :param point1: the first point
        :type point1: Scientific.Geometry.Vector
        :param point2: the second point
        :type point2: Scientific.Geometry.Vector
        :param angle: the rotation angle (in radians)
        :type angle: float
        """
        tr1 = Transformation.Translation(-point1)
        tr2 = Transformation.Rotation(point2-point1, angle)
        tr3 = tr1.inverse()
        self.applyTransformation(tr3*tr2*tr1)

    def writeToFile(self, filename, configuration = None, format = None):
        """
        Write a representation of the object in a given
        configuration to a file.

        :param filename: the name of the file
        :type filename: str
        :param configuration: a configuration object, or None for the
                              current configuration
        :type configuration: :class:`~MMTK.ParticleProperties.Configuration` or NoneType
        :param format: 'pdb' or 'vrml' (default: guess from filename)
                       A subformat specification can be added, separated
                       by a dot. Subformats of 'vrml' are 'wireframe'
                       (default), 'ball_and_stick', 'highlight' (like
                       'wireframe', but with a small sphere for
                       all atoms that have an attribute 'highlight' with a
                       non-zero value), and 'charge' (wireframe plus small
                       spheres for the atoms whose color indicates the
                       charge on a red-to-green color scale)
        :type format: str
        """
        from MMTK import ConfigIO
        universe = self.universe()
        if universe is not None:
            configuration = universe.contiguousObjectConfiguration(
                               [self], configuration)
        file = ConfigIO.OutputFile(filename, format)
        file.write(self, configuration)
        file.close()

    def view(self, configuration = None, format = 'pdb'):
        """
        Start an external viewer for the object in the given
        configuration.

        :param configuration: the configuration to be visualized
        :type configuration: :class:`~MMTK.ParticleProperties.Configuration`
        :param format: 'pdb' (for running $PDBVIEWER) or 'vrml'
                       (for running $VRMLVIEWER). An optional
                       subformat specification can be added, see
                       :class:`~MMTK.Collections.GroupOfAtoms.writeToFile` for the details.
        """
        universe = self.universe()
        if universe is not None:
            configuration = universe.contiguousObjectConfiguration([self],
                                                                configuration)
        Visualization.viewConfiguration(self, configuration, format)

    def kineticEnergy(self, velocities = None):
        """
        :param velocities: a set of velocities for all atoms, or
                           None for the current velocities
        :type velocities: :class:`~MMTK.ParticleProperties.ParticleVector`
        :returns: the kinetic energy
        :rtype: float
        """
        if velocities is None:
            velocities = self.atomList()[0].universe().velocities()
        energy = 0.
        for a in self.atomIterator():
            v = velocities[a]
            energy = energy + a._mass*(v*v)
        return 0.5*energy

    def temperature(self, velocities = None):
        """
        :param velocities: a set of velocities for all atoms, or
                           None for the current velocities
        :type velocities: :class:`~MMTK.ParticleProperties.ParticleVector`
        :returns: the temperature
        :rtype: float
        """
        energy = self.kineticEnergy(velocities)
        return 2.*energy/(self.degreesOfFreedom()*Units.k_B)

    def momentum(self, velocities = None):
        """
        :param velocities: a set of velocities for all atoms, or
                           None for the current velocities
        :type velocities: :class:`~MMTK.ParticleProperties.ParticleVector`
        :returns: the momentum
        :rtype: Scientific.Geometry.Vector
        """
        if velocities is None:
            velocities = self.atomList()[0].universe().velocities()
        return sum((a._mass*velocities[a] for a in self.atomIterator()),
                   Vector(0., 0., 0.))

    def angularMomentum(self, velocities = None, conf = None):
        """
        :param velocities: a set of velocities for all atoms, or
                           None for the current velocities
        :type velocities: :class:`~MMTK.ParticleProperties.ParticleVector`
        :param conf: a configuration object, or None for the
                     current configuration
        :type conf: :class:`~MMTK.ParticleProperties.Configuration`
        :returns: the angluar momentum
        :rtype: Scientific.Geometry.Vector
        """
        if velocities is None:
            velocities = self.atomList()[0].universe().velocities()
        cm = self.centerOfMass(conf)
        return sum((a._mass*a.position(conf).cross(velocities[a])
                    for a in self.atomIterator()),
                   Vector(0., 0., 0.))

    def angularVelocity(self, velocities = None, conf = None):
        """
        :param velocities: a set of velocities for all atoms, or
                           None for the current velocities
        :type velocities: :class:`~MMTK.ParticleProperties.ParticleVector`
        :param conf: a configuration object, or None for the
                     current configuration
        :type conf: :class:`~MMTK.ParticleProperties.Configuration`
        :returns: the angluar velocity
        :rtype: Scientific.Geometry.Vector
        """
        if velocities is None:
            velocities = self.atomList()[0].universe().velocities()
        cm, inertia = self.centerAndMomentOfInertia(conf)
        l = sum((a._mass*a.position(conf).cross(velocities[a])
                 for a in self.atomIterator()),
                Vector(0., 0., 0.))
        return inertia.inverse()*l
        
    def universe(self):
        """
        :returns: the universe of which the object is part. For an
                  object that is not part of a universe, the result is
                  None
        :rtype: :class:`~MMTK.Universe.Universe`
        """
        atoms = self.atomList()
        if not atoms:
            return None
        universe = atoms[0].universe()
        for a in atoms[1:]:
            if a.universe() is not universe:
                return None
        return universe

    def charge(self):
        """
        :returns: the total charge of the object. This is defined only
                  for objects that are part of a universe with a force
                  field that defines charges.
        :rtype: float
        """
        return self.universe().forcefield().charge(self)

    def dipole(self, reference = None):
        """
        :returns: the total dipole moment of the object. This is defined only
                  for objects that are part of a universe with a force field
                  that defines charges.
        :rtype: Scientific.Geometry.Vector
        """
        return self.universe().forcefield().dipole(self, reference)

    def booleanMask(self):
        """
        :returns: a ParticleScalar object that contains a value of 1
                  for each atom that is in the object and a value of 0 for all
                  other atoms in the universe
        :rtype: :class:`~MMTK.ParticleProperties.ParticleScalar`
        """
        universe = self.universe()
        if universe is None:
            raise ValueError("object not in a universe")
582
        array = numpy.zeros((universe.numberOfAtoms(),), numpy.int)
Jamie Hall's avatar
Jamie Hall committed
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
        mask = ParticleProperties.ParticleScalar(universe, array)
        for a in self.atomIterator():
            mask[a] = 1
        return mask

#
# This class defines a general collection that can contain
# chemical objects and other collections.
#
class Collection(GroupOfAtoms, Visualization.Viewable):

    """
    Collection of chemical objects

    Collections permit the grouping of arbitrary chemical objects
    (atoms, molecules, etc.) into one object for the purpose of analysis
    or manipulation.

    Collections permit length inquiry, item extraction by indexing,
    and iteration, like any Python sequence object. Two collections
    can be added to yield a collection that contains the combined
    elements.
    """

    def __init__(self, *objects):
        """
        :param objects: a chemical object or a sequence of or a generator
                        yielding chemical objects that define the initial
                        content of the collection.
        """
        self.objects = []
        if len(objects) == 1 and isinstance(objects[0], types.GeneratorType):
            for obj in objects[0]:
                self.addObject(obj)
        else:
            self.addObject(objects)

    is_collection = 1

    def addObject(self, object):
        """
        Add objects to the collection.

        :param object: the object(s) to be added. If it is another collection
                       or a list, all of its elements are added
        """
        from MMTK.ChemicalObjects import isChemicalObject
        if isChemicalObject(object):
            self.addChemicalObject(object)
        elif isCollection(object):
            self.addChemicalObjectList(object.objectList())
        elif Utility.isSequenceObject(object):
            if object and isChemicalObject(object[0]):
                self.addChemicalObjectList(list(object))
            else:
                for o in object:
                    self.addObject(o)
        else:
            raise TypeError('Wrong object type in collection')

    def addChemicalObject(self, object):
        self.objects.append(object)

    def addChemicalObjectList(self, list):
        self.objects.extend(list)

    def removeObject(self, object):
        """
        Remove an object or a list or collection of objects from the
        collection. The object(s) to be removed must be elements of the
        collection.

        :param object: the object to be removed, or a list or collection
                       of objects whose elements are to be removed
        :raises ValueError: if the object is not an element of the collection
        """
        from MMTK.ChemicalObjects import isChemicalObject
        if isChemicalObject(object):
            self.removeChemicalObject(object)
        elif isCollection(object) or Utility.isSequenceObject(object):
            for o in object:
                self.removeObject(o)
        else:
            raise ValueError('Object not in this collection')

    def removeChemicalObject(self, object):
        try:
            self.objects.remove(object)
        except ValueError:
            raise ValueError('Object not in this collection')

    def selectShell(self, point, r1, r2=0.):
        """
        Select objects in a spherical shell around a central point.

        :param point: the center of the spherical shell
        :type point: Scientific.Geometry.Vector
        :param r1: inner or outer radius of the shell
        :type r1: float
        :param r2: inner or outer radius of the shell (default: 0.)
        :type r2: float
        :returns: a collection of all elements whose
                  distance from point is between r1 and r2
        :rtype: :class:`~MMTK.Collections.Collection`
        """
        if r1 > r2:
            r1, r2 = r2, r1
        universe = self.universe()
        in_shell = []
        for o in self.objects:
            for a in o.atomIterator():
                r =  universe.distance(a.position(), point)
                if r >= r1 and r <= r2:
                    in_shell.append(o)
                    break
        return Collection(in_shell)

    def selectBox(self, p1, p2):
        """
        Select objects in a rectangular volume

        :param p1: one corner of the rectangular volume
        :type p1: Scientific.Geometry.Vector
        :param p2: the other corner of the rectangular volume
        :type p2: Scientific.Geometry.Vector
        :returns: a collection of all elements that lie
                  within the rectangular volume
        :rtype: :class:`~MMTK.Collections.Collection`
        """
712
713
        x1 = numpy.minimum(p1.array, p2.array)
        x2 = numpy.maximum(p1.array, p2.array)
Jamie Hall's avatar
Jamie Hall committed
714
715
716
        in_box = []
        for o in self.objects:
            r = o.position().array
717
718
719
            if numpy.logical_and.reduce( \
                numpy.logical_and(numpy.less_equal(x1, r),
                              numpy.less(r, x2))):
Jamie Hall's avatar
Jamie Hall committed
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
                in_box.append(o)
        return Collection(in_box)

    def objectList(self, type = None):
        """
        Make a list of all objects in the collection that are instances
        of a specific type or of one of its subtypes.

        :param type: the type that serves as a filter. If None,
                     all objects are returned
        :returns: the objects that match the given type
        :rtype: list
        """
        if type is None:
            return self.objects
        else:
            return [o for o in self.objects if isinstance(o, type)]

    def atomList(self):
        """
        :returns: a list containing all atoms of all objects in the collection
        :rtype: list
        """
        atoms = []
        for o in self.objectList():
            atoms.extend(o.atomList())
        return atoms

    def atomIterator(self):
        return itertools.chain(*(o.atomIterator() for o in self.objects))
    
    def numberOfAtoms(self):
        """
        :returns: the total number of atoms in the objects of the collection
        :rtype: int
        """
        return sum(o.numberOfAtoms() for o in self.objectList())
    
    def universe(self):
        """
        :returns: the universe of which all objects in the collection
                  are part. If no such universe exists, the return value
                  is None
        :rtype: :class:`~MMTK.Universe.Universe`
        """
        if not self.objects:
            return None
        universe = self.objects[0].universe()
        for o in self.objects[1:]:
            if o.universe() is not universe:
                return None
        return universe

    def __len__(self):
        """
        :returns: the number of objects in the collection
        :rtype: int
        """
        return len(self.objects)

    def __getitem__(self, item):
        """
        :param item: an index into the object list
        :type item: int
        :returns: the object with the given index
        """
        return self.objects[item]

    def __iter__(self):
        return self.objects.__iter__()

    def __add__(self, other):
        return Collection(self.objectList(), other.objectList())

    def __str__(self):
        return "Collection of %d objects" % len(self.objects)

    def map(self, function):
        """
        Apply a function to all objects in the collection and
        return the list of the results. If the results are chemical
        objects, a Collection object is returned instead of a list.

        :param function: the function to be applied
        :type function: callable
        :returns: the list or collection of the results
        """
        from MMTK.ChemicalObjects import isChemicalObject
        list = [function(o) for o in self.objectList()]
        if list and isChemicalObject(list[0]):
            return Collection(list)
        else:
            return list

    def bondedUnits(self):
        bu = []
        for o in self.objects:
            bu = bu + o.bondedUnits()
        return bu

    def degreesOfFreedom(self):
        return GroupOfAtoms.degreesOfFreedom(self) \
               - self.numberOfDistanceConstraints()

    def distanceConstraintList(self):
        """
        :returns: the list of distance constraints
        :rtype: list
        """
        dc = []
        for o in self.objects:
            dc.extend(o.distanceConstraintList())
        return dc

    def numberOfDistanceConstraints(self):
        """
        :returns: the number of distance constraints
        """
        return sum(o.numberOfDistanceConstraints() for o in self.objects)

    def setBondConstraints(self, universe=None):
        """
        Set distance constraints for all bonds
        """
        if universe is None:
            universe = self.universe()
        for o in self.objects:
            o.setBondConstraints(universe)

    def removeDistanceConstraints(self, universe=None):
        """
        Remove all distance constraints
        """
        if universe is None:
            universe = self.universe()
        for o in self.objects:
            o.removeDistanceConstraints(universe)

    def _graphics(self, conf, distance_fn, model, module, options):
        gobs = []
        for o in self.objects:
            gobs.extend(o._graphics(conf, distance_fn, model,
                                    module, options))
        return gobs

    def __copy__(self):
        return self.__class__(copy.copy(self.objects))


# type check for collections

def isCollection(object):
    """
    :param object: any Python object
    :returns: True if the object is a :class:`~MMTK.Collections.Collection`
    """
    return hasattr(object, 'is_collection')

#
# This class defines a partitioned collection. Such collections
# divide their objects into cubic boxes according to their positions.
# It is then possible to find potential neighbours much more efficiently.
#
class PartitionedCollection(Collection):

    """
    Collection with cubic partitions

    A PartitionedCollection differs from a plain Collection by
    sorting its elements into small cubic cells. This makes adding
    objects slower, but geometrical operations like 
    selectShell become much faster for a large number of
    objects.
    """

    def __init__(self, partition_size, *objects):
        """
        :param partition_size: the edge length of the cubic cells
        :param objects: a chemical object or a sequence of chemical objects that
                        define the initial content of the collection.
        """
        self.partition_size = 1.*partition_size
        self.undefined = []
        self.partition = {}
        self.addObject(objects)

    def addChemicalObject(self, object):
        p = object.position()
        if p is None:
            self.undefined.append(object)
        else:
            index = self.partitionIndex(p)
            try:
                partition = self.partition[index]
            except KeyError:
                partition = []
                self.partition[index] = partition
            partition.append(object)
        self.all = None

    def addChemicalObjectList(self, list):
        for object in list:
            self.addChemicalObject(object)

    def removeChemicalObject(self, object):
        p = object.position()
        if p is None:
            self.undefined.remove(object)
        else:
            index = self.partitionIndex(p)
            try:
                partition = self.partition[index]
            except KeyError:
                raise ValueError('Object not in this collection')
            try:
                partition.remove(object)
            except ValueError:
                raise ValueError('Object not in this collection')
        self.all = None

    def partitionIndex(self, x):
941
942
943
        return (int(numpy.floor(x[0]/self.partition_size)),
                int(numpy.floor(x[1]/self.partition_size)),
                int(numpy.floor(x[2]/self.partition_size)))
Jamie Hall's avatar
Jamie Hall committed
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982

    def objectList(self):
        return sum(self.partition.values(), [self.undefined])

    def __len__(self):
        return sum(len(p) for p in self.partition.values()) + \
               len(self.undefined)

    def __getitem__(self, item):
        if self.all is None:
            self.all = self.objectList()
        if item >= len(self.all):
            self.all = None
            raise IndexError
        return self.all[item]

    def __copy__(self):
        return self.__class__(self.partition_size,
                              copy.copy(self.objectList()))

    def partitions(self):
        """
        :returns: a list of cubic partitions. Each partition is specified
                  by a tuple containing two vectors (describing the diagonally
                  opposite corners) and the list of objects in the partition.
        :rtype: list
        """
        list = []
        for index, objects in self.partition.items():
            min = Vector(index)*self.partition_size
            max = min + Vector(3*[self.partition_size])
            list.append((min, max, objects))
        return list

    def selectCube(self, point, edge):
        x = int(round(point[0]/self.partition_size))
        y = int(round(point[1]/self.partition_size))
        z = int(round(point[2]/self.partition_size))
        d = (Vector(x, y, z)*self.partition_size-point).length()
983
        n = int(numpy.ceil((edge + d)/(2.*self.partition_size)))
Jamie Hall's avatar
Jamie Hall committed
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
        objects = []
        for nx in range(-n, n):
            for ny in range(-n, n):
                for nz in range(-n, n):
                    try:
                        objects.append(self.partition[(nx+x, ny+y, nz+z)])
                    except KeyError: pass
        return Collection(objects)

    def selectShell(self, point, min, max=0):
        if min > max:
            min, max = max, min
        objects = Collection()
        minsq = min**2
        maxsq = max**2
        for index in self.partition.keys():
1000
            d1 = self.partition_size*numpy.array(index) - point.array
Jamie Hall's avatar
Jamie Hall committed
1001
1002
            d2 = d1 + self.partition_size
            dmin = (d1 > 0.)*d1 - (d2 < 0.)*d2
1003
1004
            dminsq = numpy.add.reduce(dmin**2)
            dmaxsq = numpy.add.reduce(numpy.maximum(d1**2, d2**2))
Jamie Hall's avatar
Jamie Hall committed
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
            if dminsq >= minsq and dmaxsq <= maxsq:
                objects.addObject(self.partition[index])
            elif dmaxsq >= minsq and dminsq <= maxsq:
                o = Collection(self.partition[index]).selectShell(point,
                                                                  min, max)
                objects.addObject(o)
        return objects

    def pairsWithinCutoff(self, cutoff):
        """
        :param cutoff: a cutoff for pair distances
        :returns: a list containing all pairs of objects in the
                  collection whose center-of-mass distance is less than
                  the cutoff
        :rtype: list
        """
        pairs = []
        positions = {}
        for index, objects in self.partition.items():
            pos = map(lambda o: o.position(), objects)
            positions[index] = pos
            for o1, o2 in Utility.pairs(zip(objects, pos)):
                if (o2[1]-o1[1]).length() <= cutoff:
                    pairs.append((o1[0], o2[0]))
1029
1030
1031
        partition_cutoff = int(numpy.floor((cutoff/self.partition_size)**2))
        ones = numpy.array([1,1,1])
        zeros = numpy.array([0,0,0])
Jamie Hall's avatar
Jamie Hall committed
1032
1033
1034
1035
1036
        keys = self.partition.keys()
        for i in range(len(keys)):
            p1 = keys[i]
            for j in range(i+1, len(keys)):
                p2 = keys[j]
1037
                d = numpy.maximum(abs(numpy.array(p2)-numpy.array(p1)) -
Jamie Hall's avatar
Jamie Hall committed
1038
                              ones, zeros)
1039
                if numpy.add.reduce(d*d) <= partition_cutoff:
Jamie Hall's avatar
Jamie Hall committed
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
                    for o1, pos1 in zip(self.partition[p1],
                                        positions[p1]):
                        for o2, pos2 in zip(self.partition[p2],
                                            positions[p2]):
                            if (pos2-pos1).length() <= cutoff:
                                pairs.append((o1, o2))
        return pairs

#
# A special form of partitioned collection that stores the atoms
# of all objects that are added to it.
#
class PartitionedAtomCollection(PartitionedCollection):

    """
    Partitioned collection of atoms

    PartitionedAtomCollection objects behave like PartitionedCollection
    atoms, except that they store only atoms. When a composite chemical
    object is added, its atoms are stored instead.
    """

    def __init__(*args):
        apply(PartitionedCollection.__init__, args)

    def addChemicalObject(self, object):
        for atom in object.atomIterator():
            PartitionedCollection.addChemicalObject(self, atom)

    def removeChemicalObject(self, object):
        for atom in object.atomIterator():
            PartitionedCollection.removeChemicalObject(self, atom)