1 CE 530 Molecular Simulation Lecture 4 Object-Oriented Programming and Etomica David A. Kofke Department of Chemical Engineering SUNY Buffalo kofke@eng.buffalo.edu 2 Object-Oriented Programming Programming accomplished through the actions and interactions of objects • everything is an object Forces abstract thinking about the structure and activities of a program Promotes re-use of code and extension to new applications Good design is difficult to develop • requires thorough understanding of application • conversely, its use facilitates a better understanding of application presents a good vehicle for teaching It’s fun! What is an Object? A fancy variable • stores data • can perform operations using the data Every object has a type, or “class” • analogous to real, integer, etc. Fortran: real x, y, z Java: Atom a1, a2; • you define types (classes) as needed to solve your problems public class Atom { double mass; Vector r, p; } • types differ in the data they hold and the actions they can perform on it • every object is an “instance of a class” a1 = new Atom(); 3 4 Makeup of an Object Fields (data) • primitive types (integer, float, double, boolean, etc.) • handles to other objects complex objects are composed from simpler objects (composition) Methods (actions) • “subroutines and functions” • may take arguments and return values • have complete access to all fields of object A class has an interface • what the object presents to enable its manipulation • implementation (how it accomplishes its operations) can be hidden • object is viewed in terms of its “actions” and not its “thoughts” Inheritance • • • • can define subclasses which inherit features of parent class same interface, but different implementations subclasses can be used anywhere parent class is expected mechanism to change behavior of simulation Detailed Look: Atom parentGroup (via node) Space makes 5 AtomFactory makes type coord seq node next (via seq) Atom previous (via seq) makes any classes allatomAgents[] ia makes Integrator childList (via node) Click here for the complete API specification 6 Etomica Application Programming Interface (API) • Library of components used to assemble a simulation • Can be used independent of development environment Invoked in code programmed using Emacs (for example) GUI-based development environment • Simulation is constructed by piecing together elements • No programming required • Result can be exported to run stand-alone as applet or application Written in Java • Widely used and platform independent • Features of a modern programming language • Object-oriented Vehicle for presentation of molecular simulation methods 7 Etomica API Simulation SimulationGraphic Space Display Vector, Tensor Device Coordinate, Orientation Controller Species Phase Boundary Configuration Potential Meter Integrator 8 Simulation Elements: Simulation Simulation SimulationGraphic Space Simulation collects all the other elements of the simulation and ensures that they are connected for proper interaction Display Vector, Tensor Device There is only one instance of a Simulation in anyCoordinate, Orientation Controller applet/application Species • Applet: runs in a web page Phase • Application: runs as a program, from command line SimulationGraphic Boundary Configuration • Subclass of Simulation used when preparing a simulation with a Potential graphical user interface (GUI) Meter Integrator 9 Simulation Elements: Space Space defines properties of the physical space in which the simulation is performed Simulation • Dimensionality (1D, 2D, 3D, etc.); continuum SimulationGraphic Spacevs. lattice •Display Construction of vectors, tensors Vector, Tensor •Device Makes Coordinate for placement in each Atom Coordinate, Orientation position and momentum vector Controller • CoordinatePair defines how distances are computed Species • Constructs various types of Boundary for placement in each Phase Phase Concrete classes • Space1D • Space2D • Space3D Boundary Configuration Potential Meter Integrator 10 Simulation Elements: Controller Governs general plan of action for simulation • For example: run forever, as controlled by an interactive Stop/Resume button Simulation run a fixed number of relaxation/production cycles, then quit SimulationGraphic run over a series of state conditions for a fixed Space duration at each Display Oversees activities of Integrator Vector, Tensor • Makes Device connections between Integrator and other elements Coordinate, to Orientation ensure proper functioning Controller • Turns Integrator on and off according to plan Speciesof action Phase Entire Simulation Entire Simulation Initialization Initialization Initialization Boundary Reset block sums Reset block sums Reset block sums Configuration New configuration New configuration 1 move per cycle 1 move per cycle cycles per block cycles per block Add to block sum Compute block average blocks per simulation Compute final results Add to block sum Compute block average blocks per simulation Compute final results Potential Meter Entire Simulation New configuration 1 move per cycle Add to block sum cycles per block Integrator Compute block average blocks per simulation Compute final results 11 Simulation Elements: Integrator Adds the physics needed Simulation to generate configurations properly • variousSimulationGraphic integration schemes introduced bySpace developing a new integrator Display Vector, Tensor • Molecular dynamics integrators Device hard-potential dynamics various kinds of soft-potential integrator • Monte Carlo integrators more later Coordinate, Orientation Controller Species Phase Places an Agent in each atom to assist integration • for example, hard potential places Agent recording collision time collision partner Boundary Configuration Potential Meter Fires IntegrationIntervalEvent to notifyIntegrator listeners that simulation has proceeded one step 12 Simulation Elements: Integrator Simulation run method for top-level Integrator class SimulationGraphic Space public void run() { Display Vector, Tensor stepCount = 0; int iieCount = interval+1; Device Coordinate, Orientation while(stepCount < maxSteps) { while(pauseRequested) doWait(); Controller if(resetRequested) {doReset(); resetRequested = false;} if(haltRequested) break; Species doStep(); //abstract method in Integrator. subclasses implement algorithms (MD/MC) if(--iieCount == 0) { //count down to determine when a cycle is completed Phase fireIntervalEvent(intervalEvent); //notify listeners of completion of cycle iieCount = interval; Boundary } if(doSleep) { //slow down simulation so display can keep up Configuration try { Thread.sleep(sleepPeriod); } catch (InterruptedException e) { } Potential } stepCount++; } //end of while loop Meter fireIntervalEvent(new IntervalEvent(this, IntervalEvent.DONE)); } //end of run method Integrator 13 Simulation Elements: Phase Collects molecules that interact Simulation • holds root of hierarchy of atoms/moleculesSpace SimulationGraphic • handles addition/removal of molecules Display • multiple phases possible in one simulation Device • sets up base lists of all atoms, molecules,Controller species Vector, Tensor Coordinate, Orientation defines which atoms are up or down from a given atom Species Holds a Boundary object (from Space) that Phase defines the boundary conditions used in the phase Boundary Houses Configuration object that creates or saves aConfiguration configuration of molecules Potential Meter Integrator 14 Simulation Elements: Meter Simulation Measurement of simulation property SimulationGraphic • Configurational property in a phase Space Display potential Device energy kinetic energy density structure Vector, Tensor Coordinate, Orientation Controller Species • Each phase has by default kinetic and potential Phase energy meters others added as desired • Can also keep track of other quantities of interest simulation time Potential Boundary Configuration Accumulator handles all block averagingMeter and error analysis • listener for IntegrationIntervalEvent Integrator 15 Simulation Elements: Species Simulation Holds AtomFactory type of SimulationGraphicthat defines how a particular Space molecule is constructed Display Vector, Tensor • how many atoms of which type • nominal arrangement of atoms in molecule Controller Device Coordinate, Orientation Places SpeciesAgent in each phase to manage molecules Species there Phase • root of atom hierarchy for species in phase • looping over molecules • addition and removal of atoms Potential Boundary Configuration Basis for defining interaction potential between molecules Meter • but does not by itself describe the pair potential Integrator 16 Simulation Elements: Potential Defines interaction between atoms (and thereby molecules) Simulation • Hard potential SimulationGraphic Display Device Space collision time collision dynamics • Soft potential force, virial • All potentials energy Vector, Tensor Coordinate, Orientation Controller Species Phase Boundary Intermolecular potentials collect interatomic potential • Potential1: intramolecular • Potential2: intermolecular Hierarchical arrangement • More later Configuration Potential Meter Integrator 17 Simulation Elements: Display Simulation SimulationGraphic from the simulation Space Presents information Display • display Vector, Tensor of configuration for animation Device • display of data table graph Connects to Meter to get information Listener of IntegrationIntervalEvent Coordinate, Orientation Controller Species Phase Boundary Configuration Potential Meter Integrator 18 Simulation Elements: Device Simulation InteractiveSimulationGraphic manipulation of simulation Space Display • sliders, buttons, comboBoxes etc. for setting propertiesVector, andTensor affecting course of simulation Device Coordinate, Orientation Controller Species Phase Boundary Configuration Potential Meter Integrator Putting It Together import etomica.*; public class MySimulation extends SimulationGraphic { //Constructor public void init() { //Instantiate classes super(Space2D()); controller = new Controller (this); integrator = new IntegratorHard(this); potential = new P2HardSphere(this); species = new SpeciesSpheresMono(this); phase = new Phase(this); display = new DisplayPhase(this); //Tie elements together this.elementCoordinator.go(); } //End of constructor public static void main(String[] args) { MySimulation simulation = new MySimulation(); simulation.makeAndDisplayFrame(); } //End of main } //End of MySimulation class 19 20 Running It Compile source • javac filename filename.java is the source file filename should be the same as the class defined in the file creates filename.class Run as an applet for class named Applet1 <HTML> <HEAD> <TITLE>Applet HTML</TITLE> </HEAD> <BODY bgcolor="#ffffff"> <APPLET CODE="Applet1.class" archive=“etomica.jar" WIDTH=640 HEIGHT=350></APPLET> </BODY> </HTML> need to reference etomica.jar, which contains simulation classes Load html in browser Enjoy your applet! Run as an application • java filename