Molecular Dynamics Simulation In Java, by Thilo Stöferle

* Abstract
* Program Usage
* Technical Information
* Future

Release Date: 12-Oct-96 (Version 1.0)

"Java" is a registered trademark of Sun Microsystems, Inc.


The MDModel program has been developed as project for the &quotSoftware Praktikum" at the Computational Physics Group at the Universität Heidelberg; tutor has been Thorsten Hapke.
It offers an experimental environment for simple molecular dynamics simulations. Main intention was to provide fast visual feedback of a single simulated molecule instead of very exact scientific results or simulating larger systems. With MDModel one has the chance to play around with parameters and molecules and get an instant response of the MD model to get an idea how molecular dynamics work.
As this is implemented using the new programming language Java, it runs on every computer with a Java capable browser (as an applet) or Java system (as an application).


This section is about launching MDModel with initial parameters and about the structure of the user interface.

- Arguments On Program Startup

MDModel can be run as both Java applet and Java application. The names of the parameters are the same for both methods except the way of actually setting a parameter. If you are not familiar with applet tags or Java application invokation, please read these sections in the browser or Java system manuals. Since all parameters can also be set through the user interface, you do not need to use any parameters on startup at all.

In the applet case, parameters are provided by parameter/value pairs like in other applets. Remember that the CODEBASE tag tells the applet where its classes and its data files are.

[... other applet tags ...]

When running as an application, parameters with their values are submitted in the command line. As there obviously is nothing like a CODEBASE tag here, file names have to be a full qualified URL.

java MDModel molecule &quotfile:///home/tstoefer/mdmodel/c20.cfg"

Possible parameters are listed below:

par.: molecule
val.: URL
Sets the initial molecule data. If the suffix of the file name is ".pdb", the file is imported from PDB format, otherwise standard &quotcraps" format is used.
par.: chain
val.: String
Specifies the desired chain in the molecule file. If omitted, the first chain in the file is read (for &quotcraps" files) or every atom (for PDB files).
par.: parameter
val.: URL
Sets the initial parameter data file. The file must be in the craps format. Unfortunately, only few of the various parameter settings of MDModel can be retrieved due to current limitations of the file format.
par.: doublebuffer
val.: boolean
Enables or disables double buffering. This feature eliminates the flickering in the animation. Valid boolean values are:
For &quottrue": yes y 1
For &quotfalse": no n 0
par.: depthcue
val.: boolean
Enables or disables depth cueing. This is important for a more realistic depth experience of the rendered molecules (only in line rendering mode).
par.: autorotation
val.: boolean
Switches automatic rotation around the y-axis on or off.
par.: backcolor
val.: hex rgb color
Sets the background color for the rendering screen area. Format of the color is RRGGBB, while RR, GG and BB range from hexadecimal 00 to FF (decimal 255), specifying each color component. (This is the same format as for example in HTML documents.)
par.: backimage
val.: URL
Sets a background image. This might look nicer than uni-colored backgrounds but consumes some rendering performance.
par.: renderstyle
val.: style tag
Sets the style of rendering. The style tag is one of line, ball or lineball to have the molecule represented by bonding lines, the atoms as balls or both.

- The User Interface

The user interface of MDModel is resembled by a rendering area where the molecule is drawn in a three-dimensional projection, a line of buttons, a line of &quotcard-selectors" and a multi-purpose area. Because of the many options and informations provided by the user interface, the applet (via width and height tags) or the application (by just making the window large enough) should be preferably run at dimensions of 800x600 and up.

Screenshot of MDModel

Screenshot of MDModel at work.

* Rendering Area

While over the rendering area, pressing the left mouse button and dragging the mouse alters the view of the molecule.

* Buttons

Explanation of the buttons:

Start Starts the molecular dynamics simulation.
Stop Stops the molecular dynamics simulation.
Center Molecule Re-centers the molecule if it has diffused away or has become to big or small.

* &quotCard-Selectors" And Multi-Purpose Area

The &quotcards" work like the register-like elements common to many operating systems. Pressing a card-selector changes the information contents in the multi-purpose area changes according to the specific selector.

Forces Here you can enable/disable force calculations for each kind of force.
See the &quotTech" section for details on how each force affects the molecule.
Statistics Displays statistics about the potential energy of each kind of interaction as well as the total kinetic, total potential and total system energy.
Mol. Geo. Displays information about the current geometry of the molecule. This includes the x,y,z dimensions and the distance from one end to another (for unforked chains). The average bond length and bond angle is also shown.
Last but not least the performance (measured in frames/steps per second) of the renderer and the simulation subsystem is displayed.
Energy Plot This is actually the same information as shown under &quotStatistics", but this time displayed graphically. Watch the energy being exchanged between the different kind of potentials and the kinetic energy. Do not get confused when the plotting area is suddenly cleared, because the current plotter class implementation does not know how to refresh properly if the plotting area has to be rescaled or refreshed. Another problem with this kind of area plots is that negative energies are plotted incorrectly but the total sum of all energies is always shown properly, of course.
Parameter Here you can change the simulation parameters. Press &quotApply" if you want to really set the altered parameters, press &quotCancel" to abort the changes. If you have changed the &quotinitial temperature" parameter, reload the molecule (card &quotConfigs") to reinitialize it with the new temperature.
See the &quotTech" section for details on the meaning of the parameters.
Configs If you want to load a new molecule, set the URL and the desired chain and press &quotOpen". The current implementation knows about PDB files and &quotcraps" files. Leave &quotchain" empty if you want all the molecule data (for PDB files) or the first chain (for &quotcraps" files). Press &quotCancel" to abort. It is not recommended to simulate common PDB molecules, because the current MD implementation only works right for monomers. Nevertheless, PDB files can just be viewed correctly.
With parameter files, it works accordingly. Currently, only the &quotcraps" format is understood.
Renderer Switch renderer settings (double buffering, depth cueing) or the automatic rotation (which can be very disturbing). You can also choose between three styles of rendering: Line, Ball and Line+Ball.


This section covers details of the molecular dynamics simulation and information about how MDModel is actually implemented.

- Molecular Dynamics Simulation

* Integration

The initial kinetic energy of each atom is drawn from the Boltzmann curve using the initial temperature settings. Important: This is only done on reloads of the molecule (pressing &quotOpen" in the &quotConfigs" card).
The movement of the atoms is calculated by integrating locations and velocities and calculating the forces. If the integration time step is too large, watch the energy conservation principle fail.

Integration step is h, r is the location vector, v the velocity vector and f the force vector.

  1. r(t+h) = r(t) + v(t)*h + 1/2 f(t) * h2 / m
  2. v(t+h/2) = v(t) + 1/2 f(t) * h / m
  3. f(t+h) (calculate forces)
  4. v(t+h) = v(t+h/2) + 1/2 f(t+h) * h / m

* Forces And Potentials

The MD simulation calculates four different kind of potentials/forces between the atoms:

  • Bond length (&quotHooke")
  • Bond angle (&quotBend")
  • Dihedral (&quotTorsion")
  • Van-der-Waals (with &quotLennard Jones" potential)

Only a brief idea of each kind of force is explained, because the actual exact theory of the underlying physics and mathematics is beyond my knowledge.

* Bond Length

This is part of the &quotBead-Spring" model, where atoms are regarded as dimensionless balls connected by little springs. These springs excert a restoring force on each of the bonded atoms which is proportional to the displacement from the balanced position what is also as &quotHooke's Law".
This force is calculated on each 2-atom pair.

Potential: U = 1/2 k ( r - r0 )2

* Bond Angle

quotBend&" forces are also part of the &quotBead-Spring" model. Atoms tend to have their energetically most favorable orientation to their neighbors, so e.g. you will usually have monomers in a thedrahedrical configuration. The magnitude of the restoring force is dependent on the differences of the cosines of the bond angles to the adjacent atoms.
This force is calculated on each 3-atom triple.

Potential: U = 1/2 k ( cos theta - cos theta0 )2

* Dihedral

This resembles torsion forces, excerted by neighboring atoms on each side of a bond applying some &quottorque" on the bond.
This force is calculated on each 4-atom quadruple.
The current implementation of the calculation is obviously flawed in some way, so it is better to leave &quotTorsion" forces switched off.

Potential: U = SUMn kn [ 1 + cos ( n*phi - phasen)]
(phase: +1 for phase 0, -1 for phase pi)

* Van-der-Waals

Van-der-Waals interaction is caused by slightly inequally distributed charges (electrons and nucleus) in an atom which attracts or repells other atoms. To model this situation, the simulation uses the &quotLennard Jones" potential, which has a distance of no force (sigma) and a maximum attracting potential (epsilon).
The nearest neighbors are excluded from LJ interaction because forces between them are modeled differently. Besides them, one would have to let each atom interact which each of the other atoms, but as the LJ potential gets very weak at a long distances, lots of calculation time can be saved when using a &quotcutoff": Atoms beyond this distance are neglected.
If one takes a closer look, e.g. monomers at the end of a chain and in the middle have different epsilon values, what can be taken into account by enabling the &quotAutoEps" option.

Potential: U = 4 epsilon [ (sigma/r)12 - (sigma/r)6 ]

- Implementation Details

An important feature of the implementation is that it is done in Java. This enables the user to run MDModel independently from the type of computer hardware or the operating system, as long as some Java capable software exists on it.
Java has some unique superior design features, which are responsible for its more and more wide-spread use in software development. But as Java is quite new and has just emerged, it still has some - say &quotuncertainties" - which make life for user and programmer harder. The promised stability and security (you might well experience their lacking while using MDModel) is yet to become realized.
Basic Java programming knowledge is precluded in the following explanations of the interior design of MDModel.

* Applet / Application Polymorphism

As you might have noticed, MDModel can be run via a Java capable browser or as a standalone Java application.
This is achieved by basing the user interface on the main MDControl class (which is a subclass of Panel class) rather than on the Applet class. Because the MDModel class also implements a main() method which opens an own AppFrame (the frame handles the close-window-request), it adds the MDControl object to the frame and thus runs as an application exactly the same way as an applet.
Differentiations between the two execution types are also necessary in the parsing of the parameters (applet parameters versus command line arguments), the display of status messages (applet: status bar, application: window title) and the loading of images (built into Applet class only). Disregarding these minor changes, all the rest of MDModel can stay the same.

* Subsystems With Multithreaded Architecture

It is common implementation behavior in a thread-capable system to let time-consuming tasks execute in their own little environment virtually parallel to other tasks. MDModel takes advantage of this feature by having separate threads for each of the controlling, rendering and simulating subsystems.

Figure explaining the main architecture

To achieve communication between the user interface and the simulation and renderer thread, all settings and parameters have been externalized in a Settings object which &quotknows" the configurable features of MDSimulation as well as of Renderer.
The actual render or calculation requests are issued asynchronously by MDControl to the thread of Renderer and MDSimulation.

* Benefits Of Object Oriented Design

The reuse of already-written code by OOP is one of the distinct features in the design of MDModel.
The (abstract) Renderer class, for example, implements common features of all Renderer subclasses, that is: communication with Settings objects, handling render requests and implementing things like double buffering or background images. The LineRenderer, which draws a line-style rendering of the molecule, is placed on top of this. On top of LineRenderer there is the BallRenderer which uses the LineRenderer to also draw bonding lines in addition to the atom balls if requested by the user.
Also all forces have a common base class Forces, which implements features every force must have and generalizes the way of &quotusing" force objects (Forces is an abstract class).
The interface mechanism of the Java language is used to formalize import filters for the molecule and parameter files. Importable is the interface every molecule importer has to implement, ParamImporter is for parameter file importers.

- Class Listing

A detailed documentation of each class and its methods and fields can easily be generated by running javadoc over the source files. Here is just a brief abstract of the purpose of each class.

MDModel Main class to execute as applet or application. Its only task is to launch MDControl.
MDControl This is the main controller in MDModel; it handles all other objects and runs as a separate thread.
GUIHandler All rather &quotstatic" user interface handling is done by this class, except for the &quotdynamic" mouse dragging, which is handled by MDControl.
Settings This class incorporates an external settings mechanism for all parameters and settings under user control.
Renderer This abstract base class for all molecule renderers implements the communication with Settings objects, handling of render requests and some general animation features. To do the actual rendering, which is done in a separate thread, it calls the render() method in its subclasses.
LineRenderer This class renders the bonds of the molecule as lines (with some sort of depth cueing). It uses centric projection with a vanishing point.
BallRenderer This class renders the atoms of the molecule as balls, and/or the bonds as lines if desired. The code for the creation of the graphical ball images is &quotborrowed" from the &quotMoleculeViewer" example provided in the JDK.
MDSimulation All simulation initialization and integration is done here running in a separate thread.
Forces This is the abstract base class for all forces, implementing some general fields (like the potential energy and number of interactions) and some helpful &quotatom collector" for all n-atom-interactions.
ForceHooke Bond length forces are calculated by this class.
ForceBend Bond angle forces are calculated by this class.
ForceTorsion Torsion forces are calculated by this class. The physical results on the molecule are a bit strange - read: buggy - in the current implementation.
ForceVdw Van-der-Waals forces (&quotLennard Jones potential") are calculated by this class.
Importable This interface defines the common methods all import filters for molecule data files have to implement.
ImportCfg Polymers stored in &quotcraps" format are imported by this class.
ImportPDB A rudimentary PDB file reader is implemented by this class.
ParameterImporter This interface defines the common methods all importer filters for parameter files have to implement.
ParamCfg Imports MD simulation parameters from &quotcraps" files.
Molecule This class manages all atoms, bonds and other molecule characteristics.
Atom All information of a single atom like location, velocity, force acting on it, mass and LJ-epsilon is stored in an Atom object.
Bond What atoms are bonded with a base atom is stored here.
Transform A Transform object can apply certain transformations Vector3 objects: translation, scaling and rotation around the center. This is used by the Renderer to transform the molecule from its system space to an on-screen-projectable 3D world space.
Vector3 Basic vector operations for 3-dimensional vectors are implemented by this class.
Plotter This class draws area, line and dot plots, which is used in the &quotEnergy Plot" card.
RingBuffer A ring buffer and the accessing methods to it are provided by this class. This is needed by the Plotter class for temporary queing of its plot requests.
ColorField This very simple class just displays a framed colored field, which is used for the legend in the &quotEnergy Plot" card.
AppFrame The only extension to the Frame superclass is that an AppFrame calls System.exit() if the user wishes to close the window. Only needed if MDModel is launched as an application.


As MDModel is my project for the obligatory practical training in addition to the computer science lectures, it is finished for me by fixing development at the current state, fulfilling all provided requirements. But there are still lots of ideas and enhancements which could be implemented by others (perhaps future practial training groups) in order to make MDModel even nicer.

  • Fixing mysterious crashes of the renderer
  • Fixing the torsion force calculation
  • More sophisticated rendering techniques using the yet-to-come standard Java 3D package
  • Creating and simulating the molecule in a VRML 2.0 world
  • Improve the user interface with new versions of AWT in yet-to-come JDKs
  • Simulate systems with more molecules
  • Simulate molecules with other than monomer chains correctly

- Author

Thilo Stöferle, the author of MDModel, wishes to thank Thorsten Hapke for always having time and patience for well-understandable explanations of the physical model and the mathematics.

* Contact

"Thilo Stoeferle" Email:

Home Java-Sammlung