Commit 71d91890 authored by peastman's avatar peastman
Browse files

Merge pull request #404 from rmcgibbo/imutable-elements

Make element basically immutable
parents 88402c54 c96e2478
......@@ -42,22 +42,34 @@ class Element(object):
The simtk.openmm.app.element module contains objects for all the standard chemical elements,
such as element.hydrogen or element.carbon. You can also call the static method Element.getBySymbol() to
look up the Element with a particular chemical symbol."""
look up the Element with a particular chemical symbol.
Element objects should be considered immutable
"""
_elements_by_symbol = {}
_elements_by_atomic_number = {}
def __init__(self, number, name, symbol, mass):
"""Create a new element
Parameters:
number (int) The atomic number of the element
name (string) The name of the element
symbol (string) The chemical symbol of the element
mass (float) The atomic mass of the element
"""
## The atomic number of the element
self.atomic_number = number
self._atomic_number = number
## The name of the element
self.name = name
self._name = name
## The chemical symbol of the element
self.symbol = symbol
self._symbol = symbol
## The atomic mass of the element
self.mass = mass
self._mass = mass
# Index this element in a global table
s = symbol.strip().upper()
assert s not in Element._elements_by_symbol
Element._elements_by_symbol[s] = self
if number in Element._elements_by_atomic_number:
......@@ -81,6 +93,28 @@ class Element(object):
def getByAtomicNumber(atomic_number):
return Element._elements_by_atomic_number[atomic_number]
@property
def atomic_number(self):
return self._atomic_number
@property
def name(self):
return self._name
@property
def symbol(self):
return self._symbol
@property
def mass(self):
return self._mass
def __str__(self):
return '<Element %s>' % self.name
def __repr__(self):
return '<Element %s>' % self.name
# This is for backward compatibility.
def get_by_symbol(symbol):
s = symbol.strip().upper()
......
import pickle
import unittest
from simtk.unit import dalton
from simtk.openmm.app import element
class TestElement(unittest.TestCase):
def test_immutable(self):
def modifyElement():
# this should not be allowed
element.sulfur.mass = 100*dalton
self.assertRaises(AttributeError, modifyElement)
def test_pickleable(self):
newsulfur = pickle.loads(pickle.dumps(element.sulfur))
# make sure that a new object is not created during the pickle/unpickle
# cycle
assert element.sulfur == newsulfur
assert element.sulfur is newsulfur
assert id(element.sulfur) == id(newsulfur)
def test_attributes(self):
assert element.hydrogen.atomic_number == 1
assert element.hydrogen.symbol == 'H'
assert element.hydrogen.name == 'hydrogen'
assert element.hydrogen.mass == 1.007947 * dalton
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment