This file is indexed.

/usr/share/pyshared/MMTK/ChemicalObjects.py is in python-mmtk 2.7.9-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  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
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 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
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 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
 712
 713
 714
 715
 716
 717
 718
 719
 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
 941
 942
 943
 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
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
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
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
# This module implements classes that represent atoms, molecules, and
# complexes. They are made as copies from blueprints in the database.
#
# Written by Konrad Hinsen
#

"""
Atoms, groups, molecules and similar objects
"""

__docformat__ = 'restructuredtext'

from MMTK import Bonds, Collections, Database, \
                 Units, Utility, Visualization
from Scientific.Geometry import Vector
from Scientific.Geometry import Objects3D
from Scientific import N
import copy

#
# The base class for all chemical objects.
#
class ChemicalObject(Collections.GroupOfAtoms, Visualization.Viewable):

    """
    General chemical object

    This is an abstract base class that implements methods which
    are applicable to any chemical object (atom, molecule, etc.).
    """

    def __init__(self, blueprint, memo):
        if isinstance(blueprint, basestring):
            blueprint = self.blueprintclass(blueprint)
        self.type = blueprint.type
        if hasattr(blueprint, 'name'):
            self.name = blueprint.name
        if memo is None: memo = {}
        memo[id(blueprint)] = self
        for attr in blueprint.instance:
            setattr(self, attr,
                    Database.instantiate(getattr(blueprint, attr), memo))

    is_chemical_object = True
    is_incomplete = False
    is_modified = False

    __safe_for_unpickling__ = True
    __had_initargs__ = True

    def __hash__(self):
        return id(self)

    def __getattr__(self, attr):
        if attr[:1] == '_' or attr[:3] == 'is_':
            raise AttributeError
        else:
            return getattr(self.type, attr)

    def isSubsetModel(self):
        return False

    def addProperties(self, properties):
        if properties:
            for item in properties.items():
                if hasattr(self, item[0]) and item[0] != 'name':
                    raise TypeError('attribute '+item[0]+' already defined')
                setattr(self, item[0], item[1])

    def binaryProperty(self, properties, name, default):
        value = default
        try:
            value = properties[name]
            del properties[name]
        except KeyError:
            pass
        return value

    def topLevelChemicalObject(self):
        """Returns the highest-level chemical object of which
        the current object is a part."""
        if self.parent is None or not isChemicalObject(self.parent):
            return self
        else:
            return self.parent.topLevelChemicalObject()

    def universe(self):
        """
        :returns: the universe to which the object belongs,
                  or None if the object does not belong to any universe
        :rtype: :class:`~MMTK.Universe.Universe`
        """
        if self.parent is None:
            return None
        else:
            return self.parent.universe()

    def bondedUnits(self):
        """
        :returns: the largest subobjects which can contain bonds.
                  There are no bonds between any of the subobjects
                  in the list.
        :rtype: list
        """
        return [self]

    def atomList(self):
        """
        :returns: a list containing all atoms in the object
        :rtype: list
        """
        pass

    def atomIterator(self):
        """
        :returns: an iterator over all atoms in the object
        :rtype: iterator
        """
        pass

    def fullName(self):
        """
        :returns: the full name of the object. The full name consists
                  of the proper name of the object preceded by
                  the full name of its parent separated by a dot.
        :rtype: str
        """
        if self.parent is None or not isChemicalObject(self.parent):
            return self.name
        else:
            return self.parent.fullName() + '.' + self.name

    def degreesOfFreedom(self):
        """
        :returns: the number of degrees of freedom of the object
        :rtype: int
        """
        return Collections.GroupOfAtoms.degreesOfFreedom(self) \
               - self.numberOfDistanceConstraints()

    def distanceConstraintList(self):
        """
        :returns: the distance constraints of the object
        :rtype: list
        """
        return []

    def _distanceConstraintList(self):
        return []

    def traverseBondTree(self, function = None):
        return []

    def numberOfDistanceConstraints(self):
        """
        :returns: the number of distance constraints of the object
        :rtype: int
        """
        return 0

    def setBondConstraints(self, universe=None):
        """
        Sets distance constraints for all bonds.
        """
        pass

    def removeDistanceConstraints(self, universe=None):
        """
        Removes all distance constraints.
        """
        pass

    def setRigidBodyConstraints(self, universe = None):
        """
        Sets distance constraints that make the object fully rigid.
        """
        if universe is None:
            universe = self.universe()
        if universe is None:
            import Universe
            universe = Universe.InfiniteUniverse()
        atoms = self.atomList()
        if len(atoms) > 1:
            self.addDistanceConstraint(atoms[0], atoms[1],
                                       universe.distance(atoms[0], atoms[1]))
        if len(atoms) > 2:
            self.addDistanceConstraint(atoms[0], atoms[2],
                                       universe.distance(atoms[0], atoms[2]))
            self.addDistanceConstraint(atoms[1], atoms[2],
                                       universe.distance(atoms[1], atoms[2]))
        if len(atoms) > 3:
            for a in atoms[3:]:
                self.addDistanceConstraint(atoms[0], a,
                                           universe.distance(atoms[0], a))
                self.addDistanceConstraint(atoms[1], a,
                                           universe.distance(atoms[1], a))
                self.addDistanceConstraint(atoms[2], a,
                                           universe.distance(atoms[2], a))

    def getAtomProperty(self, atom, property):
        """
        Retrieve atom properties from the chemical database.

        Note: the property is first looked up in the database entry
        for the object on which the method is called. If the lookup
        fails, the complete hierarchy from the atom to the top-level
        object is constructed and traversed starting from the top-level
        object until the property is found. This permits database entries
        for higher-level objects to override property definitions in
        its constituents.

        At the atom level, the property is retrieved from an attribute
        with the same name. This means that properties at the atom
        level can be defined both in the chemical database and for
        each atom individually by assignment to the attribute.
        
        :returns: the value of the specified property for the given
                  atom from the chemical database.
        """

    def writeXML(self, file, memo, toplevel=1):
        if self.type is None:
            name = 'm' + `memo['counter']`
            memo['counter'] = memo['counter'] + 1
            memo[id(self)] = name
            atoms = copy.copy(self.atoms)
            bonds = copy.copy(self.bonds)
            for group in self.groups:
                group.writeXML(file, memo, 0)
                for atom in group.atoms:
                    atoms.remove(atom)
                for bond in group.bonds:
                    bonds.remove(bond)
            file.write('<molecule id="%s">\n' % name)
            for group in self.groups:
                file.write('  <molecule ref="%s" title="%s"/>\n'
                           % (memo[id(group.type)], group.name))
            if atoms:
                file.write('  <atomArray>\n')
                for atom in atoms:
                    file.write('    <atom title="%s" elementType="%s"/>\n'
                               % (atom.name, atom.type.symbol))
                file.write('  </atomArray>\n')
            if bonds:
                file.write('  <bondArray>\n')
                for bond in bonds:
                    a1n = self.relativeName(bond.a1)
                    a2n = self.relativeName(bond.a2)
                    file.write('    <bond atomRefs2="%s %s"/>\n' % (a1n, a2n))
                file.write('  </bondArray>\n')
            file.write('</molecule>\n')
        else:
            name = self.name
            self.type.writeXML(file, memo)
            atom_names = self.type.getXMLAtomOrder()
        if toplevel:
            return ['<molecule ref="%s"/>' % name]
        else:
            return None

    def getXMLAtomOrder(self):
        if self.type is None:
            atoms = []
            for group in self.groups:
                atoms.extend(group.getXMLAtomOrder())
            for atom in self.atoms:
                if atom not in atoms:
                    atoms.append(atom)
        else:
            atom_names = self.type.getXMLAtomOrder()
            atoms = []
            for name in atom_names:
                parts = name.split(':')
                object = self
                for attr in parts:
                    object = getattr(object, attr)
                atoms.append(object)
        return atoms

    def relativeName(self, object):
        name = ''
        while object is not None and object != self:
            name = object.name + ':' + name
            object = object.parent
        return name[:-1]

    def relativeName_unused(self, object):
        name = ''
        while object is not None and object != self:
            for attr, value in object.parent.__dict__.items():
                if value is object:
                    name = attr + ':' + name
                    break
            object = object.parent
        return name[:-1]

    def description(self, index_map = None):
        tag = Utility.uniqueAttribute()
        s = self._description(tag, index_map, 1)
        for a in self.atomList():
            delattr(a, tag)
        return s

    def __repr__(self):
        return self.__class__.__name__ + ' ' + self.fullName()
    __str__ = __repr__

    def __copy__(self):
        return copy.deepcopy(self, {id(self.parent): None})

# Type check

def isChemicalObject(object):
    """
    :returns: True if object is a chemical object
    """
    return hasattr(object, 'is_chemical_object')

#
# The second base class for all composite chemical objects.
#
class CompositeChemicalObject(object):

    """
    Chemical object containing subobjects

    This is an abstract base class that implements methods
    which can be used with any composite chemical object,
    i.e. any chemical object that is not an atom.
    """

    def __init__(self, properties):
        if properties.has_key('configuration'):
            conf = properties['configuration']
            self.configurations[conf].applyTo(self)
            del properties['configuration']
        elif hasattr(self, 'configurations') and \
             self.configurations.has_key('default'):
            self.configurations['default'].applyTo(self)
        if properties.has_key('position'):
            self.translateTo(properties['position'])
            del properties['position']
        self.addProperties(properties)

    def atomList(self):
        return self.atoms

    def atomIterator(self):
        return iter(self.atoms)

    def setPosition(self, atom, position):
        if atom.__class__ is Database.AtomReference:
            atom = self.atoms[atom.number]
        atom.setPosition(position)

    def setIndex(self, atom, index):
        if atom.__class__ is Database.AtomReference:
            atom = self.atoms[atom.number]
        atom.setIndex(index)

    def getAtom(self, atom):
        if atom.__class__ is Database.AtomReference:
            atom = self.atoms[atom.number]
        return atom

    def getReference(self, atom):
        if atom.__class__ is Database.AtomReference:
            return atom
        return Database.AtomReference(self.atoms.index(atom))

    def getAtomProperty(self, atom, property, levels = None):
        try:
            return atom.__dict__[property]
        except KeyError:
            try:
                return getattr(self, property)[self.getReference(atom)]
            except (AttributeError, KeyError):
                if levels is None:
                    object = atom
                    levels = []
                    while object != self:
                        levels.append(object)
                        object = object.parent
                if not levels:
                    raise KeyError('Property ' + property +
                                    ' not defined for  ', `atom`)
                return levels[-1].getAtomProperty(atom, property, levels[:-1])

    def deleteUndefinedAtoms(self):
        delete = [a for a in self.atoms if a.position() is None]
        for a in delete:
            a.delete()

    def _deleteAtom(self, atom):
        self.atoms.remove(atom)
        self.is_modified = True
        self.type = None
        if self.parent is not None:
            self.parent._deleteAtom(atom)

    def distanceConstraintList(self):
        dc = self._distanceConstraintList()
        for o in self._subunits():
            dc = dc + o._distanceConstraintList()
        return dc

    def _distanceConstraintList(self):
        try:
            return self.distance_constraints
        except AttributeError:
            return []

    def numberOfDistanceConstraints(self):
        n = len(self._distanceConstraintList()) + \
            sum(len(o._distanceConstraintList()) for o in self._subunits())
        return n

    def setBondConstraints(self, universe=None):
        if universe is None:
            universe = self.universe()
        bond_database = universe.bondLengthDatabase()
        for o in self.bondedUnits():
            o._setBondConstraints(universe, bond_database)

    def _setBondConstraints(self, universe, bond_database):
        self.distance_constraints = []
        for bond in self.bonds:
            d = bond_database.bondLength(bond)
            if d is None:
                d = universe.distance(bond.a1, bond.a2)
            self.addDistanceConstraint(bond.a1, bond.a2, d)

    def addDistanceConstraint(self, atom1, atom2, distance):
        try:
            self.distance_constraints.append((atom1, atom2, distance))
        except AttributeError:
            self.distance_constraints = [(atom1, atom2, distance)]

    def removeDistanceConstraints(self, universe=None):
        try:
            del self.distance_constraints
        except AttributeError:
            pass
        for o in self._subunits():
            o.removeDistanceConstraints()

    def traverseBondTree(self, function = None):
        self.setBondAttributes()
        todo = [self.atoms[0]]
        done = {todo[0]: True}
        bonds = []
        while todo:
            next_todo = []
            for atom in todo:
                bonded = atom.bondedTo()
                for other in bonded:
                    if not done.get(other, False):
                        if function is None:
                            bonds.append((atom, other))
                        else:
                            bonds.append((function(atom), function(other)))
                        next_todo.append(other)
                        done[other] = True
            todo = next_todo
        self.clearBondAttributes()
        return bonds

    def _description(self, tag, index_map, toplevel):
        letter, kwargs = self._descriptionSpec()
        s = [letter, '(', `self.name`, ',[']
        s.extend([o._description(tag, index_map, 0) + ','
                  for o in self._subunits()])
        s.extend([a._description(tag, index_map, 0) + ','
                  for a in self.atoms if not hasattr(a, tag)])
        s.append(']')
        if toplevel:
            s.extend([',', `self._typeName()`])
        if kwargs is not None:
            s.extend([',', kwargs])
        constraints = self._distanceConstraintList()
        if constraints:
            s.append(',dc=[')
            if index_map is None:
                s.extend(['(%d,%d,%f),' % (c[0].index, c[1].index, c[2])
                          for c in constraints])
            else:
                s.extend(['(%d,%d,%f),' % (index_map[c[0].index],
                                           index_map[c[1].index], c[2])
                          for c in constraints])
            s.append(']')
        s.append(')')
        return ''.join(s)

    def _typeName(self):
        return self.type.name

    def _graphics(self, conf, distance_fn, model, module, options):
        glist = []
        for bu in self.bondedUnits():
            for a in bu.atomList():
                glist.extend(a._graphics(conf, distance_fn, model,
                                         module, options))
            if hasattr(bu, 'bonds'):
                for b in bu.bonds:
                    glist.extend(b._graphics(conf, distance_fn, model,
                                             module, options))
        return glist

#
# The classes for atoms, groups, molecules, and complexes.
#
class Atom(ChemicalObject):

    """
    Atom
    """

    def __init__(self, atom_spec, _memo = None, **properties):
        """
        :param atom_spec: a string (not case sensitive) specifying
                          the chemical element
        :type atom_spec: str
        :keyword position: the position of the atom
        :type position: Scientific.Geometry.Vector
        :keyword name: a name given to the atom
        :type name: str
        """
        Utility.uniqueID.registerObject(self)
        ChemicalObject.__init__(self, atom_spec, _memo)
        self._mass = self.type.average_mass
        self.array = None
        self.index = None
        if properties.has_key('position'):
            self.setPosition(properties['position'])
            del properties['position']
        self.addProperties(properties)

    blueprintclass = Database.BlueprintAtom

    def __getstate__(self):
        state = copy.copy(self.__dict__)
        if self.array is not None:
            state['array'] = None
            state['pos'] = Vector(self.array[self.index,:])
        return state

    def atomList(self):
        return [self]

    def atomIterator(self):
        yield self

    def setPosition(self, position):
        """
        Changes the position of the atom.

        :param position: the new position
        :type position: Scientific.Geometry.Vector
        """
        if position is None:
            if self.array is None:
                try: del self.pos
                except AttributeError: pass
            else:
                self.array[self.index,0] = Utility.undefined
                self.array[self.index,1] = Utility.undefined
                self.array[self.index,2] = Utility.undefined
        else:
            if self.array is None:
                self.pos = position
            else:
                self.array[self.index,0] = position[0]
                self.array[self.index,1] = position[1]
                self.array[self.index,2] = position[2]

    translateTo = setPosition

    def position(self, conf = None):
        """
        :returns: the position in configuration conf. If conf is 
                  'None', use the current configuration. If the atom has
                  not been assigned a position, the return value is None.
        :rtype: Scientific.Geometry.Vector
        """
        if conf is None:
            if self.array is None:
                try:
                    return self.pos
                except AttributeError:
                    return None
            else:
                if N.logical_or.reduce(
                    N.greater(self.array[self.index, :],
                              Utility.undefined_limit)):
                    return None
                else:
                    return Vector(self.array[self.index,:])
        else:
            return conf[self]

    centerOfMass = position

    def setMass(self, mass):
        """
        Changes the mass of the atom.

        :param mass: the mass
        :type mass: float
        """
        self._mass = mass
        universe = self.universe()
        if universe is not None:
            universe._changed(True)

    def getAtom(self, atom):
        return self

    def translateBy(self, vector):
        if self.array is None:
            self.pos = self.pos + vector
        else:
            self.array[self.index,0] = self.array[self.index,0] + vector[0]
            self.array[self.index,1] = self.array[self.index,1] + vector[1]
            self.array[self.index,2] = self.array[self.index,2] + vector[2]

    def numberOfPoints(self):
        return 1

    numberOfCartesianCoordinates = numberOfPoints

    def setIndex(self, index):
        if self.index is not None and self.index != index:
            raise ValueError('Wrong atom index')
        self.index = index

    def setArray(self, index):
        self.index = index
        self.array = None

    def getArray(self):
        return self.array

    def unsetArray(self):
        self.pos = self.position()
        self.array = None

    def setBondAttribute(self, atom):
        try:
            self.bonded_to__.append(atom)
        except AttributeError:
            self.bonded_to__ = [atom]

    def clearBondAttribute(self):
        try:
            del self.bonded_to__
        except AttributeError:
            pass

    def bondedTo(self):
        """
        :returns: a list of all atoms to which a chemical bond exists.
        :rtype: list
        """
        try:
            return self.bonded_to__
        except AttributeError:
            if self.parent is None or not isChemicalObject(self.parent):
                return []
            else:
                return self.parent.bondedTo(self)

    def delete(self):
        if self.parent is not None:
            self.parent._deleteAtom(self)           

    def getAtomProperty(self, atom, property, levels = None):
        if self != atom:
            raise ValueError("Wrong atom")
        return getattr(self, property)

    def _description(self, tag, index_map, toplevel):
        setattr(self, tag, None)
        if index_map is None:
            index = self.index
        else:
            index = index_map[self.index]
        if toplevel:
            return 'A(' + `self.name` + ',' + `index` + ',' + \
                   `self.symbol` + ')'
        else:
            return 'A(' + `self.name` + ',' + `index` + ')'

    def _graphics(self, conf, distance_fn, model, module, options):
        #PJC change:
        if model == 'ball_and_stick':
            color = self._atomColor(self, options)
            material = module.DiffuseMaterial(color)
            radius = options.get('ball_radius', 0.03)
            return [module.Sphere(self.position(), radius, material=material)]
        elif model == 'vdw' or model == 'vdw_and_stick':
            color = self._atomColor(self, options)
            material = module.DiffuseMaterial(color)
            try:
                radius = self.vdW_radius
            except:
                radius = options.get('ball_radius', 0.03)
            return [module.Sphere(self.position(), radius, material=material)]
        else:
            return []

        if model != 'ball_and_stick':
            return []
        color = self._atomColor(self, options)
        material = module.DiffuseMaterial(color)
        radius = options.get('ball_radius', 0.03)
        return [module.Sphere(self.position(), radius, material=material)]

    def writeXML(self, file, memo, toplevel=1):
        return ['<atom title="%s" elementType="%s"/>'
                % (self.name, self.type.symbol)]

    def getXMLAtomOrder(self):
        return [self]

class Group(CompositeChemicalObject, ChemicalObject):

    """
    Group of bonded atoms

    Groups can contain atoms and other groups, and link them by chemical
    bonds. They are used to represent functional groups or any other
    part of a molecule that has a well-defined identity.

    Groups cannot be created in application programs, but only in
    database definitions for molecules or through a MoleculeFactory.
    """

    def __init__(self, group_spec, _memo = None, **properties):
        """
        :param group_spec: a string (not case sensitive) that specifies
                           the group name in the chemical database
        :type group_spec: str
        :keyword position: the position of the center of mass of the group
        :type position: Scientific.Geometry.Vector
        :keyword name: a name given to the group
        :type name: str
        """
        if group_spec is not None:
            # group_spec is None when called from MoleculeFactory
            ChemicalObject.__init__(self, group_spec, _memo)
            self.addProperties(properties)

    blueprintclass = Database.BlueprintGroup
    is_incomplete = True

    def bondedTo(self, atom):
        if self.parent is None or not isChemicalObject(self.parent):
            return []
        else:
            return self.parent.bondedTo(atom)

    def setBondAttributes(self):
        pass

    def clearBondAttributes(self):
        pass

    def _subunits(self):
        return self.groups

    def _descriptionSpec(self):
        return "G", None

class Molecule(CompositeChemicalObject, ChemicalObject):

    """Molecule

    Molecules consist of atoms and groups linked by bonds.
    """

    def __init__(self, molecule_spec, _memo = None, **properties):
        """
        :param molecule_spec: a string (not case sensitive) that specifies
                              the molecule name in the chemical database
        :type molecule_spec: str
        :keyword position: the position of the center of mass of the molecule
        :type position: Scientific.Geometry.Vector
        :keyword name: a name given to the molecule
        :type name: str
        :keyword configuration: the name of a configuration listed in the
                                database definition of the molecule, which
                                is used to initialize the atom positions.
                                If no configuration is specified, the
                                configuration named "default" will be used,
                                if it exists. Otherwise the atom positions
                                are undefined.
        :type configuration: str
        """
        if molecule_spec is not None:
            # molecule_spec is None when called from MoleculeFactory
            ChemicalObject.__init__(self, molecule_spec, _memo)
            properties = copy.copy(properties)
            CompositeChemicalObject.__init__(self, properties)
            self.bonds = Bonds.BondList(self.bonds)

    blueprintclass = Database.BlueprintMolecule

    def bondedTo(self, atom):
        return self.bonds.bondedTo(atom)

    def setBondAttributes(self):
        self.bonds.setBondAttributes()

    def clearBondAttributes(self):
        for a in self.atoms:
            a.clearBondAttribute()

    def _subunits(self):
        return self.groups

    def _descriptionSpec(self):
        return "M", None

    def addGroup(self, group, bond_atom_pairs):
        for a1, a2 in bond_atom_pairs:
            o1 = a1.topLevelChemicalObject()
            o2 = a2.topLevelChemicalObject()
            if set([o1, o2]) != set([self, group]):
                raise ValueError("bond %s-%s outside object" %
                                  (str(a1), str(a2)))
        self.groups.append(group)
        self.atoms = self.atoms + group.atoms
        group.parent = self
        self.clearBondAttributes()
        for a1, a2 in bond_atom_pairs:
            self.bonds.append(Bonds.Bond((a1, a2)))
        for b in group.bonds:
            self.bonds.append(b)

    # construct positions of missing hydrogens
    def findHydrogenPositions(self):
        """
        Find reasonable positions for hydrogen atoms that have no
        position assigned.

        This method uses a heuristic approach based on standard geometry
        data. It was developed for proteins and DNA and may not give
        good results for other molecules. It raises an exception
        if presented with a topology it cannot handle.
        """
        self.setBondAttributes()
        try:
            unknown = {}
            for a in self.atoms:
                if a.position() is None:
                    if a.symbol != 'H':
                        raise ValueError('position of ' + a.fullName() + \
                                          ' is undefined')
                    bonded = a.bondedTo()[0]
                    unknown.setdefault(bonded, []).append(a)
            for a, list in unknown.items():
                bonded = a.bondedTo()
                n = len(bonded)
                known = [b for b in bonded if b.position() is not None]
                nb = len(list)
                try:
                    method = self._h_methods[a.symbol][n][nb]
                except KeyError:
                    raise ValueError("Can't handle this yet: " +
                                      a.symbol + ' with ' + `n` + ' bonds (' +
                                      a.fullName() + ').')
                method(self, a, known, list)
        finally:
            self.clearBondAttributes()

    # default C-H bond length and X-C-H angle
    _ch_bond = 1.09*Units.Ang
    _hch_angle = N.arccos(-1./3.)*Units.rad
    _nh_bond = 1.03*Units.Ang
    _hnh_angle = 120.*Units.deg
    _oh_bond = 0.95*Units.Ang
    _coh_angle = 114.9*Units.deg
    _sh_bond = 1.007*Units.Ang
    _csh_angle = 96.5*Units.deg

    def _C4oneH(self, atom, known, unknown):
        r = atom.position()
        n0 = (known[0].position()-r).normal()
        n1 = (known[1].position()-r).normal()
        n2 = (known[2].position()-r).normal()
        n3 = (n0 + n1 + n2).normal()
        unknown[0].setPosition(r-self._ch_bond*n3)

    def _C4twoH(self, atom, known, unknown):
        r = atom.position()
        r1 = known[0].position()
        r2 = known[1].position()
        plane = Objects3D.Plane(r, r1, r2)
        axis = -((r1-r)+(r2-r)).normal()
        plane = plane.rotate(Objects3D.Line(r, axis), 90.*Units.deg)
        cone = Objects3D.Cone(r, axis, 0.5*self._hch_angle)
        sphere = Objects3D.Sphere(r, self._ch_bond)
        circle = sphere.intersectWith(cone)
        points = circle.intersectWith(plane)
        unknown[0].setPosition(points[0])
        unknown[1].setPosition(points[1])

    def _C4threeH(self, atom, known, unknown):
        self._tetrahedralH(atom, known, unknown, self._ch_bond)

    def _C3oneH(self, atom, known, unknown):
        r = atom.position()
        n1 = (known[0].position()-r).normal()
        n2 = (known[1].position()-r).normal()
        n3 = -(n1 + n2).normal()
        unknown[0].setPosition(r+self._ch_bond*n3)

    def _C3twoH(self, atom, known, unknown):
        r = atom.position()
        r1 = known[0].position()
        others = filter(lambda a: a.symbol != 'H', known[0].bondedTo())
        r2 = others[0].position()
        try:
            plane = Objects3D.Plane(r, r1, r2)
        except ZeroDivisionError:
            # We get here if all three points are colinear.
            # Add a small random displacement as a fix.
            from MMTK.Random import randomPointInSphere
            plane = Objects3D.Plane(r, r1, r2 + randomPointInSphere(0.001))
        axis = (r-r1).normal()
        cone = Objects3D.Cone(r, axis, 0.5*self._hch_angle)
        sphere = Objects3D.Sphere(r, self._ch_bond)
        circle = sphere.intersectWith(cone)
        points = circle.intersectWith(plane)
        unknown[0].setPosition(points[0])
        unknown[1].setPosition(points[1])

    def _C2oneH(self, atom, known, unknown):
        r = atom.position()
        r1 = known[0].position()
        x = r + self._ch_bond * (r - r1).normal()
        unknown[0].setPosition(x)

    def _N2oneH(self, atom, known, unknown):
        r = atom.position()
        r1 = known[0].position()
        others = filter(lambda a: a.symbol != 'H', known[0].bondedTo())
        r2 = others[0].position()
        try:
            plane = Objects3D.Plane(r, r1, r2)
        except ZeroDivisionError:
            # We get here when all three points are colinear.
            # Add a small random displacement as a fix.
            from MMTK.Random import randomPointInSphere
            plane = Objects3D.Plane(r, r1, r2 + randomPointInSphere(0.001))
        axis = (r-r1).normal()
        cone = Objects3D.Cone(r, axis, 0.5*self._hch_angle)
        sphere = Objects3D.Sphere(r, self._nh_bond)
        circle = sphere.intersectWith(cone)
        points = circle.intersectWith(plane)
        unknown[0].setPosition(points[0])

    def _N3oneH(self, atom, known, unknown):
        r = atom.position()
        n1 = (known[0].position()-r).normal()
        n2 = (known[1].position()-r).normal()
        n3 = -(n1 + n2).normal()
        unknown[0].setPosition(r+self._nh_bond*n3)

    def _N3twoH(self, atom, known, unknown):
        r = atom.position()
        r1 = known[0].position()
        others = filter(lambda a: a.symbol != 'H', known[0].bondedTo())
        r2 = others[0].position()
        plane = Objects3D.Plane(r, r1, r2)
        axis = (r-r1).normal()
        cone = Objects3D.Cone(r, axis, 0.5*self._hnh_angle)
        sphere = Objects3D.Sphere(r, self._nh_bond)
        circle = sphere.intersectWith(cone)
        points = circle.intersectWith(plane)
        unknown[0].setPosition(points[0])
        unknown[1].setPosition(points[1])

    def _N4threeH(self, atom, known, unknown):
        self._tetrahedralH(atom, known, unknown, self._nh_bond)

    def _N4twoH(self, atom, known, unknown):
        r = atom.position()
        r1 = known[0].position()
        r2 = known[1].position()
        plane = Objects3D.Plane(r, r1, r2)
        axis = -((r1-r)+(r2-r)).normal()
        plane = plane.rotate(Objects3D.Line(r, axis), 90.*Units.deg)
        cone = Objects3D.Cone(r, axis, 0.5*self._hnh_angle)
        sphere = Objects3D.Sphere(r, self._nh_bond)
        circle = sphere.intersectWith(cone)
        points = circle.intersectWith(plane)
        unknown[0].setPosition(points[0])
        unknown[1].setPosition(points[1])

    def _N4oneH(self, atom, known, unknown):
        r = atom.position()
        n0 = (known[0].position()-r).normal()
        n1 = (known[1].position()-r).normal()
        n2 = (known[2].position()-r).normal()
        n3 = (n0 + n1 + n2).normal()
        unknown[0].setPosition(r-self._nh_bond*n3)

    def _O2(self, atom, known, unknown):
        others = known[0].bondedTo()
        for a in others:
            r = a.position()
            if a != atom and r is not None: break
        dihedral = 180.*Units.deg
        self._findPosition(unknown[0], atom.position(), known[0].position(), r,
                           self._oh_bond, self._coh_angle, dihedral)

    def _S2(self, atom, known, unknown):
        c2 = filter(lambda a: a.symbol == 'C', known[0].bondedTo())[0]
        self._findPosition(unknown[0], atom.position(), known[0].position(),
                           c2.position(),
                           self._sh_bond, self._csh_angle,
                           180.*Units.deg)

    def _tetrahedralH(self, atom, known, unknown, bond):
        r = atom.position()
        n = (known[0].position()-r).normal()
        cone = Objects3D.Cone(r, n, N.arccos(-1./3.))
        sphere = Objects3D.Sphere(r, bond)
        circle = sphere.intersectWith(cone)
        others = filter(lambda a: a.symbol != 'H', known[0].bondedTo())
        others.remove(atom)
        other = others[0]
        ref = (Objects3D.Plane(circle.center, circle.normal) \
               .projectionOf(other.position())-circle.center).normal()
        p0 = circle.center + ref*circle.radius
        p0 = Objects3D.rotatePoint(p0,
                                  Objects3D.Line(circle.center, circle.normal),
                                  60.*Units.deg)
        p1 = Objects3D.rotatePoint(p0,
                                  Objects3D.Line(circle.center, circle.normal),
                                  120.*Units.deg)
        p2 = Objects3D.rotatePoint(p1,
                                  Objects3D.Line(circle.center, circle.normal),
                                  120.*Units.deg)
        unknown[0].setPosition(p0)
        unknown[1].setPosition(p1)
        unknown[2].setPosition(p2)

    def _findPosition(self, unknown, a1, a2, a3, bond, angle, dihedral):
        sphere = Objects3D.Sphere(a1, bond)
        cone = Objects3D.Cone(a1, a2-a1, angle)
        plane = Objects3D.Plane(a3, a2, a1)
        plane = plane.rotate(Objects3D.Line(a1, a2-a1), dihedral)
        points = sphere.intersectWith(cone).intersectWith(plane)
        for p in points:
            if (a1-a2).cross(p-a1)*(plane.normal) > 0:
                unknown.setPosition(p)
                break

    _h_methods = {'C': {4: {3: _C4threeH,
                            2: _C4twoH,
                            1: _C4oneH},
                        3: {2: _C3twoH,
                            1: _C3oneH},
                        2: {1: _C2oneH}},
                  'N': {4: {3: _N4threeH,
                            2: _N4twoH,
                            1: _N4oneH},
                        3: {2: _N3twoH,
                            1: _N3oneH},
                        2: {1: _N2oneH}},
                  'O': {2: {1: _O2}},
                  'S': {2: {1: _S2}},
                  }


class ChainMolecule(Molecule):

    """
    ChainMolecule

    ChainMolecules are generated by a MoleculeFactory from
    templates that have a sequence attribute.
    """

    def __len__(self):
        return len(self.sequence)

    def __getitem__(self, item):
        return getattr(self, self.sequence[item])


class Crystal(CompositeChemicalObject, ChemicalObject):

    def __init__(self, blueprint, _memo = None, **properties):
        ChemicalObject.__init__(self, blueprint, _memo)
        properties = copy.copy(properties)
        CompositeChemicalObject.__init__(self, properties)
        self.bonds = Bonds.BondList(self.bonds)

    blueprintclass = Database.BlueprintCrystal

    def _subunits(self):
        return self.groups

    def _descriptionSpec(self):
        return "X", None

class Complex(CompositeChemicalObject, ChemicalObject):

    """
    Complex

    A complex is an assembly of molecules that are not connected by
    chemical bonds.
    """

    def __init__(self, complex_spec, _memo = None, **properties):
        """
        :param complex_spec: a string (not case sensitive) that specifies
                              the complex name in the chemical database
        :type complex_spec: str
        :keyword position: the position of the center of mass of the complex
        :type position: Scientific.Geometry.Vector
        :keyword name: a name given to the complex
        :type name: str
        :keyword configuration: the name of a configuration listed in the
                                database definition of the complex, which
                                is used to initialize the atom positions.
                                If no configuration is specified, the
                                configuration named "default" will be used,
                                if it exists. Otherwise the atom positions
                                are undefined.
        :type configuration: str
        """
        ChemicalObject.__init__(self, complex_spec, _memo)
        properties = copy.copy(properties)
        CompositeChemicalObject.__init__(self, properties)

    blueprintclass = Database.BlueprintComplex

    def recreateAtomList(self):
        self.atoms = []
        for m in self.molecules:
            self.atoms.extend(m.atoms)

    def bondedUnits(self):
        return self.molecules

    def setBondAttributes(self):
        for m in self.molecules:
            m.setBondAttributes()

    def clearBondAttributes(self):
        for m in self.molecules:
            m.clearBondAttributes()

    def _subunits(self):
        return self.molecules

    def _descriptionSpec(self):
        return "C", None

    def writeXML(self, file, memo, toplevel=1):
        if self.type is None:
            name = 'm' + `memo['counter']`
            memo['counter'] = memo['counter'] + 1
            memo[id(self)] = name
            for molecule in self.molecules:
                molecule.writeXML(file, memo, 0)
            file.write('<molecule id="%s">\n' % name)
            for molecule in self.molecules:
                file.write('  <molecule ref="%s"/>\n' % memo[id(molecule)])
            file.write('</molecule>\n')
        else:
            ChemicalObject.writeXML(self, file, memo, toplevel)
        if toplevel:
            return ['<molecule ref="%s"/>' % name]
        else:
            return None

    def getXMLAtomOrder(self):
        if self.type is None:
            atoms = []
            for molecule in self.molecules:
                atoms.extend(molecule.getXMLAtomOrder())
            return atoms
        else:
            return ChemicalObject.getXMLAtomOrder(self)

Database.registerInstanceClass(Atom.blueprintclass, Atom)
Database.registerInstanceClass(Group.blueprintclass, Group)
Database.registerInstanceClass(Molecule.blueprintclass, Molecule)
Database.registerInstanceClass(Crystal.blueprintclass, Crystal)
Database.registerInstanceClass(Complex.blueprintclass, Complex)


class AtomCluster(CompositeChemicalObject, ChemicalObject):

    """
    An agglomeration of atoms

    An atom cluster acts like a molecule without any bonds or atom
    properties. It can be used to represent a group of atoms that
    are known to form a chemical unit but whose chemical properties
    are not sufficiently known to define a molecule.
    """

    def __init__(self, atoms, **properties):
        """
        :param atoms: a list of atoms in the cluster
        :type atoms: list
        :keyword position: the position of the center of mass of the cluster
        :type position: Scientific.Geometry.Vector
        :keyword name: a name given to the cluster
        :type name: str
        """
        self.atoms = list(atoms)
        self.parent = None
        self.name = ''
        self.type = None
        for a in self.atoms:
            if a.parent is not None:
                raise ValueError(repr(a)+' is part of ' + repr(a.parent))
            a.parent = self
            if a.name != '':
                setattr(self, a.name, a)
        properties = copy.copy(properties)
        CompositeChemicalObject.__init__(self, properties)
        self.bonds = Bonds.BondList([])

    def bondedTo(self, atom):
        return []

    def setBondAttributes(self):
        pass

    def clearBondAttributes(self):
        pass

    def _subunits(self):
        return []

    def _description(self, tag, index_map, toplevel):
        s = 'AC(' + `self.name` + ',['
        for a in self.atoms:
            s = s + a._description(tag, index_map, 1) + ','
        s = s + ']'
        constraints = self._distanceConstraintList()
        if constraints:
            s = s + ',dc=['
            if index_map is None:
                for c in constraints:
                    s = s + '(%d,%d,%f),' % (c[0].index, c[1].index, c[2])
            else:
                for c in constraints:
                    s = s + '(%d,%d,%f),' % (index_map[c[0].index],
                                             index_map[c[1].index], c[2])
            s = s + ']'
        return s + ')'