Design Patterns For Multiphysics Modeling in Fortran 2003 and C++
Design Patterns For Multiphysics Modeling in Fortran 2003 and C++
We present three new object-oriented software design patterns in Fortran 2003 and C++. These
patterns integrate coupled differential equations, facilitating the flexible swapping of physical and
numerical software abstractions at compile-time and runtime. The Semi-Discrete pattern supports
the time advancement of a dynamical system encapsulated in a single abstract data type (ADT).
The Puppeteer pattern combines ADTs into a multiphysics package, mediates interabstraction
communications, and enables implicit marching even when nonlinear terms couple separate ADTs
with private data. The Surrogate pattern emulates C++ forward references in Fortran 2003. Af-
ter code demonstrations using the Lorenz equations, we provide architectural descriptions of our
use of the new patterns in extending the Rouson et al. [2008a] Navier-Stokes solver to simulate
multiphysics phenomena. We also describe the relationships between the new patterns and two
previously developed architectural elements: the Strategy pattern of Gamma et al. [1995] and the
template emulation technique of Akin [2003]. This report demonstrates how these patterns man-
age complexity by providing logical separation between individual physics models and the control
logic that bridges between them. Additionally, it shows how language features such as operator
overloading and automated memory management enable a clear mathematical notation for model
bridging and system evolution.
Categories and Subject Descriptors: D.1.5 [Programming Techniques]: Object-oriented Pro-
gramming; D.2.10 [Software Engineering]: Design—Methodologies; D.2.11 [Software Engi-
neering]: Software Architectures—Data abstraction, information hiding; D.3.3 [Programming
D. Rouson acknowledges supported from the Office of Naval Research (Contract N00014-08-1-0086)
via the Research Foundation of the City University of New York.
Authors’ addresses: D. W. I. Rouson and H. Adalsteinsson, Sandia National Laboratories, Scalable
Computing R&D, MS 9158, Livermore, CA 94550; email: {rouson,hadalst}@sandia.gov.; J. Xia,
IBM Corporation, IBM Toronto Lab, 8200 Warren Ave., Markham, Ont., Canada L6G IC7; email:
[email protected].
2010
c Association for Computing Machinary. ACM acknowledges that this contribution was au-
thored or co-authored by a contractor or affiliate of the [U.S.] Goverment. As such, the Goverment
retains a nonexclusive, royalty-free right to publish or reproduce this article, or to allow others to
do so, for Goverment purposes only.
Permission to make digital or hard copies of part or all of this work for personal or classroom use
is granted without fee provided that copies are not made or distributed for profit or commercial
advantage and that copies show this notice on the first page or initial screen of a display along
with the full citation. Copyrights for components of this work owned by others than ACM must be
honored. Abstracting with credit is permitted. To copy otherwise, to republish, to post on servers,
to redistribute to lists, or to use any component of this work in other works requires prior specific
permission and/or a fee. Permissions may be requested from Publications Dept., ACM, Inc., 2 Penn
Plaza, Suite 701, New York, NY 10121-0701 USA, fax +1 (212) 869-0481, or [email protected].
C 2010 ACM 0098-3500/2010/01-ART3 $10.00
DOI 10.1145/1644001.1644004 http://doi.acm.org/10.1145/1644001.1644004
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
3:2 • D. W. I. Rouson et al.
Languages]: Language Constructs and Features—Abstract data types, classes and objects, data
types and structures, modules, packages, polymorphism, procedures, functions, and subroutines;
G.1.8 [Numerical Analysis]: Partial Differential Equations—Spectral methods
General Terms: Design, Languages
Additional Key Words and Phrases: Design patterns, multiphysics modeling, Lorenz equations
ACM Reference Format:
Rouson, D. W. I., Adalsteinsson, H., Xia, J. 2010. Design patterns for multiphysics modeling in
fortran 2003 and C++. ACM Trans. Math. Softw. 37, 1, Article 3 (January 2010), 30 pages.
DOI = 10.1145/1644001.1644004 http://doi.acm.org/10.1145/1644001.1644004
1. INTRODUCTION
Over the past decade, there appears to have emerged awareness that the soft-
ware crisis commonly spoken of in the software engineering community in the
1970s has entered the critical path of the scientific programming community. As
the steady march of progress in individual scientific disciplines continues, the
focus naturally turns toward leveraging successes in one domain to spawn new
capabilities for multidomain investigations. Such work falls under the rubric of
multiphysics modeling. As an application’s capabilities grow, the process of scal-
ing up to hundreds of program units (e.g., procedures, modules, components, or
classes) impacts project budgets and timelines at least as much as the process
of scaling up to hundreds of execution units (e.g., processors, processes, threads,
or cores).
That multidisciplinary scientific software engineering warrants greater
scrutiny has been noted at high levels. The 1999 Presidential Information
Technology Advisory Committee (PITAC) summarized the situation [Joy and
Kennedy 1999]:
Today it is altogether too difficult to develop computational science software
and applications. Environments and toolkits are inadequate to meet the needs
of software developers in addressing increasingly complex interdisciplinary. . . .
In addition, since there is no consistency in software engineering best practices,
many of the new applications are not robust and cannot easily be ported to new
hardware.
(1) What are the best units in which to decompose a design, that is, what are
modules?
(2) What are the best practices for decomposing the design into these modules?
2. METHODOLOGY
2.1 Nomenclature
In any multilanguage discussion of OOP, one encounters a terminology conun-
drum. While terms such as abstract data type (ADT) have a universal mean-
ing, there also exist more commonly used language-specific synonyms. For ex-
ample, ADT corresponds closely to class in C++ and derived type in Fortran
2003. Similarly, what the language-neutral Unified Modeling Language (UML)
[Booch et al. 1999] diagrammatic description standard refers to as attributes
and methods are typically termed data members and member functions in C++
and components and type-bound procedures in Fortran 2003.
Yet other examples are the terms encapsulation and information hiding,
which in C++ imply protecting data members and member functions via the pri-
vate keyword in a class definition. Fortran likewise uses the keyword private for
1 http://www.acm.org.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
Design Patterns for Multiphysics Modeling in Fortran 2003 and C++ • 3:5
hiding data and procedures, but employs modules as the encapsulation mech-
anism. Viewed globally for purposes of introducing scoping tools for data, data
types, and procedures, Fortran modules more closely match namespaces in C++.
Furthermore, not only does the name associated with a given concept often
differ among languages, but occasionally the reverse also holds: a name com-
mon to different languages may be associated with different concepts in those
languages. For example, the C++ term class denotes an ADT as already noted,
whereas the Fortran term class denotes a polymorphic entity whose dynamic
type may vary at runtime between the type named in the class construct and
any of its extended (child) types. In C++, such dynamic polymorphism is pro-
vided to references or pointers to base classes. An invocation of a type-bound
procedure (C++ virtual member function) on such an entity is bound to the
appropriate procedure based on the dynamic type of the entity at runtime.
Our resolution of the above conflicts follows: whenever possible, we adopt
language-neutral terminology such as ADT and object (an instance of a specific
ADT). When presenting design patterns, we default to Fortran terms since its
new standard motivates this article. On first usage, we follow each Fortran
term with a parenthetical note containing the italicized name of the closest
corresponding C++ term. Table I summarizes these correspondences.
Although our parenthetical phrases relate Fortran constructs to C++ ones,
the relationship is rarely one of exact equality. Often, both constructs could be
used in additional ways that do not correspond with the typical usage of the
other.2 For example, in suggesting that Fortran 2003 derived types correspond
to C++ classes, we are neglecting the fact that both Fortran derived types and
C++ classes can be parameterized. The reason for neglecting this is that the
2 This is true even for many non-object-oriented constructs. For example, Fortran requires compilers
to store considerably more state in a pointer or an array than does C++. Fortran pointers can be
queried for their allocation status and Fortran arrays can be queried for their size and shape;
whereas C++ pointers are simply memory addresses and C++ arrays do not carry information
about their layout.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
3:6 • D. W. I. Rouson et al.
items 2–4 enumerate the three critical factors in each pattern. These are often
termed collectively the three-part rule [Alexander et al. 1977].
In some instances, what constitutes a pattern depends on perspective. A re-
curring, programmer-constructed solution in one language might be an intrin-
sic language facility in another. For instance, as pointed out by Gamma et al.
[1995] and demonstrated in Fortran 90/95 by Decyk et al. [1997a; 1997b; 1998],
one might construct patterns for inheritance, encapsulation, or polymorphism
in a procedural language, whereas, by definition, these exist in object-oriented
languages. Although it is no longer necessary to emulate these features with
the advent of Fortran 2003, Fortran’s approach to supporting OOP is not well
known among C++ and Fortran 90/95 programmers. The next subsection sum-
marizes the process.
3 InFortran 2008, it will be possible to move the implementation of the type-bound procedures to a
separate submodule, leaving only their interfaces in the module that defines the type. This allows
complete documentation of the interface details needed by users of the module without exposing
details of how the services described in the interface are implemented.
4 Henceforth, we use the Courier New font for language keywords and code excerpts.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
3:8 • D. W. I. Rouson et al.
of brevity, we defer the Fortran ADT code examples to Section 3 and refer the
reader to Metcalf et al. [2004] for additional information.
Fig. 1. Semidiscrete pattern class model: abstract type integrable model and extended type
dynamical system.
Figure 1 depicts a UML class model for the Semi-Discrete pattern. The
italic bold typeface used for the integrable model ADT name indicates that
it is abstract. We refer to the concrete extended type generically as a
dynamical system. As stipulated by the abstract interface it implements, the ex-
tended type defines a function d dt() that takes a dynamical system argument
with state {V1 , V2 , . . . , Vm }T and uses the governing Equations (4) to calculate
and return a dynamical system with state {d V1 /d t, d V2 /d t, . . . , d Vm /d t}T .
One can use the return object in time marching algorithms of the form
tn+1
n+1 = V
n+ dV
V dt , (5)
tn d t
where tn denotes nth time step, tn+1 ≡ tn + t and t is the time step.
Online Appendices A.1 and B.1 provide Fortran 2003 and C++ code, respec-
tively, employing the Semi-Discrete pattern to integrate the Lorenz system,
a reduced-dimension model for weather with parametric dependence on the
constants σ , ρ, and β [Lorenz 1963]:
⎧ ⎫ ⎧ ⎫
σ (v2 − v1 ) ⎬
d ⎨ 1⎬ ⎨
v
v2 = v1 (ρ − v3 ) − v2 . (6)
d t ⎩ v ⎭ ⎩ v v − βv ⎭
3 1 2 3
The code uses the explicit Euler algorithm, which approximates the integral
n )t. This function evaluation and product occur via
in Equation (5) as f (V
overloaded arithmetic on instances of a lorenz ADT that plays the role of
dynamical system in extending integrable model. Equation (5) thus takes the
form
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
Design Patterns for Multiphysics Modeling in Fortran 2003 and C++ • 3:11
where “%” is the Fortran component selector analogous to “.” in C++. To guar-
antee execution, the integrable model ADT mandates that its extended types
define assignment, addition, and multiplication operators in addition to a type-
bound time derivative function d dt(). The end result is program syntax mir-
roring the original mathematical syntax in Equation (5). Objects replace differ-
ential and algebraic operator results as well as all operands except the RHS in
the multiplication operation. The resulting call tree is determined at runtime
based on the dynamic type passed to integrate(). This one procedure can be
employed for any concrete extended type.
3.2.2 The Solution. Gamma et al. [1995] resolved this problem with the
Strategy pattern. They stated the essence of this pattern as follows: “Define a
family of algorithms, encapsulate each one, and make them interchangeable.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
Design Patterns for Multiphysics Modeling in Fortran 2003 and C++ • 3:13
Fig. 2. Class model for applying the strategy and surrogate patterns to extend the Lorenz model.
Strategy lets the algorithm vary independently from clients that use it (page
315).”
The Strategy pattern severs the link between algorithms and data. Data ob-
jects delegate operations to strategy classes that apply appropriate algorithms
to the data.
Our Strategy pattern implementation defines a timed lorenz type that
extends the lorenz type. As before, the lorenz concrete type extends the
integrable model abstract type. In addition to the deferred bindings that
integrable model stipulates must be implemented by its extended types,
it now contains a reference to an abstract derived type, strategy, to
which integrable model delegates the responsibility to provide a type-bound
integrate() procedure. The strategy defines only the interface (via deferred
binding) for the time integration method, leaving its own extended types to
provide actual quadrature schemes. In applying the strategy pattern, one
passes a reference to a lorenz dynamical system as an actual argument to the
integrate() method of the strategy object. Again, the program syntax mirrors
the mathematical syntax:
class(surrogate), intent(inout) :: this
real , intent(in) :: dt
...
this half = this + this%d dt()∗ (0.5∗ dt)
this = this + this half%d dt()∗ dt
We explain the role of the new type surrogate next.
Figure 2 depicts a UML class model of our Fortran Strategy pattern imple-
mentation, including an empty surrogate type, instances of which substitute for
all references to integrable model objects and their extended types inside the
strategy module. Declaring all such instances with the Fortran class keyword
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
3:14 • D. W. I. Rouson et al.
defers to runtime the resolution of their ultimate dynamic type, which can be
any descendant of the surrogate type. The role played by the surrogate pro-
vides an example of a Fortran-specific design pattern: the Surrogate pattern.
It circumvents Fortran’s prohibition against circular references, wherein one
module’s reference to a second module via a use statement precludes refer-
encing the first module in the second via a reciprocal use. In C++, one avoids
such circular references by using forward references. Forward references allow
one ADT to declare another and then to manipulate references to the declared
ADT without knowing its definition. Online Appendices A.2 and B.2 provide our
Strategy pattern code in Fortran 2003 and C++, respectively. The A.2 imple-
mentation relies upon the Surrogate pattern in lieu of the forward references
available to the C++ code in Appendix B.2.
3.2.3 The Consequences. Since the Strategy pattern uses composition in-
stead of inheritance, it allows better decoupling of the classes that focus on
data (the context) from those that focus on algorithms (behaviors). One ob-
vious advantage is that strategies can provide varying implementations (or
algorithms) for the same behavior, thus giving users more freedom to choose
at runtime based on the problem at hand. Compared to patterns that employ
inheritance as the means for maintaining algorithms (e.g., the Interpreter pat-
tern of Gamma et al. [1995]), the Strategy pattern is much easier to understand
and extend. Since each concrete strategy class implements one particular al-
gorithm for the context, the use of this pattern also encourages programmers
to avoid lumping many different algorithms into one class that often lead to
unmanageable code.
This pattern is commonly used in applications where a family of related al-
gorithms or behaviors exists for the context (data). Examples given by Gamma
et al. [1995] included the register allocation schemes and instruction schedul-
ing policies used in the compiler optimization code in the Register Transfer
Language (RTL) systems. The application of strategy patterns yields great flex-
ibility for the optimizer in targeting different machine architectures.
As with every design pattern, the Strategy pattern also has drawbacks. One
potential disadvantage is that, in applying the pattern, a user must be aware
of the differences among algorithms in order to select the appropriate one.
This sometimes becomes a burden as programmers must acquire knowledge
about various algorithms. Another potential shortcoming of strategies lies in
the possible communication overhead between data objects and algorithm ob-
jects. Although this overhead can normally be minimized by careful design of
the strategy interfaces, a naı̈ve implementer of the strategy pattern may nev-
ertheless attempt to design the interfaces with many unnecessary parameters
to pass between data and algorithms. Thus achieving a balance between data-
algorithm coupling and communication overhead should always be one of the
goals for designing a good Strategy pattern.
multiple abstractions. This poses two problems. The first involves how to facili-
tate inter-abstraction communication. Gamma et al. [1995] addressed interab-
straction communication with the Mediator pattern. When N objects interact,
a software architect can reduce the N (N −1) associations between the objects to
2N associations by employing a Mediator. The Mediator association count stems
from the requirements that the Mediator know each communicating party and
those parties know the Mediator. For example, in a Mediator implementation
presented by Gamma et al. [1995], the sender passes a reference to itself to the
Mediator. The sender must be aware of the Mediator in order to know where
to send the message. Likewise, the Mediator must be aware of the sender in
order to invoke methods on the sender via the passed reference. Figure 3 illus-
trates the associations in an atmospheric boundary layer model, wherein the
air, ground, and cloud ADTs might solve equation sets for the airflow, ground
transpiration, and discrete droplet motion, respectively.
The second and conceptually more challenging problem concerns whether
one can use the Semi-Discrete pattern to implement implicit time advancement
algorithms for systems in which nonlinear coupling terms connect state vari-
ables hidden behind separate interfaces. 5 Of particular concern is the desire to
calculate cross-coupling terms without violating abstractions by exposing their
data. Consider marching the dynamical system defined by Equation (4) forward
in time according to the trapezoidal rule:
V n+1 = V n + t Vn + V n+1 , (8)
2
where the presence of V n+1 on the RHS makes iteration necessary when
contains nonlinearities. One generally poses the problem in terms of finding
the roots of a residual vector such as
f V n+1 = V n+1 − V n + t n +
V V n+1 , (9)
2
where V n is known.
The difficulty arises in finding the roots of f using Jacobian-based itera-
tion methods. Consider Newton’s method. Defining y m as the mth iterative
5 In
the first author’s experience with presenting these patterns, this is the most common question
posed by the audience.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
3:16 • D. W. I. Rouson et al.
y m+1 ≡ y m + y m , (11)
⎡
⎤
n+1
∂ f i ∂ f i t ⎣ ∂i V ⎦
Ji j ≡ = = δi j − , (12)
∂ y j y = y m ∂ V jn+1 V n+1 = y m 2 ∂ V jn+1
n+1 = y m
V
6 Ineqution (11) and elsewhere, we abbreviate a common notation for Jacobians in which the list of
f components appears in the numerator and the list of y components appears in the denominator.
We do not mean for the arrows to connote vectors that transform as first-order tensors.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
3:18 • D. W. I. Rouson et al.
zero. I’ll determine the number of zero elements by multiplying the size of
∂ a /∂ α by the size of ∂ g
/∂ γ after I receive the latter from my ground puppet.
The Puppeteer then holds analogous dialogues with its cloud and ground
puppets, after which the Puppeteer passes an array containing ∂ /∂ V to
integrate(). The latter procedure uses the passed array to form J, which it
then passes to a Puppeteer for use in inverting the matrix system (10). Most
importantly, integrate() does so without violating the Puppeteer’s data pri-
vacy, and the Puppeteer responds without violating the privacy of its puppets.
The Puppeteer’s construction is based solely on information from the public
V
interfaces of each puppet. Figure 5 details the construction of ∂ /∂ in a UML
sequence diagram. Online Appendices A.3 and B.3 illustrate this process.
Fig. 5. A UML sequence diagram for the Puppeteer’s Jacobian contribution. The coordinate()
method calls return solution variables. The next three calls return diagonal blocks of /∂ ¯ V̄ . The
subsequent six calls return off-diagonal blocks. The final two steps allocate and fill /∂
¯ V̄ .
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
3:20 • D. W. I. Rouson et al.
7 The name inverseTimes is intended to be suggestive of the ultimate result. The sample code in
online Appendix A.3 employs Gaussian elimination rather than computing and premultiplying the
inverse Jacobian.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
Design Patterns for Multiphysics Modeling in Fortran 2003 and C++ • 3:21
3.4.2 The Solution. The solution lies in making the Field references in-
side Fluid generic. One way to accomplish this is for the Fluid source code to
reference a generic type in place of all references to Field types. It must fur-
ther be possible to switch the generic type to any desired actual Field type at
compile-time. In C++, this can be accomplished with template classes. Since
the Fortran facilities for generic programming do not include template classes,
there is some utility in emulating these.
Akin [2003] outlined a Fortran programming technique that we refer to as
the Template Class pattern. Here we outline how it enables the creation of a
general multiphysics software architecture when employed in conjunction with
the other patterns described in this paper. The technique involves referring to
all occurrences of the generic type with the text Template$. Since the Fortran
character set does not contain the “$ ” symbol, one can safely perform a text
search, replacing each occurrence of Template$ with the desired actual type
without fear of changing any executable code. By incorporating this procedure
into the automatic process of building executable files, one can emulate delaying
the choice of spatial discretizations to compile-time.
Figure 6 depicts a UML class model for a multiphysics software package:
the Multiphysics Object-oriented Reconfigurable Fluid Environment for Uni-
fied Simulations (Morfeus) under development at Sandia National Laboratories
and the City University of New York.8 Morfeus currently uses Fortran 95 aug-
mented by a Fortran 2003 feature subset we have found to be widely available—
specifically those features common to the g95, gfortran, and Intel compilers at
the time of this writing. The limitations of this feature subset require emulating
runtime polymorphism, inheritance, and templates.
Morfeus employs two template classes: Grid and Field. Switching the
Template$ type in Field to an actual derived type selects basis sets. Currently,
Morfeus supports three basis sets:
(1) A 3D discrete Fourier expansion used for statistically isotropic turbulence
as first employed by Orszag and Patterson (1972),
(2) A hybrid 2D-Fourier/1D-Chebyshev polynomial expansion for flows with
one direction of statistical inhomogeneity as first employed by Kim et al.
(1987),
(3) A time-varying Fourier basis for statistically homogeneous shear flows as
developed by Brucker et al. (2007).
Switching the Template$ type in Grid to an actual type provides ADTs that
store the mesh information for the chosen basis set.
8 http://public.ca.sandia.gov/csit/research/scalable/morfeus.php.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
3:22 • D. W. I. Rouson et al.
Fig. 6. Morfeus class model for simulating of turbulent flow in superfluids (using the
Quantum Fluid and classical fluid classes), semisolid metals (using the Magnetofluid and Cloud
classes), and atmospheric boundary layers (using the Classical Fluid, Scalar, and Cloud classes).
The Template parameters$ are switched to actual types in a precompilation phase.
The Mixture ADT in Figure 6 plays the role of the Puppeteer. At runtime,
the code constructs a Mixture object by associating that object’s pointer compo-
nents with any combination of Tangle, Fluid, Magnetofluid, Scalar, and Cloud
instances. The Tangle component simulates the integrodifferential equations
governing quantum vortex dynamics in superfluid liquid helium [Morris et al.
2008]. The Fluid component solves the incompressible Navier-Stokes equa-
tions for momentum transport and mass conservation in fluid flows. The Mag-
netofluid inherits this behavior from its parent Fluid and couples it to the mag-
netic induction equation, which derives from Maxwell’s equations and governs
the advection and diffusion of magnetic field lines in electrically conducting flu-
ids and plasmas [Knaepen et al. 2004]. The Scalar component solves the scalar
advection/diffusion equation [Rouson et al. 2006]. The Cloud component solves
a drag law for the motion of aerosolized droplets and solid particles [Rouson
et al. 2008b]. In atmospheric simulations, the Mixture ADT aggregates a Fluid,
a Cloud, and a Scalar temperature field [Rouson and Handler 2007].
Since the chosen Fortran subset does not support abstract types and inheri-
tance, Morfeus’s integrand ADT uses aggregation to emulate the runtime poly-
morphism of the integrable model from Section 3.1 in the manner described by
Rouson et al. [2005]. The current integrand code allows for choosing at runtime
among several adaptive Runge-Kutta marching algorithms, including one that
uses implicit integration on linear terms.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
Design Patterns for Multiphysics Modeling in Fortran 2003 and C++ • 3:23
4. DISCUSSION
Having covered the consequences of the new patterns in Section 3, this
section turns to the similarities and differences between their expression
in Fortran and C++. In particular, it addresses some of the implementation
differences necessitated by language constructs and design aspects of the two
programming languages.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
3:24 • D. W. I. Rouson et al.
ensures state can be used only to allocate or access the elements of the array
state. Second, the language standard obligates the compiler to free any memory
subsequently allocated to state. The compiler must do so after state goes out of
scope even if the programmer does not write a final procedure (C++ destructor).
Third, even the initial allocation of state can be automatic if its first assignment
contains a RHS expression that yields an array of the desired size, in which case
the compiler allocates the amount of memory required to store the result. For
illustrative purposes, the online Appendix A code contains many of the implicit
allocations in comments to demonstrate where a C++ or Fortran 95 programmer
would be required to insert such allocations. Finally, Fortran 2003 allocatable
entities can also be scalars and objects. For the objects in online Appendix
A, the programs explicitly perform all allocations. The compiler handles all
deallocations in online Appendices A.1 and A.2. We discuss online Appendix
A.3 next
Despite at least 75 implicit and explicit memory allocations in roughly 1100
lines of Fortran (discounting blanks), no explicit deallocations occur in all of
online Appendix A. In addition to the automatic deallocations performed by
the compiler, careful use of the Fortran 2003 move alloc intrinsic procedure
facilitates the elimination of temporary objects for storing results and the at-
tendant deallocations such temporaries necessitate. As stated by Metcalf et al.
[2004]:
4.4 Scoping
Fortran’s module construct encapsulates each ADT in online Appendix A. Mod-
ules separate sundry entities—including variables, named constants, derived
type definitions, procedures, and procedure interfaces—into a scope apart from
other like entities outside the module. This capability most closely resembles
the C++ namespace. Since Fortran has no concept of file scope, modules pro-
vide the means to make entities available across multiple program units. (The
venerable old common block widely used in Fortran 77 supplies another means
but only for data and even that use has been deprecated in favor of the newer
module construct [Metcalf et al. 2004].)
Modules also have characteristics that distinguish them from namespaces.
For example, modules are closed to extension via multiple declarations. More
significantly, modules provide data protections in that the Fortran keyword
private can be applied only to entities inside a module. Doing so only affects code
outside the module in which private appears, whereas the entities declared
private remain available to all procedures inside the module, not just type-
bound procedures. C++ achieves similar data protection at the class level,
but only the member functions and friends can access private data. Thus, the
Fortran module provides protection in a more coarse-grained scope (as if at the
level of a namespace) than a C++ class.
4.5 Complexity
As mentioned, design patterns aim to produced loosely coupled yet cohesive
ADTs. Cohesion connotes a commonality of purpose among an individual ADT’s
procedures. In their seminal treatment of the subject, Stevens et al. [1974]
ranked “coincidental” cohesion as the weakest form and “functional” cohesion
as the strongest form. Coincidental cohesion implies no significant relation-
ship between the procedures. Functional cohesion implies that each procedure
contributes to a single task. Rouson [2008] pointed out that the Semi-Discrete
pattern proposed in this article imposes functional cohesion on any types that
extended the integrable model type at least when these extended types im-
plement only the abstract interfaces referenced in the deferred bindings of the
integrable model. In that case, each procedure contributes to the time advance-
ment expression evaluation and assignment. Furthermore, multiphysics mod-
els of the type described in Figure 6 propagate this functional cohesion down
the ADT hierarchy as the Mixture puppeteer delegates the defined operations
and assignment in integrable model to its puppets. In a similar manner, each
puppet that uses the Field class in Figure 6 imposes a high degree of functional
cohesion on it by writing various field expressions (e.g., scalar field products
and vector field divergences) that necessitate the implementation of defined
operators and assignments in the Field template and the basis-function ADTs
it employs.
Many traditional, procedural mathematical libraries, while very useful, lack
functional cohesion. A similar situation would result if we included all desired
integration procedures in the integrable model parent type rather than sep-
arating them into a strategy class hierarchy. Each procedure would be used
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
Design Patterns for Multiphysics Modeling in Fortran 2003 and C++ • 3:27
separately and, most likely, independently from the others. In such situations,
greater clarity results from separating the implementations.
While cohesion is essentially qualitative, coupling is more easily quantified.
Following Martin [2002], we define an ADT’s afferent couplings (Ca) as the
number of other ADTs that depend on it, while its efferent couplings (Ce) are
the number of ADTs on which it depends. Its instability
Ce
I≡ (14)
Ce + Ca
vanishes when changes to other parts of the software do not impact the ADT in
question (a completely stable situation) and approaches unity when changes to
any other ADT can potentially affect the one in question (a completely unstable
situation). In any multiphysics package employing the Semi-Discrete pattern,
the integrable model abstract type would be highly stable because it depends
on no other ADTs (Ce = 0) and the associated integrate procedure depends
only on the dynamical system being integrated, which will typically be a single
Puppeteer in a multiphysics simulation.
Examining Figure 6 suggests that the Puppeteer (Mixture) depends on the
integrable model type (it must implement the defined assignments and oper-
ators specified by the integrable model) along with each of the single-physics
ADTs. Thus, Ce = 6 in the case shown. Importantly, no ADTs depend on the
Puppeteer, although the integrate procedure accepts it as an argument, so Ca
= 1 and I = 6/7. This highlights one of the strongest arguments for the Pup-
peteer design pattern: it takes what in many scientific software projects proves
to be the least stable activity (the process of coupling separately developed
single-physics packages into a multiphysics whole) and turns it into the most
stable part of the entire enterprise. Similar observations can be made about
the rest of Figure 6. Few classes depend on more than one other class and some
depend on none (e.g., Tangle and Cloud). This leads to a highly stable design in
which I approaches 1 throughout most of the software.
5. CONCLUSIONS
We have presented UML class models for three new object-oriented software
design patterns. We further expressed the patterns in Fortran and C++ imple-
mentations. The new patterns integrate coupled sets of differential equations
and facilitate the flexible swapping of physical and numerical software abstrac-
tions at compile-time and runtime. The Semi-Discrete pattern supports the
time advancement of a dynamical system encapsulated in a single abstract data
type. The Puppeteer pattern combines multiple abstractions into a multiphysics
package, mediates interabstraction communications, and enables implicit time
integration even when nonlinear terms couple separate abstractions contain-
ing private data. The Surrogate pattern emulates C++ forward references in
Fortran 2003. Online Appendices A and B provide code demonstrations corre-
sponding to each pattern applied to the Lorenz dynamical system.
We provided architectural descriptions of how we have used the new de-
sign patterns in extending the Navier-Stokes solver of Rouson et al. [2008a]
to simulate three multiphysics problems: quantum vortices interacting with
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
3:28 • D. W. I. Rouson et al.
normal fluid, electromagnetic fields interacting with conducting fluids and plas-
mas, and droplets interacting with the atmospheric boundary layer. We also
described the relationships between the new patterns and two previously de-
veloped architectural elements: the Strategy pattern of Gamma et al. [1995]
and the template class emulation technique of Akin [2003].
The patterns and resulting software abstractions presented in this article
greatly ease the development of multiphysics applications by reducing and man-
aging the associated complexity. Most of the patterns are language agnostic—
provided that the target language provides basic facilities for memory man-
agement and dynamic typing—and can easily be tailored to leverage advanced
language features for automatic memory management and expression seman-
tics. This article has focused primarily on a simple demonstration problem,
but the real strength of the patterns lies in their managing the design, de-
velopment, and maintenance of complex multiphysics or multiscale simulation
systems.
ACKNOWLEDGMENTS
The first author acknowledges the support of Sameer Shende in the form of
computer time in the Department of Computer Science at the University of
Oregon as well as the technical assistance of Brandon Davidson and Xiaofeng
Xu in maintaining and testing the IBM XLF compiler installation.
REFERENCES
AKIN, E. 2003. Object-Oriented Programming via Fortran 90/95. Cambridge University Press,
Cambridge, U.K.
ALEXANDER, C., ISHIKAWA, S., MURRAY, S., JACOBSON, M., FIKSDAHL-KING, I., AND ANGEL S. 1977. A
Pattern Language: Towns, Buildings, Construction. Oxford University Press, Oxford, U.K.
BALAY, S., BUSCHELMAN, K., EIJKHOUT, V., GROPP, W., KAUSHIK, D., KNEPLEY, M., MCINNES, L. C., SMITH,
B., AND ZHANG, H. 2007. PETSc Users Manual, ANL-95/11–Rev. 2.3.3. Argonne National Lab-
oratory, Argonne, IL.
BARKER, V. A., BLACKFORD, L. S., DONGARRA, J., DU CROZ, J., HAMMARLING, S., MARINOVA, M., WANIEWSKY,
J., AND YALAMOV, P. 2001. LAPACK95 Users’ Guide. Society for Industrial and Applied Mathe-
matics, Philadelphia, PA.
BERNHOLDT, D. E., ALLAN, B. A., ARMSTRONG, R., BERTRAND, F., CHIU, K., DAHLGREN, T. L., DAMEVSKI, K.,
ELWASIF, W. R., EPPERLY, T. G. W., GOVINDARAJU, M., KATZ, D. S., KOHL, J. A., KIRSHNAN, M., KUMFERT,
G., LARSON, J. W., LEFANTZI, S., LEWIS, M. J., MALONY, A. D., MCINNES, L. C., NIEPLOCHA, J., NORRIS, B.,
PARKER, S. G. M, RAY, J., SHENDE, S., WINDUS, T. L. AND ZHOU, S. 2006. A component architecture
for high-performance scientific computing. Int. J. High Perform. Comput. Appl. 20, 163–202.
BLACKFORD, L. S., DEMMEL, J., DONGARRA, J., DUFF, I., HAMMARLING, S., HENRY, G., HEROUX, M., KAUFMAN,
L., LUMSDAINE, A., PETITET, A., POZO, R., REMINGTON, K., WHALEY, R. C. 2002. An updated set of
basic linear algebra subprograms (BLAS). ACM Trans. Math. Soft., 28, 2, 135–151.
BLACKFORD, L. S., CHOI, J., CLEARY, A., D’AZEVEDO, E., DEMMEL, J., DHILLON, I., DONGARRA, J., HAMMAR-
LING, S., HENRY, G., PETITET, A., STANLEY, K., WALKER, D., AND WHALEY, R. C. 1997. ScaLAPACK
Users’ Guide. Society for Industrial and Applied Mathematics, Philadelphia, PA.
BLILIE, C. 2002. Patterns in scientific software: An introduction. Comput. Sci. Eng., 4, 3, 48–52.
BOOCH, G., RUMBAUGH, J., AND JACOBSON, I. 1999. The Unified Modeling Language User Guide,
Addison-Wesley, Reading, MA.
BRUCKER, K. A., ISAZA, J. C., VAITHIANATHAN, T., AND COLLINS, L. R. 2007. Efficient algorithm for
simulating homogeneous turbulent shear flow without remeshing. J. Comput. Phys. 225, 20–32.
COLLINS-SUSSMAN, B., FITZPATRICK, B. W., AND PILATO, C. M. 2004. Version Control with Subversion,
O’Reilly & Associates, Sebastopol, CA.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
Design Patterns for Multiphysics Modeling in Fortran 2003 and C++ • 3:29
DECYK, V. K., NORTON, C. D., AND SZYMANSKI, B. K. 1997a. Expressing object-oriented concepts in
Fortran 90. ACM Fortran For. 15, 13–18.
DECYK, V. K., NORTON, C. D., AND SZYMANSKI, B. K. 1997b. How to express C++ concepts in Fortran
90. Sci. Program. 6, 363–390.
DECYK, V. K., NORTON, C. D., AND SZYMANSKI, B. K. 1998. How to support inheritance and run-time
polymorphism in Fortran 90. Comput. Phys. Commun. 115, 9–17.
DECYK, V. K. AND GARDNER, H. J. 2007. A factory pattern in Fortran 95. In Lecture Notes in
Computer Science, 4487/2007, 583-590, Springer Berlin/Heidelberg.
DECYK, V. K. AND GARDNER, H. J. 2008. Design patterns in Fortran 90/95. Comput. Phys. Commun.
In press.
FREE SOFTWARE FOUNDATION. 2004a. Gnu concurrent version system home page.
http://www.gnu.org/software/cvs.
FREE SOFTWARE FOUNDATION. 2004b. Gnu mailman home page.
http://www.gnu.org/software/mailman/mailman.html.
GAMMA, E., HELM, R., JOHNSON, R., AND VLISSIDES, J. 1995. Design Patterns: Elements of Reusable
Object-Oriented Software, Addison-Wesley, Reading, MA.
GARDNER, H. AND MANDUCHI, G. 2007. Design Patterns for e-Science. Springer, Berlin, Germany.
GRANT, P. W., HAVERAAEN, M., AND WEBSTER, M. F. 2000. Coordinate free programming of compu-
tational fluid dynamics problems. Sci. Program. 8, 211–230.
HEROUX, M. A., BARTLETT, R. A., HOWLE, V. E., HOEKSTRA, R. J., HU, J. J., KOLDA, T. G., LEHOUCQ, R.
B., LONG, K. R., PAWLOWSKI, R. P., PHIPPS, E. T., SALINGER, A. G., THORNQUIST, H. K., TUMINARO, R.
S., WILLENBRING, J. M., WILLIAMS, A., STANLEY, K. S. 2005. An overview of the Trilinos project.
ACM Trans. Math. Soft. 31, 3, 397–423.
HILL, C., DELUCA, C., BALAJI, V., SUAREZ, M., AND DA SILVA, A. 2004. The architecture of the Earth
Systems Modeling Framework. Comput. Sci. Eng. 6, 1, 18–28.
JOY, W. AND KENNEDY, K. CHAIRS. 1999. Information technology research: Investing in our fu-
ture. President’s Information Technology Advisory Committee Report. Cited in Oden [2006].
www.nited.gov/pitae/report/pitae report.pdf.
KIM, J. R., MOSER, D., AND MOIN, P. 1987. Turbulence statistics in fully developed channel flow at
low Reynolds number. J. Fluid Mech. 177, 133.
KIRK, S. R. AND JENKINS, S. 2004. Information theory-based software metrics and obfuscation. J.
Syst. Softw. 72, 179–186.
KNAEPEN, B., KASSINOS, S. C., AND CARATI, D. 2004. Magnetohydrodynamic turbulence at moderate
magnetic Reynolds number. J. Fluid Mech. 513, 199–220.
LORENZ, E. N. 1963. Deterministic nonperiodic flow. J. Atmos. Sci. 20, 2, 130– 141.
MARKUS, A. 2006. Design patterns and Fortran 90/95. ACM Fort. For. 26, 1, April.
MARTIN, R. C. 2002. Agile Software Development, Principles, Patterns and Practices. Prentice-
Hall, Englewood Cliffs, NJ. Cited in Kirk and Jenkins [2004].
MAWLAWSKI, M., DAWID, K. AND SUNDARAM, V. 2005. MOCCA—towards a distributed CCA frame-
work for metacomputing. In Proceedings of the 19th IEEE International Parallel and Distributed
Processing Symposium (IPDPS). IEEE Computer Society, Los Alamitos, CA.
MATTSON, T. G., SANDERS, B. A., AND MASSINGILL, B. L. 2004. Patterns for Parallel Programming.
Addison-Wesley, Reading, MA. 25, 1, 13–29.
MCGRATTAN, K., BRYAN, K., HOSTIKKA, S. AND FLOYD, J. 2008. Fire dynamics simulator (version 5)
user’s guide. NIST Special Publication 1019-5. National Institute of Standards and Technology,
Gaithersburg, MD.
METCALF, M., REID, J., AND COHEN, M. 2004. Fortran 95/2003 Explained. Oxford University Press,
Oxford, U.K.
MORRIS, K., KOPLIK, J., AND ROUSON, D. W. I. 2008. Vortex locking in direct numerical simulations
of quantum turbulence. Phys. Rev. Lett. 101, 015301.
ODEN, J. T. (CHAIR). 2006. Revolutionizing engineering science through simulation. Report of
the National Science Foundation Blue Ribbon Panel on Simulation-Based Engineering Science.
National Science Foundation, Arlington, VA.
ORSZAG, S. A. AND PATTERSON, G. S. 1972. Numerical simulation of three-dimensional homogeneous
isotropic turbulence. Phys. Rev. Lett. 28, 2.
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.
3:30 • D. W. I. Rouson et al.
ROUSON, D. W. I. 2008. Toward analysis-driven scientific software architecture: The case for ab-
stract data type calculus, Sci. Program. 16, 4.
ROUSON, D. W. I. AND HANDLER, R. 2007. Towards a variational multiscale large-eddy simulation
of the atmospheric boundary layer. In Environmental Sciences and Environmental Computing
Vol. III, Envirocomp Institute, Inc., Fremont, CA.
ROUSON, D. W. I., MORRIS, K. AND XU, X. 2005. Dynamic memory de-allocation in Fortran 95/2003
derived type calculus. Sci. Program. 13, 3, 189–203.
ROUSON, D. W. I., ROSENBERG, R., XU, X., MOULITSAS, I., AND KASSINOS, S. C. 2008a. A grid-free
abstraction of the Navier-Stokes equations in Fortran 95/2003. ACM Trans. Math Soft. 34, 1,
Article 2 (Jan.)
ROUSON, D. W. I., KASSINOS, S. C., MOULITSAS, I., SARRIS, I. AND XU, X. 2008b. Dispersed-phase struc-
tural anisotropy in homogeneous magnetohydrodynamic turbulence at low magnetic Reynolds
number. Phys. Fluids 20, 025101 (Feb.)
ROUSON, D. W. I. AND XIONG, Y. 2004. Design metrics in quantum turbulance simulations: How
physics influences software architecture. Sci. Program. 12, 3, 185–186.
ROUSON, D. W. I., XU, X., AND MORRIS, K. 2006. Formal constraints on memory management for
composite overloaded operations. Sci. Program. 14, 1, 27–40.
STEVENS, W. P., MYERS, G. J., AND CONSTANTINE, L. L. 1974. Structured design. IBM Syst. J. 13, 2,
115.
STROUSTRUP, B. 1997. The C++ Programming Language, 3rd ed. Addison-Wesley, Reading, MA.
THE MOZILLA ORGANIZATION. 2004a. Mozilla Bonsai home page.
http://ww.mozilla.org/bonsai.html.
THE MOZILLA ORGANIZATION. 2004b. Mozilla Bugzilla home page. http://ww.mozilla.org
/projects/bonsai.
ZHANG, K., DAMEVSKI, K., VENKATACHALAPATHY, V., AND PARKER, S. G. 2004. SCIRun2: A CCA frame-
work for high-performance computing. In Proceedings of the 9th International Workshop on High-
Level Parallel Programming Models and Supportive Environments (HIPS ’04). C. Rasmussen,
Workshop Chair. 72–79.
Received March 2008; revised October 2008, March 2009; accepted March 2009
ACM Transactions on Mathematical Software, Vol. 37, No. 1, Article 3, Publication date: January 2010.