Extending Saiph to simulate fluid mechanics and chemistry problems
Abstract
Saiph is a domain specific language for solving partial differential equations in high performance computing systems, developed at the Barcelona Computing Center. The aim of this project is to extend this language to support fluid mechanics and chemistry problems.
Full text
Universitat Politècnica de Catalunya (UPC) - BarcelonaTech Facultat d’Informàtica de Barcelona (FIB) Final Master Thesis (FMT) 2015-2016 |Autumn Semester Master in Innovation and Research in Informatics (MIRI) High Performance Computing (HPC) Extending SAIPH Simulating fluid mechanics and chemistry problems Sandra Macià Sorrosal ([email protected]) Director: Vicenç Beltran Querol ([email protected]) Co-director: Eduard Ayguadé Parra ([email protected]) Computer Architecture Department (DAC)
”Well, Mr. Frankel, who started this program, began to suffer from the computer disease that anybody who works with computers now knows about. It’s a very serious disease and it interferes completely with the work. The trouble with computers is you *play* with them. They are so wonderful. You have these switches - if it’s an even number you do this, if it’s an odd number you do that - and pretty soon you can do more and more elaborate things if you are clever enough, on one machine. After a while the whole system broke down. Frankel wasn’t paying any attention; he wasn’t supervising anybody. The system was going very, very slowly - while he was sitting in a room figuring out how to make one tabulator automatically print arc-tangent X, and then it would start and it would print columns and then bitsi, bitsi, bitsi, and calculate the arc-tangent automatically by integrating as it went along and make a whole table in one operation. Absolutely useless. We *had* tables of arctangents. But if you’ve ever worked with computers, you understand the disease - the *delight* in being able to see how much you can do. But he got the disease for the first time, the poor fellow who invented the thing.” – Richard Feynman, Surely You’re Joking, Mr. Feynman!: Adventures of a Curious Character
Acknowledgments I would like to thank my supervisor Vicen¸c Beltran for the useful comments, remarks and engagement through the learning process of this master thesis and for giving me the opportunity to work on this exciting and engaging project. Many thanks also to Sergi and Alejandro for introducing me to the topic as well as for the great support you gave me on the way. To BSC’s CASE department, specially to Daniel Mira for helping me on the theoretical scientific view of the project. In general, thanks to all my colleagues at BSC. Special thanks to Marc for being always there, believing in me more than I do. You still keep surprising me with your physicist and global view advices. Last but not least, I want to thank my family and friends to make this work possible. iii
Extending Saiph: Simulating fluid mechanics and chemistry problems Sandra Maci`a Sorrosal Computer Architecture Department (DAC) Universitat Polit`ecnica de Catalunya (UPC) 2016 ABSTRACT Nowadays, High-Performance Computing (HPC) is assuming an increasingly central role in scientific research. It is becoming frequent to see scientists working in supercomputing environments while computer architectures are becoming more and more heterogeneous and complex with different parallel programming models and techniques. Under this scenario, the only way to successfully exploit an HPC system requires that computer and domain scientists work closely towards producing applications to solve domain problems, ensuring productivity and performance at the same time. Facing such purpose, Saiph is a Domain Specific Language (DSL) designed to ease the task of simulating complex Partial Differential Equation systems (PDEs) that model real physical phenomena, freeing the users from numerical methods and high-performance complexities. This project aims to extend Saiph to support fluid mechanics and chemistry -combustion- simulations, two domains with a high interest within the scientific community. Driven by use-cases requirements, extensions have been performed at different levels of abstraction. New user-functionalities, suitable numerical methods and specific domain optimizations have been added leading to validated simulation results of the selected use-cases, obtained through the parallel execution of such Saiph applications. Keywords: HPC, DSL, PDEs, Fluids, Combustion, Scala, Compilers, Parallelism. iv
Table of Contents 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Motivation................................... 1 1.2 Objectives................................... 2 1.2.1 DetailedObjectives.......................... 3 1.3 Context .................................... 3 1.4 Documentstructure.............................. 3 2 State of the art . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.1 Liszt...................................... 5 2.2 FEniCS .................................... 6 3 Saiph overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.1 Saiphdesign.................................. 7 3.2 Underlyingtechnology ............................ 8 3.2.1 Scala.................................. 9 3.2.2 Lightweight Modular Staging . . . . . . . . . . . . . . . . . . . . 10 3.2.3 Scala-virtualized compiler . . . . . . . . . . . . . . . . . . . . . . 10 3.3 Saiphasalanguage.............................. 11 3.3.1 Units.................................. 11 3.3.2 Cartesianmeshes ........................... 14 3.3.3 Terms ................................. 15 3.3.4 Operators ............................... 16 3.3.5 Equations ............................... 20 v
3.3.6 Boundary conditions . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.3.7 Pointsources ............................. 24 3.3.8 Problem................................ 25 3.4 Saiph’s internal features . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 3.4.1 Numericalmethods.......................... 27 3.4.2 Domain specific optimizations . . . . . . . . . . . . . . . . . . . . 29 3.4.3 Exploiting parallelism . . . . . . . . . . . . . . . . . . . . . . . . 30 4 Fluid mechanics and chemistry theory . . . . . . . . . . . . . . . . . . 33 4.1 Governingequations ............................. 33 4.2 Dissecting the equations . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 4.2.1 Meaningofterms........................... 35 4.2.2 Operators involved . . . . . . . . . . . . . . . . . . . . . . . . . . 37 4.2.3 Vectorequations ........................... 41 4.2.4 Non-derivative equation . . . . . . . . . . . . . . . . . . . . . . . 42 4.2.5 Coupledsystem............................ 42 5 Tools and methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 5.1 Tools...................................... 45 5.2 Methodology ................................. 45 5.2.1 Scientific method design . . . . . . . . . . . . . . . . . . . . . . . 46 5.2.2 Development strategy . . . . . . . . . . . . . . . . . . . . . . . . . 46 6 Extending Saiph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 6.1 Newfunctionalities .............................. 47 6.1.1 Vectorequations ........................... 47 6.1.2 Non-derivative equations . . . . . . . . . . . . . . . . . . . . . . . 49 6.1.3 Coupledscheme............................ 50 6.1.4 Operations over vector of Units . . . . . . . . . . . . . . . . . . . 52 6.1.5 Otheroperators............................ 53 6.2 Optimizations................................. 54 vi
6.2.1 Stabilizedgradient .......................... 54 6.2.2 Nestedderivatives........................... 56 7 Results and evaluations . . . . . . . . . . . . . . . . . . . . . . . . . . 60 7.1 Fluid mechanics and chemistry use-cases . . . . . . . . . . . . . . . . . . 60 7.1.1 Convection .............................. 60 7.1.2 Sod’sshocktube ........................... 64 7.1.3 Results and validation . . . . . . . . . . . . . . . . . . . . . . . . 69 7.1.4 Autoignition delay time . . . . . . . . . . . . . . . . . . . . . . . 70 7.1.5 Premixed laminar flame . . . . . . . . . . . . . . . . . . . . . . . 78 7.1.6 Results and validation . . . . . . . . . . . . . . . . . . . . . . . . 85 7.1.7 Nomenclature, units and constants . . . . . . . . . . . . . . . . . 87 7.2 Parallel execution analysis . . . . . . . . . . . . . . . . . . . . . . . . . . 90 7.2.1 Platform................................ 90 7.2.2 ExperimentalSetup.......................... 91 7.2.3 Scalability Results . . . . . . . . . . . . . . . . . . . . . . . . . . 91 8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 9 Conclusions and future work . . . . . . . . . . . . . . . . . . . . . . . 94 A Scala . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 B Lightweight Modular Staging . . . . . . . . . . . . . . . . . . . . . . . 97 C Premixed laminar flame; Saiph complete code . . . . . . . . . . . . . 101 Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 vii
1|Introduction Today, synergy is one of the most important requirements for research and scientific advances. In any domain, it is necessary to work closely with different domain experts with different backgrounds and views but ideally binding them in its own domain of expertise. For such purpose, Domain Specific Languages (DSLs) are becoming a popular approach. Ideally, domain experts would just need to specify their problems unambiguously, with all the details required to formalize the whole simulation description and the domainspecific compiler would handle the details related to the domain specific problem and the high-performance execution in a supercomputer. And that is exactly what Saiph is meant for; Saiph is a Domain Specific Language being developed at the Barcelona Supercomputing Center (BSC) for simulating physical phenomena modeled by complex Partial Differential Equations (PDE) systems. Saiph eases the development of scientist applications by allowing domain experts to transcribe their equations into Saiph code and then generating HPC-ready code that efficiently exploits the computational resources of modern heterogeneous supercomputers while dealing with all the specific aspects of solving partial differential equations systems. 1.1 Motivation In supercomputing environments, scientists model real-world phenomena using partial differential equation systems. Afterwards, these models are transcribed into a programming language in order to numerically estimate the solutions of the equations via simulation. This scenario requires a strong collaboration between computer experts, numerical methods experts and scientists lighting up the fact that scientist could not perform as computer (or numerical methods) experts and vice versa. Without a strong collaboration, domain experts are forced to leave their domain of expertise and productivity and efficiency start to plummet. Consequently the productivity can be hindered by issues related to domains that are, in fact, adjacent to the scientific domain of the specific research. The Saiph project is motivated by the fact that regarding simulations involved in science, the unavoidable and essential adjacent domains are the computer science domain and the numerical method domain, which are fields of expertise by 1
themselves. Domain Specific Languages could, in general, separate and establish the link between those different but dependent domains, allowing the work to progress in the same direction while each expert working in its own domain of expertise. Saiph, in particular, has been designed for users which are not familiar with PDEs resolution, nor numerical methods neither programming for supercomputers. Saiph is a high-level language with domain specific syntax that provides to the users, numerical correctness, specific domain optimizations and high performance computing. However, Saiph is a tool under development and until this project, it has successfully faced the resolution of few and small systems. The idea behind Saiph is strong and powerful, so Saiph could have a long and exciting trajectory. For this reason, it is important and necessary to validate and use what it has been done until now as well as to extend it to demonstrate its strength to the scientific community. Given the users targeted by the tool, it appears interesting to have a development process driven by real large, complex and popular use-cases with their specific requirements. To this end, it seems wise to choose a specific scientific domain, wide and popular enough to have several use-cases for conducting the development and the extension of Saiph as a specific language of the domain of resolutions and simulations of physical problems written as PDEs systems. 1.2 Objectives The main objective of this project is to make real use of Saiph and to extend it. To this end, we have chosen a wide enough scientific domain able to provide us with real applications of interest to drive the development of our tool. This scientific domain corresponds to fluid mechanics and chemistry. For quite awhile, fluid mechanics and chemistry has been a domain of high interest in the scientific community. As a fact of matter, this domain of expertise can provide us with use-cases as systems of partial differential equations which lead to real, interesting and complex scientific simulations. Moreover, the popularity of the field allows us to be able to validate the obtained results of the simulated systems against other. Thus, the objective is twofold; make real use of Saiph and extend this domain specific language for the resolution of problems related to fluid mechanics and chemistry offering a high level syntax that directly maps with a concept of the domain, hiding from the user all the complexities related to numerical methods, domain specific optimizations and the generation of specific code to be executed in parallel by a supercomputer, distributing the work across several nodes and applying intra-node techniques to achieve a high performance. 2
3.2.1 Scala Scala [7] is a statically typed programming language which unifies and generalizes object oriented and functional programming. It provides a powerful set of mechanisms for composing, abstracting and adapting components. Those mechanisms allow the language to be extensible enough so that users can model their domains writing libraries that are used like they were built-in features provided by the language itself. Scala is thus an attractive language for embedding DSLs. Using Scala and LMS (explained later in this chapter), Saiph is embedded as an internal DSL. Therefore, Saiph applications are actually Scala applications. The most basic concepts, constructions and features of Scala used in Saiph applications are introduced in appendix A. In this section we solely mention an interesting Scala feature used in Saiph to allow domain specific optimizations; pattern matching. Pattern matching One of the functional features that Scala implements is pattern matching. Scala allows the programmer to match values of any type with a match-first policy. However, Scala, as an object-oriented language, extends this concept for objects. This is achieved with a special kind of classes called case classes. The following code illustrates how Function findRoom (line 1) takes a parameter nof type Int. This parameter is pattern-matched against several cases (lines 2-5). If nis equal to one of these values, the corresponding string is returned. Line 5 is the default pattern, which, if reached, it is always executed. 1def findRoom(n: Int): String = n match { 2case 103 => "Lab" 3case 105 => "Dean" 4case 104 => "Secretary" 5case _ => "Empty" 6} As previously mentioned, Scala allows the programmer to pattern-match case classes. The definition of a case class is shown as follows: 1case class Rectangle(x: Int, y: Int, w: Int, h: Int) The only difference between case classes and regular Scala classes is that case classes come by default with a constructor with the same name as the case class. Regular scala classes cannot be pattern-matched. 9
The following code shows how case classes are pattern-matched. 1def assertRectangle(r: Rectangle): String = r match { 2case Rectangle(0, 0, _, _) => // When rectange is at (0,0)... 3// More cases... 4case Rectangle(_, _, w, h) => // Use w and h to... 5} This last code illustrates how case classes can be pattern-matched against values of their members (line 2). Values of case class members can be bound and used (line 4). Case classes act like regular Scala classes in terms of class hierarchies. This means that an instance of a superclass can be matched against instances of case classes implemented as subclasses derived from a given type. 3.2.2 Lightweight Modular Staging LMS [8] is a Scala library for dynamic code generation. Dynamic code generation is inherently more flexible because code can be specialized with respect to parameters only available at runtime. The concept of staging is based on the observation that many computations can naturally be separated into stages distinguished by frequency of execution or availability of information. The staging approach, although introduced initially as a set of compiler transformations, can be thought of as a method for embeddeding domain-specific languages [9]. By means of LMS, the Saiph compiler is embedded as a Scala application, and the Scala code is translated into C++ code when the LMS Scala application is run. LMS is just a library, so a DSL application is compiled together with the DSL implementation, giving place to an executable code generator. Once the code generator is run, the DSL application gets translated. Appendix B shows how to build and use a DSL using the Lightweight Modular Staging as DSL development platform. 3.2.3 Scala-virtualized compiler The Scala-Virtualized compiler [6], offers a set of small extensions to the Scala language to provide even better support for hosting embedded DSLs. LMS allows programmers to stage any kind of computation resulting on an object of a particular type, however, the vanilla Scala compiler does not provide us with staging of control flow constructs such as if-else statements or loops. The functionality of staging control flow is achieved through this extension (Scala-Virtualized compiler). The control flow constructs are 10
compiled down into regular method calls. Thus, Scala-Virtualized extends the idea of virtualizing certain language features by defining them as method calls, so that they can be redefined within the language. Scala-Virtualized redefines most of Scala’s expression sub-language in this way, enabling DSL implementations to give domain-specific meaning to core language constructs. 3.3 Saiph as a language Saiph offers a high level syntax to unambiguously define a complete system of partial differential equations which models a physical phenomena. This system is solved, by Saiph, using finite differences and Euler’s integration methods but those numerical methods are hidden to the user, as well as issues related to the generation of parallel code. It follows a complete description of this new language with the components and constructions needed by the users to describe the complete physical systems and the simulations parameters. 3.3.1 Units Units are unavoidable components of Saiph to force the users to provide the physical dimensions of variables of their system. Saiph internally validates that all operations within equations are valid, avoiding illegal operations such as adding two variables representing different magnitudes. To support this type-checking, Saiph computes the units of each expression: if xis a variable whose unit is Meters, the unit of the expression x∗xis Meters2. Thus, a unit represents a physical magnitude with its dimensionality information. There are seven attributes that indicate the exponent of each fundamental magnitude: Length, Mass, Time, Electric Current, Temperature, Amount of Substance and Luminous intensity. Apart from those seven fundamental units there is the unit Unitless which is used to qualify dimensionless variables, constants or expressions. Despite the fact that is always recommended to specify the real units of the variables, in some specific cases it may be a tedious work. Using this unitless unit as a black box unit type may be helpful in some cases. Aside from avoiding illegal operations, Saiph also keep away from issues related to the system of units used by the user. Internally, the numerical value of each magnitude is stored in the International System of Units, thus, different units can be correctly used and combined to represent the same magnitude. For instance, miles and kilometers can be used as dimensions of length variables, or Kelvins and Celsius degrees for temperatures. Table 3.1 shows the predefined unit’s set for each fundamental physical magnitude. 11
Magnitude Units Length Micrometers, Millimeters, Centimeters, Meters, Kilometers Mass Tons, Kilograms, Grams Time Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes, Hours, Days Electric Current Amperes Temperature Kelvins, Celsius, Fahrenheit Amount Of Substance Moles Luminous Intensity Candelas Table 3.1: Predefined unit’s set for each fundamental physical magnitude Apart from the units in table 3.1, Saiph supports several operators to compare units and combine them to create new ones. The example below shows how to define a new unit using some of these operators and how to use it: // Defining new units def MetersPerSecond = Meters / Seconds def Seconds2 = Seconds * Seconds def MetersPerSecond2 = Meters / Seconds2 // Using a new unit: Gravity of Earth def g = -9.81 * MetersPerSecond2 // Equivalent to def g1 = -9.81 * Meters / Seconds2 // And also equivalent to def g2 = -9.81 * Meters / Seconds / Seconds For the sake of convenience, Saiph has a predefined set of combined units, which is shown in Table 3.2. However, this set is not fixed and it can be extended if needed. 12
Magnitude Units Area Micrometers2, Millimeters2, Centimeters2, Meters2, Kilometers2 Volume Micrometers3, Millimeters3, Decimeters3, Centimeters3, Meters3, Kilometers3 Energy Joules Pressure Pascals, Bars, Atmospheres, Psis Power Watts Speed MetersPerSecond, KmPerHour Table 3.2: Predefined combined unit’s set In order to combine and compare units, there is a specific set of operations between units that is supported by Saiph: •Comparison operators def infix_>(l: Unit, r: Unit) : bool def infix_<(l: Unit, r: Unit) : bool def infix_>=(l: Unit, r: Unit): bool def infix_<=(l: Unit, r: Unit): bool The types of the arguments land rmust match. The result is always a boolean. •Add operator def infix_+(l: Unit, r: Unit) : Unit The type of Units of the arguments land rmust match. The result type is the same as the type of the arguments. •Minus operator def infix_-(l: Unit, r: Unit) : Unit The type of Units of the arguments land rmust match. The result type is the same as the type of the arguments. 13
•Product operator def infix_*(l: Unit, r: Unit) : Unit def infix_*(l: Scalar, r: Unit) : Unit def infix_*(l: Unit, r: Scalar) : Unit The result type is the product of the argument’s types. •Division operator def infix_/(l: Unit, r: Unit) : Unit def infix_/(l: Scalar, r: Unit) : Unit def infix_/(l: Unit, r: Scalar) : Unit The result type is the division of the argument’s types. 3.3.2 Cartesian meshes Saiph works with implicit cartesian meshes. Simulations take place inside a 3D cartesian mesh defined using the following constructor: def Cartesian(xs: Length, ys: Length, zs: Length) : Cartesian Where xs,ys and zs are the respective sizes of each direction X, Y and Z respectively. These sizes should be specified using continuous lengths, that is, the user should model the systems in physical continuous space. The following example shows how to define a cartesian mesh: val mesh = Cartesian(12.5 * Meters, 25.0 * Meters, 37.5 * Meters) Once the mesh has been defined it must be discretized in order to map the physical coordinates to the actual discrete coordinates. This is done by the mandatory operation discretize whose parameters are real values representing the physical spacing between points in each of the dimensions. The following code shows an example on how to define and discretize a mesh: 14
val mesh = Cartesian(12.5 * Meters, 25.0 * Meters, 37.5 * Meters) mesh.discretize(2.5 * Meters, 1.0 * Meters, 2.5 * Meters) In the previous code, the discretized mesh has 6 points in the X axis (origin + 5 points), 26 in the Y axis (origin + 25 points) and 16 in the Z axis (origin + 15 points). 3.3.3 Terms Saiph offers two types of components to represent dimensional constants and variables of the problem being simulated. A Term represents a variable whereas a ConstTerm is used to act for constant values of the problem. The main difference between a Term and aConstTerm is how data is allocated: since ConstTerms are used when the data does not vary over time neither over space, it shares the same data along all the points of the mesh without being modified at any time. On the other hand, a Term privatizes the data for each point of the mesh and this data is conveniently updated. Saiph supports scalar and vector terms, allocating the requested data (a scalar or a vector) for each point of the mesh. The following code shows how to declare a scalar and a vector term: val T1 = Term(Temperature)("Temp1", mesh, 300 * Kelvins) val T2 = Term(Temperature)("Temp2", mesh, Vector(0 * Kelvins, 300 * Kelvins), List("Gas1","Gas2")) In the example above, the two terms defined have magnitude Temperature. The first term T1 is a scalar term whereas T2 is a vectorial one. In this example, terms are initialized uniformly for each point of the mesh, but it is also possible to provide a function over space specifying how the values vary over the point position of the mesh: val T3 = Term(Temperature)("Temp3", mesh, { x => if (x < XSIZE/2) 0 * Kelvins else 300 * Kelvins}) In this last example T3 is initialized depending on the X axis position. Scalar and vector constant terms are also supported. Instead of allocating the requested data for each point of the mesh, a ConstTerm share the same data. As a consequence, aConstTerm do not depend on the mesh and their memory consumption is lower than aTerm. Constant terms can be declared as follows: 15
val T4 = ConstTerm(Temperature)("Temp4", 300 * Kelvins) Because of the nature of a constant term, this component can not be initilized with spatial functions. Both components, Term and ConstTerm are aimed to be combined, through operators, with other ones to build the equation system of the problem. 3.3.4 Operators The operators that can be used to build the equations operate over scalar/vector terms and constant terms. Whenever any of the operators have requirements related to arguments units, Saiph checks the validity of the operation before performing it, and emits an error if units do not match. The operators supported by Saiph are •Add operator This operator defines the + operator over scalars and vectors as follows: x+y ~u +x= (u1, ..., un) + x= (u1+x, ..., un+x) ~u +~v = (u1, ..., un)+(v1, ..., vn)=(u1+v1, ..., un+vn) def infix_+(x: scalar-expr, y: scalar-expr) : scalar-expr def infix_+(u: vector-expr, y: scalar-expr) : vector-expr def infix_+(u: vector-expr, v: vector-expr) : vector-expr For the sake of simplicity, for this operator and the ones following, we do not show the version in which the first argument is a scalar and the second argument is a vector, even though it is supported. •Subtraction operator This operator defines the −operator over scalars and vectors as follows: x−y ~u −x= (u1, ..., un)−x= (u1−x, ..., un−x) ~u −~v = (u1, ..., un)−(v1, ..., vn)=(u1−v1, ..., un−vn) 16
def infix_-(x: scalar-expr, y: scalar-expr) : scalar-expr def infix_-(u: vector-expr, x: scalar-expr) : vector-expr def infix_-(u: vector-expr, v: vector-expr) : vector-expr •Division operator This operator defines the / operator over scalars and vectors as follows: x/y ~u/x = (u1, ..., un)/x = (u1/x, ..., un/x) ~u/~v = (u1, ..., un)/(v1, ..., vn)=(u1/v1, ..., un/vn) def infix_/(x: scalar-expr, y: scalar-expr) : scalar-expr def infix_/(u: vector-expr, x: scalar-expr) : vector-expr def infix_/(u: vector-expr, v: vector-expr) : vector-expr •Product operator This operator defines the ∗operator over scalars and vectors. If the two arguments are vectors, it defines the dot product between them. x∗y ~u ∗x= (u1, ..., un)∗x= (u1∗x, ..., un∗x) ~u ·~v = (u1, ..., un)·(v1, ..., vn) = n X i=1 ui∗vi def infix_*(x: scalar-expr, y: scalar-expr) : scalar-expr def infix_*(u: vector-expr, x: scalar-expr) : vector-expr def infix_*(u: vector-expr, v: vector-expr) : scalar-expr •Unary minus operator This operator defines an unary - operator over scalars and vectors. It changes the sign of a scalar or, in the case of vectors, changes the sign of all their components. −x −~u = (−u1, ..., −un) 17
def infix_-(x: scalar-expr) : scalar-expr def infix_-(u: vector-expr) : vector-expr •Component-wise product operator This operator computes the component-wise product of two vectors of the same length. Note that we need this special operator because we have already defined the ∗operator over two vectors as the dot product. ~u ∗~v = (u1, ..., un)∗(v1, ..., vn)=(u1∗v1, ..., un∗vn) def cwiseprod(u: vector-expr, v: vector-expr) : vector-expr •Exponential function Given a scalar or a vector, this operator computes the exponential function of it. ex e~u =e(u1,...,un)= (eu1, ..., eun) def exp(x: scalar-expr) : scalar-expr def exp(u: vector-expr) : vector-expr Restriction: the argument’s magnitude must be Unitless. •Invert function Given a scalar or a vector, this operator computes the invert function of it. 1/x 1/~u = 1/(u1, ..., un) = (1/u1, ..., 1/un) def invert(x: scalar-expr) : scalar-expr def invert(u: vector-expr) : vector-expr •Sum operator This operator computes the sum of all the components of a vector. X~u =X(u1, ..., un) = n X i=1 ui 18
3.3.8 Problem AProblem represents a complete finite-difference formalized problem, aimed to be solved by Saiph. Defining a problem The following code shows the constructor of a Problem: def Problem(delta_time: Time, num_steps: Float, m: Cartesian)(eqs: Equation*) : Problem Where: •delta_time is the temporal interval between two consecutive simulation steps, that is, the time step value. •num_steps is the total number of steps. The simulated time is thus tsimulation = ∆t∗numsteps •mesh is the cartesian mesh. •eqs are the equations of the system which are going to be solved one by one. Saiph allows the user to declare a problem which is modelled by one or more equations. The user should simply enumerate the equations separating them by a comma. The code below shows an example of how to define a problem called prob which is defined by the system of equations eq1 and eq2. val prob = Problem(DELTA_TIME, N_STEPS, mesh)(eq1, eq2) Solving a problem Once a problem has been defined, it should be solved and results post-processed. The resolution of a PDE system involves an integrative method. Currently Saiph only supports the explicit Euler method which has been implemented as a part of the lowlevel C++ library. On the other hand, the post-process defines how the results of the simulation are sampled and selects the output format. As sampling modes, Saiph offers three different options: 25
•Final state of the system (SamplingMethod.FinalState): The simulation only takes one sample of the system at the end of the simulation. •Snapshoot each xsteps (SamplingMethod.Periodic): This option takes a sample of the system for each xsimulation steps. It allows the user to analyze how the system evolved to its final state and make animations. •Flush every frame to the output (SamplingMethod.Flush): It takes a sample of the system at every simulation step, equivalent to a Sampling- Method.Periodic of one. This mode is the most expensive in terms of space and computing performance but can be suitable for some particular case studies. As output format, Saiph supports the following ones: •VTK images (OuputFormat.VTI), ideal format for visualizing the simulation results with tools like Paraview or Visit. •XDMF + Raw binary files (OuputFormat.Binary), suitable format to numerically analyze the data. •Both VTK and XDMF + Raw (OutputFormat.all). The next code shows how to use the EulerSolver specifying post-process options: def EulerSolver(pro: Problem)(on: String, of: OutputFormat, sm: SamplingFormat, freq: Int = 1 ) Where: •pro is a Problem. •on is the ouput name. •of is the ouput format. •sm is the sampling mode. •freq is the frequence of the sampling method, only valid when sm is Sampling- Method.Periodic. The following code illustrates how to solve the problem prob generating a VTI file for each simulation step. EulerSolver(prob)("myProblem", OutputFormat.VTI, SampingMethod.Flush) 26
3.4 Saiph’s internal features Internal features are completely transparent to the user, which is only concerned about defining the problem and the governing equations. This illustrates again the potential of Saiph as a productivity boosting tool for solving PDEs systems, hiding the end users from the details of numerical methods and generation of parallel code as much as possible. 3.4.1 Numerical methods Numerical solution of problems described by partial differential equations need the use of suitable numerical methods. Moreover, numerical evaluation requires the discretization of continuous functions, models, and equations which are time-space dependent. Thus, time-space discretization is the basis of numerical solutions of PDEs. Discretization in Saiph is accomplished by using finite difference methods. The three continuous spatial dimensions are discretized through the use of Cartesian meshes. Within such meshes, equidistant points are the main entities in which the values of the problem are stored. Each point is identified using the three dimension indexes (i, j, k). Regarding time, the PDE system is solved using the Euler’s method. The temporal evolution of the system is discretized through the use of discrete time steps. At each of those temporal instants, the complete PDE system is solved and results updated. Finite differences In order to obtain numerical approximations of PDEs, Saiph uses the finite difference method. This method is a discretization method based on the approximations performed by using Taylor expansions around a point. The derivative of φ(x) with respect to xcan be defined as ∂φ ∂xx=i=∂φ(xi) ∂x = lim δx→0 φ(xi+δx)−φ(xi) δx = lim δx→0 φ(xi)−φ(xi−δx) δx = lim δx→0 φ(xi+δx)−φ(xi−δx) 2δx 27
In all these expressions the approximation converges to the derivative as δx →0, thus they are equivalent in a continuous sense. If δx is small but finite, we can deduce the three different form of approximations of the derivative ux, forward, backward and central differences: ∂φ ∂x forward x=i≈φi+1 −φi δx ∂φ ∂x backward x=i≈φi−φi−1 δx ∂φ ∂x central x=i≈φi+1 −φi−1 2δx Finite difference method is basically the discrete analog of the derivative. By default, Saiph uses central differences when computing spatial derivatives. Euler’s method The Euler’s method is the most basic explicit method for numerical resolution of a system of partial differential equations with given initial values. It is derived from Taylor expansion and basically approximates the PDE solution through the approximation of the temporal derivative using forward finite differences: From ∂φ ∂t forward t=n≈φn+1 −φn δt the Euler’s method is φn+1 =φn+δt∂φ ∂t n where ∂φ ∂t represents the left-hand side of a partial differential equation expressed as: ∂φ ∂t =f(t, φ) At each time step, f(tn, φn) is evaluated and added to current results φnin order to obtain the next temporal solution φn+1: φn+1 =φn+δtf(tn, φn) This methodology is applied starting from the known initial state φ(t0) = φ0to a final state determined by a fixed temporal progress. When having a second order partial differential equation such as ∂2φ ∂t2=f(t, φ) 28
we approximate the solution through the approximation of the second temporal derivative using central finite differences: From ∂2φ ∂t2 central t=n≈φn+1 −2φn+φn−1 (δt)2 the Euler’s method is then φn+1 = 2φn−φn−1+ (δt)2∂2φ ∂t2n 3.4.2 Domain specific optimizations High order operator discretization In some cases, approximating the value of a derivative using only its direct neighboring points does not yield an accurate result. For that purpose, some derivative operators can be discretized using higher-order stencil schemes that use multiple points in each dimension to minimize the numerical error. This is the case for high-order derivative operators as ∂n ∂tnor ∂n ∂xn. Consequently, those operators imply a higher computational cost of the whole simulation. Saiph automatically detects when a particular equation in a system contains higherorder time derivatives and automatically uses more expensive numerical schemes when required. Convective gradient For numerical reasons, as we are going to see in section 4.2.1, whenever there is a dot product between a vector and a gradient of some magnitude, the gradient should be a convective gradient. This can be easily done inside the Saiph compiler, using Scala’s pattern matching features to identify such case. If that operation takes place, the generated code corresponds to an upwind scheme instead of a regular gradient and dot product chain. Below is the Scala code inside the Saiph compiler that recognizes the pattern and applies the IR node replacement in the application tree: // Dot product of two vectors def vecDot(x: Exp[Vector], y: Exp[Vector]) = (x, y) match { // Replace Grad by StabGrad (upwind gradient) on second argument case (x, Def(Grad(u))) => VecDot(x, StabGrad(u, x)) // Same for the first argument case case (Def(Grad(u)), y) => VecDot(StabGrad(u, y), y) // Otherwise, just compute dot product of x and y case _ => VecDot(x, y) 29
} 3.4.3 Exploiting parallelism For solving a PDE, it is necessary to have access only to current time-step values. To apply a spatial discretization at a certain point, the direct neighboring of the point is required. Under this scenario Saiph offers either inter-node and intra-node parallelization. Inter-node parallelization Inter-node parallelization is achieved through the Message Passing Interface (MPI) [10]. The mesh is partitioned by the last dimension Zand a similar workload is distributed across the available MPI processes. Each process will solve just its part of the mesh for the whole simulation but has to take care of allocating some extra memory for the boundary values since spatial derivatives need some extra data that may does not belong to the current MPI process. Fig. 3.3: MPI mesh partitioning and shared boundaries Computations at each time-step are completely parallel and dependence’s free but, after each of them, each MPI process has to exchange its boundaries with its neighbors in order to correctly update all the values to be used for the spatial derivatives of future computational steps. 30
Intra-node parallelization For the intra-node parallelization, we use OpenMP parallel programming model [11]. At any time, each equation can be integrated in parallel. The current implementation is very simple; by using only one pragma, the three nested loops traversing the mesh are forced to collapse and their iteration spaces are distributed across available OpenMP threads and executed in parallel. There is an implicit barrier at the end of the collapsed loop, so each equation is solved in parallel for all the points of the mesh, one equation after the other. Inter and intra-node parallelism Inter and intra-node parallelism are harmoniously combined. For instance, executing a system of equations composed by two equations eq1 and eq2, with two MPI processes and four OpenMP threads (two threads per MPI process), the execution diagram can be schematized as follows: Fig. 3.4: Inter and intra node parallelism The next figure shows a trace of a time-step of a real execution of a Saiph application modelled by two equations and executed using two MPI processes with two OpenMP threads each. For each MPI process, only the master thread is concerned about the inter-node communications, so in the MPI calls. The trace shows how communications are done, taking into account that each process need to exchange boundary values with two neighbours(1) and of two terms; that is 4 message to send and 4 to receive: (1)By default, the left boundary of the first MPI process corresponds to the right boundary of the last MPI process. 31
Fig. 3.5: MPI +OpenMP snippet execution trace of a complete time-step 32
4|Fluid mechanics and chemistry theory Fluid mechanics is the study of the effects of forces and energy on liquids and gases, so-called fluids. This is a wide domain embracing science, engineering, medicine... with its corresponding large interest within the scientific community. On the other-hand, chemistry, more concretely combustion, produces nowadays around an 85% of the energy we consume, thus, it is also a domain of high interest. Fluid mechanics correspond to the study of flows. Combustion is basically the study of reacting flows, that is flows in which a chemical process takes place: a reactant (fuel) reacts rapidly with oxygen (oxidizer) and gives off heat. During combustion, new chemical substances (products) are created from the fuel and the oxidizer, when the fuel is hydrogen-carbon-based this products include water and carbon dioxide. Problems related to those physical domains can be studied through partial differential equation systems (PDEs). This chapter introduces the governing equations of any fluid mechanics and chemistry problem and dissects those equations in order to understand the theoretical meaning of each of its terms and operators. 4.1 Governing equations The motion of viscous fluid substances is described by the equations of Navier-Stokes. These equations are balance equations coming from applying Newton’s second law to fluid motion. Therefore, to take chemistry into account, the equations to be solved correspond to the compressible Navier-Stokes equations for multi-species reactive flows with constant multicomponent mixture properties. The systems are governed by the transport equations of continuity, momentum, species and energy, and they are closed by the equation of state [12]: •Continuity equation: ∂ρ ∂t +∇ · (ρu)=0 (4.1) 33
•Momentum equation: ∂(ρu) ∂t +∇ · (ρuu) = −∇p+∇ · τ(4.2) •Energy equation: ∂(ρcpT) ∂t +∇ · (ρcpuT) = ˙ωT+∇ · (λ∇T) ∂(ρE+p) ∂t +∇ · (u(ρE +p)) = ˙ωT+∇ · (λ∇T) (4.3) •Mass equation: N species: k= 1...N ∂(ρYk) ∂t +∇ · (ρuYk) = ˙ωk+∇ · λ cp ∇Yk(4.4) •Equation of state: p=ρRoT·PN k Yk Wk p= (γ−1) (ρE)−1 2(ρu)u (4.5) where ρis the density of the fluid, uis the fluid velocity, pis the pressure, Eis the total energy, Tis the temperature, λis the thermal conductivity, Ykthe mass fraction of each specie k,Wkis the molar mass of each specie k,Rois the ideal gas constant, cp is the specific heat capacity at constant pressure and γis the adiabatic gas index.(1) There are different expression for writing this same system of equations depending on the variables involved. As can be seen, the energy equation 4.3 and the equation of state 4.5 are written above using two different ways. Both equations are going to be used choosing the more convenient one, depending on the context. This set of equations represents the complete equation system defining a fluid mechanics and chemistry problem. In order to solve a problem of this type, this system should be solved at each spatial point of the domain and for each time-step of the temporal evolution. 4.2 Dissecting the equations This section correspond to a detailed study and analysis of the PDE system for expressing fluid mechanics and chemistry problems that has been presented in the previous section. The idea is to understand all the terms and operators in a theoretical and also numerical sense. (1)See section 7.1.7 for more details regarding variables, constants and units. 34
which lead to the correct differenciation. 4.2.3 Vector equations There are two vector equations in the system, the momentum equation 4.2 and the mass conservation for each specie 4.4. Those equations seem to be written down as single equations with single unknowns uand Ykrespectively. The velocity vector urepresents actually three unknowns which are the three direction components ux,uyand uzof the vector velocity. Regarding the mass fraction vector, each component represents the mass fraction of an specific chemical specie present in the fluid. Each of those components is an unknown of the system and has its own equation as we can see as follows (2): ∂(ρu) ∂t =−[ρu· ∇u+u∇ · (ρu) + ∇p]⇒ ∂(ρux) ∂t =−[ρu· ∇ux+ux∇ · (ρu) + ∂p ∂x ] ∂(ρuy) ∂t =−[ρu· ∇uy+uy∇ · (ρu) + ∂p ∂y ] ∂(ρuz) ∂t =−[ρu· ∇uz+uz∇ · (ρu) + ∂p ∂z ] The vector mass equation contains as many equations as specie are in the fluid under study. For a typical combustion process we have the following set of mass fraction equations. ∂(ρYk) ∂t =−[(ρu)· ∇Yk+Yk∇ · (ρu)] + ∇ · λ cp ∇Yk ⇒ ∂(ρYCH4) ∂t =−[(ρu)· ∇YCH4+YCH4∇ · (ρu)] + ∇ · λ cp∇YCH4 ∂(ρYO2) ∂t =−[(ρu)· ∇YO2+YO2∇ · (ρu)] + ∇ · λ cp∇YO2 ∂(ρYN2) ∂t =−[(ρu)· ∇YN2+YN2∇ · (ρu)] + ∇ · λ cp∇YN2 ∂(ρYCO2) ∂t =−[(ρu)· ∇YCO2+YCO2∇ · (ρu)] + ∇ · λ cp∇YCO2 ∂(ρYH2O) ∂t =−[(ρu)· ∇YH2O+YH2O∇ · (ρu)] + ∇ · λ cp∇YH2O (2)For the sake of simplicity we neglect the viscous term of the momentum equation 41
As we can see, there are terms on the right-hand side of the equations that depend on the component of the vector unknown at the right-hand side. Vector equations allow to define several equations with a common pattern but that are different in essence. 4.2.4 Non-derivative equation The equation of state 4.5 is a non-derivative equation. This equation gives us the relation between state variables. This is the thermodynamic equation that describes the state of matter under a given set of physical conditions. As a time-independent equation, the left and right-hand sides must match at any time. Because of the nature of this kind of equations, the values of the variables involved should be from the same time-step. The a-temporal relation of the equation of state can be seen as follows: pt=f((ρT)t, Y t k) being tany moment in time and fa function relating both sides of the equation. Those non-derivative equations should obviously be also verified at each space coordinate. 4.2.5 Coupled system As we can see, the Navier-Stokes equations for multi-species reactive flows consist of a time-dependent continuity equation 4.1 for conservation of mass, three time-dependent conservation of momentum equations 4.2, a time-dependent conservation of energy equation 4.3 and Ntime-dependent conservation of mass (for each specie kof the system) equations 4.4. That is (5 + N) partial differential equations. In this system of partial differential equations, there are (6+N) unknown variables: density ρ, pressure p, temperature T(or total energy E), three components of the velocity vector uand Nmass fractions of each specie involved in the reaction. To solve a flow problem, it is necessary to solve all (5 + N) partial differential equations simultaneously using values from previous time-steps; that is why we call this a coupled system of equations. The equation of state 4.5 is actually the closing necessary equation required to solve the system. We have (5 + N) partial differential equations for (6 + N) unknowns. The equation of state relates the pressure, temperature, density and mass fraction of the gas at each time step and thus close the solvable system. Integration scheme At each time step, the unknown variables from the partial differential equations are updated using variables values from previous time-steps. Following the Euler’s method, the 42
variation terms are computed and added to the values of previous time-steps applying the corresponding factors. The integration scheme of the full system can be expressed as follows: ρt+1 =ρt+δt ·f((ρu)t) (ρu)t+1 = (ρu)t+δt ·f((ρu)t, ut, pt) (ρT)t+1 = (ρT)t+δt ·f((ρu)t,(ρYk)t, Tt) (ρYk)t+1 = (ρYk)t+δt ·f((ρu)t,(ρYk)t, Tt) pt+1 =f((ρT)t+1, Y t+1 k) Of course, variables should be updated for each time step before being accessed. As we can appreciate, variables in the right-hand side of the equation of state should be updated for the same time-step at which the left-hand side variable is being computed. This fact forces to define an order of equation resolution. Partial differential equations can be solved simultaneously (no order restriction) on the other hand, time-independent equations (equation of state) should be the last equations to be solved at each time step. At a same time step, values updated through the resolution of partial differential equations are used for the resolution of non-derivative equations. Initial state Within fluid mechanics and chemistry theory, problems are commonly initialized defining different thermodynamic regions in the spatial domain. This fact induces the existence of interfaces between regions, where the variables should have a defined behaviour. Usually, values traverse those interfaces following a linear function. The following graph illustrates the initial profiles of the temperature in a two-regions domain. 43
Fig. 4.2: Initial temperature profile within a domain of two regions and the correspondent interface, at t=0 As we have already said, the equation of state should be verified at each moment in time and this includes the t= 0 time step, that is the initial state. Of course, it should also be verified at any space coordinate since it precisely relates the state variables at each localization of the domain. Consequently, the state variables at the interfaces must follow exactly the same function in order to fulfill the equation of state at each point in the domain at t= 0. 44
5|Tools and methodology This chapter lists the tools used for developing and extending Saiph and reports the development methodology of the project. Bearing in mind that this is a project based on the extension of an already existing tool, Saiph, the tools used for its extension are predefined by its nature; a DSL embedded in Scala with LMS and Scala-virtualized compiler. On the other hand, the concrete methodology of this project has been applied for the first time resulting in a very appropriate and progress drive way of development. 5.1 Tools As already mentioned, the principal tool used has been Saiph as it was before this project presented in chapter 3. Consequently, the main utensils have been all those tools involved in the creation of the DSL. That is, the Scala language, displayed in 3.2.1 intended for being the final basis language for the end-users’ applications; the lightweight modular staging (LMS) shown in 3.2.2 and the scala-virtualized compiler explained in 3.2.3 used for the DSL design as the interfaces between the high level Saiph code and the specific parallel C++ generated code. Because of the design of the DSL, an important part of the development has also been performed at the C++ level, involving all the resources provided by this object-oriented language [13]. Visualization and graphing tools as Paraview [14] and Gnuplot [15] have been used in order to illustrate and validate simulations results and, finally, Extrae [16] and Paraver [17] for the validation of the parallel executions. 5.2 Methodology The research design has been stated as application driven design. The Saiph’s extensions constituting this project have been determined by the requirements encountered on the selected use-cases. Those use-cases have been picked following a certain scientific method design explained below. Once the necessary extensions have been theorized, they have been fulfilled and carried out following a development strategy, also explained as follows. 45
5.2.1 Scientific method design As stated, the objective of the project is to extend Saiph in order to model and solve fluid mechanics and chemistry problems. Thus, the goal is to correctly simulate the use-case enclosing those two scientific domains which is the aforementioned premixed laminar flame. Before dealing with such a complex use-case, simpler ones have been gradually faced. Thus, a gradually development progress has been followed. Those simpler use-cases basically are divided in two main categories, the ones related to fluid mechanics theory and those related to chemistry, more precisely combustion. Within those two categories, the same progressive method has been followed; each use-case contains more equation’s terms than its predecessor. Hence, all the terms explained in section 4.2.1 have been gradually implemented, tested and validated through the adequate choose of the use-cases. Finally, the composition of all those validated terms from the two different scientific domains (fluid mechanics and chemistry) has allowed the correct resolution of the final use-case. In order to be able to progress from the simplest use-case to the more complex one, a validation process is a must. In that sense, use-cases have been selected among others depending on their popularity within the scientific community and the possibility to solve them either analytically or/and empirically. Thus, all the selected use-cases have been validated against results reported by scientific researches, cited in the current document. 5.2.2 Development strategy In a first instance, each necessary extension has been faced at the C++ level, fattening up the C++ library with all those constructions required for the selected use-cases. Then, applications have been programmed in C++, designed to be compiled and correctly executed at this low level of abstraction. After validating simulation results, our embedded compiler based on LMS has been extended in order to support these new extensions. At that point, the optimizations related to the generation of specific IR nodes have been performed. Finally, each use-case has been re-wrote in Saiph language, compiled, executed and validated again. This development method process has been repeated for each of the faced use-cases. 46
6|Extending Saiph The version of Saiph presented in this project has been implemented in order to fulfill the requirements from fluid mechanics and chemistry problems, presented in chapter 4. In the current chapter, the most important extensions are going to be described. Those extensions can be divided in two main categories; First, the new general functionalities which are going to be handled by users at the high-level and second, domain specific optimizations, transparent to the users and very specific for fluids mechanics and chemistry problems. 6.1 New functionalities After analysing all the details necessaries to perform the desired simulations, we present the implementation of the required functionalities. The extensions presented in this section are general Saiph extensions useful to the resolution of any problem expressed in PDEs. 6.1.1 Vector equations In order to allow vector equations, we firstly extend the list-case that the left-hand side expression of an equation can match. That is to allow the lhsexpr to be either a vector term (1) and a time derivative of a vector term, which is also a vector as shown in the example below. (1)lhsexpr being a non-derivative terms is also an extension of this project, see 6.1.2 47
∂u ∂t =∂ux ∂t ,∂uy ∂t ,∂uz ∂t ∂2u ∂t2=∂2ux ∂t2,∂2uy ∂t2,∂2uz ∂t2 with u= (ux, uy, uz) Allowing such left-hand sides, the dimensionality of this part of the equation cannot be assumed any more. Thus, when solving any equation, checking the dimensionality of the lhsexpr has became a must. Whenever this dimensionality is greater than one, the evaluation of the right-hand side is performed for each component of the left-hand side. This process is easily implemented by forcing an iteration over the components of each lhhexpr at each time step and mesh location, during the evaluation an update process. In essence, a vector equation internally represents a set of scalar equations. This set contains as many scalar equations as dimensions of the left-hand side vector. Those changes have been implemented in the C++ library, modifying the code that traverses the mesh to apply Euler’s method at each location for each time step and equation. Before the application of the Euler’s method, the query related to the dimensionality of lhsexpr and the loop iterating on it, have been added in order to force all the scalar equations of the set to be integrated by the Euler’s method. The left-hand side of the equation can be written as a vector, but the right-hand side should remain being evaluated as a scalar. This is achieved through the component operator, a new operator that can be used to select the component of a vector expression with the same index than the component being evaluated at the left-hand side of a vector equation. t.comp (t1 + t2).comp def comp() : scalar In the following Saiph code the use of this operator is illustrated. // Velocity; vector term val u = Term(Speed)("Velocity", mesh, V_INIT, List[Rep[String]]("X","Y" ,"Z")) // Pressure; scalar term 48
val p = Term(Pressure)("Pressure", mesh, INIT_P) // Density; scalar term val rho = Term(Kg_m3)("Density", mesh, INIT_RHO) // Vector equation val eq1 = Equation(dt(u), -(rho / (grad(p)).comp)) Having a vector lhsexpr, through the use of the component operator applied to the vector terms of the rhsexpr, it can be seen that by writing down a single equation eq1, we are actually defining a set of scalar equations: ∂ux ∂t =−1 ρ ∂p ∂x ∂uy ∂t =−1 ρ ∂p ∂y ∂uz ∂t =−1 ρ ∂p ∂z 6.1.2 Non-derivative equations In order to allow non-derivative equations, we also extend the list-case that the left-hand side expression of an equation can match. That is to allow the lhsexpr to be a term. At that point, the left-hand side expression of an equation has to be defined matching one of the following syntax: •lhsexpr is a scalar or vector term: t=rhsexpr •lhsexpr is a first time derivative of a scalar or vector term: dt(t) = rhsexpr •lhsexpr is a second time derivative of a scalar or vector term: dt2(t) = rhsexpr A non-derivative equation does not have to be integrated. Thus, to solve this kind of equations, we should not go through the Euler’s method. Instead, at each point of the mesh, the right-hand side is simply evaluated and assigned to the term at the left-hand side. This is done within the loop traversing the mesh at the update process for each time step. Depending on the equation type (which must be checked for each equation), the Euler’s method is applied or the simple assignation is performed. 49
6.1.3 Coupled scheme At each time step, the unknown variables of the problem are updated through the correct evaluation and manipulation of its associated right-hand side expression. The three equation types allowed and their requirements to be updated are: •PDEs At each time step, the Euler’s method should be applied. –First order PDEs need to access values from the previous time-step in order to update the unknown variable. φn+1 =φn+δt∂φ ∂t n –Second order PDEs need to access values from the two previous time-step in order to update the unknown variable. φn+1 = 2φn−φn−1+ (δt)2∂2φ ∂t2n In any case, the evaluation of the rhsexpr is used to substitute ∂φ ∂t and ∂2φ ∂t2respec- tively and thus, should be evaluated at time step n. That means that the previous time-step values must be accessible when solving PDEs. •Non-derivative equations Those kind of equations need to access values from the current time-step. ϕn+1 =f(φn+1) The evaluation of the already updated rhsexpr is directly used to be assigned to the unknown variable at each time step. That means that the current time-step values must exist and be accessible when solving non-derivative equations. Because Saiph is a domain specific language for solving PDE systems, variables at the right-hand side of an expression refer to values from the previous time-step by default. Hence, in order to access updated values, those values should exist and the specific access should be specified. The existence of the values must be ensured by the users; As explained, the equations are solved in parallel for all the points of the mesh, one after the other. Thus, the order in which the user lists the equations of the problem to be solved, is crucial when facing coupled system problems. Non-derivative equation should be the last equations to be solved at each time-step in order to allow them to access to the most recent updated values. 50
differentiation. When possible, the nesting can also be substituted directly by the corresponding high-order derivative operator ∇2. Those two numerical scenarios are found within fluids and chemistry problems; They correspond to the diffusive term in which the diffusion coefficient can be spatial dependent or not. When the diffusion constant is not spatial-dependent we should use the already existing laplace operator (3.3.4). If not, we need to combine forward and backward derivative schemes. To do so, we have added to the internal spatial derivative function, an argument meant to indicate the derivative scheme to be used for a first order derivative: •0, being the default value, forces the central scheme to be used. •1 forces the forward scheme to be used. •2 forces the backward scheme to be used. When, internally calling the derivative function, it is now possible to specify the derivative scheme to be used. Hence, internal derivative operators (not visible for the users) have been added, for such schemes: •Forward gradient ∇forward =∂forward ∂x ,∂f orward ∂y ,∂f orward ∂z •Backward gradient ∇backward =∂backward ∂x ,∂backward ∂y ,∂backward ∂z •Forward divergence ∇forward·=∂forward ∂x +∂f orward ∂y +∂f orward ∂z •Backward divergence ∇backward·=∂backward ∂x +∂backward ∂y +∂backward ∂z When identifying nested derivatives, those operators should be combined in a correct manner to correctly compute them. Identifying diffusive terms Inside the Saiph compiler, we use Scala’s pattern matching features to identify when the argument of a standard divergence operator is the result of a multiplication, in which one of the arguments is the result of a gradient operation. The latter, is the definition of the diffusive term. Thus, we identify the diffusion phenomena and try to apply optimizations on it; We use pattern matching again to recognize whenever the other argument is a constant expression. In such cases, the generated code corresponds to a product between the constant and a laplacian. If not, we apply the combined derivative scheme to compute nested derivatives. Below is the Scala code inside the Saiph compiler that recognizes the patterns and applies the IR node replacement in the application tree: 57
//Divergence of an expression x def term_div(x: Exp[Term]) = { xmatch { // Diffusive term optimization // The second argument is a gradient case (Def(TermTimes(x1, Def(TermGrad(x2))))) => // Replace nested derivative by second order derivative if (x1 match { case Def(ConstTermNew(_, _, _ , _)) => true case _ => false }) TermTimes(x1, TermLapla(x2)) // Replace central derivatives by combination of forward and backward derivatives else TermDivForward(TermTimes(x1, TermGradBackward(x2))) // The first argument is a gradient case (Def(TermTimes(Def(TermGrad(x1)), x2))) => // Replace nested derivative by second order derivative if (x2 match { case Def(ConstTermNew(_, _, _ , _)) => true case _ => false }) TermTimes(TermLapla(x1), x2) // Replace central derivatives by combination of forward and backward derivatives else TermDivForward(TermTimes(TermGradBackward(x1), x2)) // Otherwise, just compute a standard divergence case _ => TermDiv(x) } } The following figure illustrates in a schematic way the pattern matching driving to the emission of correct (or more adequate) IR nodes in the application tree, when facing a diffusive term. 58
Fig. 6.2: Schematized pattern matching for diffusive term optimizations 59
7|Results and evaluations This chapter is devoted to show the complete use-cases that have been simulated with Saiph and some scalability results of the most expensive application. 7.1 Fluid mechanics and chemistry use-cases The use-cases that have driven the development of Saiph are shown below. We present a complete theoretical definition and translation of the problems, to Saiph applications, for each of the use-cases faced. Results, validation and nomenclature are also reported. Those use-cases put together all the language features shown along this document. 7.1.1 Convection This first application corresponds to the simulation of two different phenomenas and the combination of them. This is not a real use-case, it is only meant to verify the computation of basic fluid terms that are going to be used for the real use-cases and the correct behaviour of the main method’s implementation and optimizations presented above. Background As said, convection is the transport of a fluid, through the combination of advection and diffusion phenomenas. In order to correctly model this combined phenomena, we firstly simulate advection and diffusion separately. After visual validations, we end up simulating the combination of them, the convection. Each of those phenomenas are mathematically translated as follows: •Advection equation ∂T ∂t =−u· ∇T(7.1) 60
•Diffusion equation ∂T ∂t =∇ · (k∇T)(7.2) •Convection equation ∂T ∂t =−u· ∇T+∇ · (k∇T)(7.3) This equations are translated to Saiph as follows: For the advection application: 1val advection = Equation(dt(T), -u*grad(T)) For the diffusion application: 1val difussion = Equation(dt(T), div(k*grad(T))) For the convection application: 1val convection = Equation(dt(T), -u*grad(T) + div(k*grad(T))) Initial and boundary conditions We simulate a small 3D hot cube. The domain is initialized as T(x, y, z, 0) = 300Kfor Xmesh 2−Xcube ≤x, y, z ≥Xmesh 2+Xcube 100Kotherwise This cube is moving along two dimensions(1) by the advection phenomena, due to a constant velocity vector set as u= (1,−1,0). The advection, when present, is forced to be periodic through the periodic boundary condition applied at each direction of the movement. Regarding diffusion, a constant diffusion coefficients khas been used. Those initial and boundary conditions are translated to Saiph as follows: (1)1D or 3D convection can also be simulated. For the sake of illustrative comprehension, we present the two-dimensional. 61
1// Function to initialize the magnitude being transported 2def cube(x: Rep[MUnit], y: Rep[MUnit], z: Rep[MUnit]) = { 3if (x >= CUBEX - EDGE_SIZE && x <= CUBEX + EDGE_SIZE && 4y >= CUBEY - EDGE_SIZE && y <= CUBEY + EDGE_SIZE && 5z >= CUBEZ - EDGE_SIZE && z <= CUBEZ + EDGE_SIZE) HOT_TEMP 6else AMBIENT_TEMP 7} 8... 9// Periodic boundaries 10 mesh.setPeriodic(DirX) 11 mesh.setPeriodic(DirY) 12 13 // Initializing Variables 14 val T = Term(Temperature)("Temperature", mesh, cube _) 15 16 val u = ConstTerm(Speed)("Velocity", V_INIT, List("X","Y","Z")) 17 val k = ConstTerm(M2_s)("Diffusion coeff", DIFFUSION_COEF) Results •Advection Figures in 7.1 show the results of the simulation by different temporal frames. Starting at t= 0 and transporting the cube until it reaches the initial position again. Fig. 7.1: Two-dimensional advection 62
•Diffusion For the diffusion application we show the initial state and a latter one illustrating how temperature is transported only by the diffusion phenomena. Fig. 7.2: Two-dimensional diffusion •Advection & Diffusion Finally, figure 7.3 shows the results from the combination of the advection and the diffusion phenomena.(2) Fig. 7.3: Two-dimensional convection (2)In order to combine, and visually identify advection and diffusion phenomenas, the coefficients and initial values of the convection application have been adequately modified with respect to the ones from advection and diffusion applications. 63
7.1.2 Sod’s shock tube Background This is a use case of a temporal integration scheme based on properties updated at different stages. The problem corresponds to the well known shock tube originally proposed by Sod[20]. It is a transient case that has analytical solution. It consists of a one-dimensional tube, closed at its ends and divided into two equal regions by a thin diaphragm. Each region is filled with the same gas, but with different thermodynamic parameters; the left and right sides of the tube present different density, energy and pressure. The region with the highest pressure is called the driven section of the tube, while the low-pressure part is the working section. The fluid is initially at rest, that is, it has zero initial velocity. It starts to move because of the sudden breakdown of the diaphragm, the discontinuous initial condition of the left and right states entails a shock wave that propagates to both left and right sides. The equations that are being solved correspond to the Euler equations, a particular case of the Navier-Stokes equations for which the viscous forces are neglected. The system is governed by the continuity, momentum and energy transport equations and closed by the equation of state. The problem is assumed to be one-dimensional (1D) and the 1D equations are given by: •Continuity equation: ∂ρ ∂t +∇ · (ρu)=0 ⇒∂ρ ∂t =−∇ · (ρu)(7.4) •Momentum equation: ∂(ρu) ∂t +∇ · (ρuu) = −∇p ⇒∂(ρui) ∂t =−ρu· ∇ui+ui∇ · (ρu) + ∂p ∂xi(7.5) •Energy equation: ∂(ρE) ∂t +∇ · (ρuE) = −∇ · (up) ⇒∂(ρE) ∂t =−[ρu· ∇E+E∇ · (ρu) + u· ∇p+p∇ · u](7.6) 64
•State equation: ⇒p= (γ−1) (ρE)−1 2(ρu)u(7.7) The fluid behaves like an ideal gas, so γis assumed to be constant and equal to γ= 1.4. To control the Mach regimes of this use-case we also compute the Mach number as ⇒Ma =ux c(7.8) where cis the speed of sound in the medium c=sγp ρ The problem contains 4 unknowns: ρ, (ρu), (ρE) and pand has 4 governing equations (Equation 7.4, 7.5, 7.6 and 7.7) which should be solved in the appropriate order. The full system can be expressed as: ρt+1 =ρt+δt ·f((ρu)t) (ρu)t+1 = (ρu)t+δt ·f((ρu)t, ut, pt) (ρE)t+1 = (ρE)t+δt ·f((ρu)t, ut, Et, pt) pt+1 =f((ρE)t+1,(ρu)t+1, ut+1) This governing equations are translated to Saiph as follows: 1 2// Equation 1: Continuity equation 3val density = Equation(dt(rho), -(div(rho_u))) 4 5// Equation 2: Momentum equation (rho*u) 6val mass_flow = Equation(dt(rho_u), -( (u.comp * div(rho_u)) + (rho_u * grad(u.comp)) + (grad(p)).comp)) 7 8// Equation 3: Energy equation (rho * E) 9val rho_energy = Equation(dt(rho_e), -( (e * div(rho_u)) + (rho_u * grad(e)) + (u * grad(p)) + (p * div(u)))) 10 65
11 // Equation 4: State equation (Pressure) 12 val pressure = Equation(p, (gamma - unit) * (rho_e.toff(0) - (cte * rho_u.compWithOffset(0) * u.compWithOffset(0)))) Initial and Boundary conditions The initial state is defined with a diaphragm in the middle of the tube separating the two states. The density, energy and pressure are discontinuous across the diaphragm at t= 0 with values [21]: ρ(x, 0) = 1.0 for x < 1 2xtube 0.125 for x > 1 2xtube , E(x, 0) = 2.5 for x < 1 2xtube 2 for x > 1 2xtube , p(x, 0) = (γ−1)ρ(x, 0)E(x, 0) = 1.0 for x < 1 2xtube 0.1 for x > 1 2xtube 66
Mass fraction ER= 0.8ER= 1.0 YCH40.0445 0.0550 YN20.7328 0.7248 YO20.2227 0.2202 YCO20.0 0.0 YH2O0.0 0.0 Table 7.2: Two initial mass fractions for gas composition at ER = 0.8and ER = 1.0 and different initial temperatures T={1000 K, 1100 K, ...,1900 K, 2000 K} The fluid is supposed to behave as a perfect gas, so the equation of state holds, the density is initialized as ρ=W p RoTwhere Rois the ideal gas constant and W, the molar mass of the mixture is 1 W=Pk Yk Wk. Finally, the pre-exponential factor Afand the activation energy Eaare coefficients depending on the composition of the gas. Simulations have been performed using values from two well-established chemical kinetics mechanisms: Mantel at al. [24] and Li˜n´an et al. [25]: Reference Afm6 mol2sEakJ mol 1-step Mantel et al. (1996) [24] 1.1·1010 167.360 1-step Liñán et al. (2006) [25] 6.9·108132.200 Table 7.3: Reference coefficients for the 1-step chemical mechanism of the CH4+ 2 O2CO2+ 2 H2O reaction Note that the boundary conditions should not influence the solution as this application is restricted to study the temporary evolution of the system. This initial conditions are translated to Saiph as follows: 1// Initial values (with units) 2 3// Constants 4// Ideal gas constant 5def JpMK = Joules / Moles / Kelvins 6def R_VALUE = 8.314462175 * JpMK 7// Activation energy 8def JpMol = Joules / Moles 9def EA_VALUE_MANTEL = -167360 * JpMol 10 def EA_VALUE_LINAN = -132200 * JpMol 11 ... 73
12 13 // Variables 14 // Mass fractions 15 def INIT_Y = Vector(0.0445 * Unitless, 0.7324 * Unitless, 0.2231 * Unitless, 0 * Unitless, 0 * Unitless) 16 // Temperature 17 def INIT_T = 1500 * Kelvins 18 // Pressure 19 def INIT_P = 1 * Atmospheres 20 ... 21 22 // Initialization: 23 24 // Constants 25 val R = ConstTerm(JpMK)("Ideal gas constant", R_VALUE) 26 val Ea = ConstTerm(JpMol)("Activation Energy", EA_VALUE_MANTEL) 27 ... 28 29 // Variables 30 val rho_T = Term(Kg_ms2)("Rho*T", mesh, DENSITY*INIT_T) 31 val rho_Y = Term(Kg_m3)("Rho*Y", mesh, INIT_rho_Y, GAS_NAMES) 32 ... Physical Description Departing from an initial composition and thermal state (p, T)0, the system evolves oxidizing the fuel until either the fuel or oxidizer are totally consumed. The consumption time of reactants is measured for each temperature investigated. As an example, the evolution of the system using the chemical scheme from Mantel et al. (1996) at T = 1500K is shown in figure 7.7. 74
Fig. 7.7: Methane autoignition temporal evolution. Chemical scheme from Mantel et al. (1996) at Tini = 1500Kand chemical composition ER=0.8 Results and validation Developing the tests for the two-schemes and the two compositions, the autoignition delay times of the mixtures under investigation can be obtained for different initial temperatures. The results are shown in figure 7.8 and 7.9. 75
Fig. 7.8: Methane autoignition delay time measurements using Mantel et al. (1996) and Liñán et al. (2006) chemical schemes, with ER = 0.8 76
Fig. 7.9: Methane autoignition delay time measurements using Mantel et al. and Liñán et al. chemical schemes, with ER = 1.0 For this use-case, the results from Holton (2008) [26] are used for comparison. The results, in figure 7.10 indicate an acceptable level of correlation. For clarity purposes simulation results and reference data have been plotted using a logscale in time axis. 77
Fig. 7.10: Methane autoignition delay time measurements (ER = 1.0) plotted alongside reference data (Holton (2008)[26]) 7.1.5 Premixed laminar flame This is the final use-case enclosing fluids mechanics and chemistry domains, stated as the final objective of this project. The premixed laminar flame contains all the theoretical terms seen in Chapter 4 and being progressively validated by the above simpler usecases. The complete Saiph code of this application can been seen in Appendix C. Background The premixed laminar flame is another example use-case of a temporal integration scheme based on properties updated at different stages. The problem to be solved corresponds to a premixed, freely propagating, steady, laminar, flat flame. The system is characterized by a premixed mixture of fuel (CH4) and air entering in the reaction zone of the computational domain, where it reacts chemically releasing energy. The problem is assumed to be one-dimensional (1D); the domain represents a tube in 78
which the dimension of motion is much longer than the vertical and spanwise directions. The initial conditions correspond to a situation of unburnt and burnt conditions separated in the center of the tube. The flame front will be located at this position. Each of these regions is initialized with its corresponding physical conditions: density, velocity, species concentrations, temperature and pressure [27]. The equations being solved correspond to the compressible Navier-Stokes equations for multi-species reactive flows with constant multicomponent mixture properties. In this case, the system is governed by the transport equations of continuity, momentum, species and energy, and it is closed by the equation of state [12]: •Continuity equation: ∂ρ ∂t +∇ · (ρu)=0 ⇒∂ρ ∂t =−∇ · (ρu)(7.11) •Momentum equation: ∂(ρu) ∂t +∇ · (ρuu) = −∇p+∇ · τ where τis the viscous tensor: τ=µ∇u+∇Tu−2 3∇ · u ⇒∂(ρux) ∂t =−ρu· ∇ux+ux∇ · (ρu) + ∂p ∂x+4 3µ∂2ux ∂x2(7.12) •Species equation: N species: k= 1...N ∂(ρYk) ∂t +∇ · (ρuYk) = ˙ωk+∇ · λ cp ∇Yk ⇒∂(ρYk) ∂t =−[(ρu)· ∇Yk+Yk∇ · (ρu)] + ∇ · λ cp ∇Yk+ ˙ωk(7.13) •Temperature equation: ∂(ρcpT) ∂t +∇ · (ρcpuT) = ∇ · (λ∇T) + ˙ωT ⇒∂(ρT) ∂t =1 cp [−cp((ρu)· ∇T+T∇ · (ρu)) + ∇ · (λ∇T) + ˙ωT](7.14) 79
•State equation: p=ρRoT· N X k Yk Wk (7.15) The problem contains (4 + N) unknowns: ρ,ρux,ρT,ρYkand pand has (4 + N) governing equations (Equation 7.11, 7.12, 7.13, 7.14 and 7.15), which should be solved in the appropriate order. The full system can be expressed as: ρt+1 =ρt+δt ·f((ρu)t) (ρu)t+1 = (ρu)t+δt ·f((ρu)t, ut, pt) (ρT)t+1 = (ρT)t+δt ·f((ρu)t,(ρYk)t, Tt) (ρYk)t+1 = (ρYk)t+δt ·f((ρu)t,(ρYk)t, Tt) pt+1 =f((ρT)t+1, Y t+1 k) This governing equations are translated to Saioh language as follows: 1// Equation 1: Continuity equation 2val density = Equation(dt(rho), -div(rho_u)) 3 4// Equation 2: Momentum equation 5val momentum = Equation(dt(rho_u), -((rho_u * grad(u.comp)) + (u.comp * div(rho_u)) + (grad(p)).comp) + (mu_cte * mu * der2(DirX)(u.comp))) 6 7// Auxiliar equations: Species source term & heat release 8// Reaction rate progress 9val Q = Af * exp(Ea / (R*T)) * (rho_Y(0) / MolarMassVector(0)) * ( rho_Y(2) / MolarMassVector(2) * rho_Y(2) / MolarMassVector(2)) 10 11 val omegak = Equation(omega_species_k, (MolarMassVector.comp * nu.comp * Q)) 12 val omegaT = Equation(omega_heat, - (sum(cwiseprod(h, omega_species_k))) ) 13 80
14 // Equation 3: Species equations 15 // Convective & Diffusion term 16 val Yconv = - ((rho_u * grad(Y.comp)) + (Y.comp * div(rho_u))) 17 val Ydiff = div((lambda / cp) * grad(Y.comp)) 18 val rho_species = Equation(dt(rho_Y), Yconv + Ydiff + omega_species_k. comp) 19 20 // Equation 4: Temperature equation 21 // Convective & Diffusion term 22 val Tconv = - (cp * ((rho_u * grad(T)) + (T * div(rho_u)))) 23 val Tdiff = div(lambda * grad(T)) 24 val rho_temperature = Equation(dt(rho_T), (Tconv + Tdiff + omega_heat) / cp) 25 26 // Equation 5: State equation (pressure) 27 val pressure = Equation(p, rho_T.toff(0) * R * sum(Y.toff(0) / MolarMassVector)) Initial and Boundary conditions The initial state is defined with a flame front in the middle of the tube separating the two states: fresh gases or unburnt conditions and products or burnt conditions. The temperature, mass fraction, velocity and density are discontinuous across the flame at t= 0. The pressure is initially constant and equal to the atmospheric pressure. Fig. 7.11: Domain and initial conditions for the one-dimensional premixed flame The initial conditions in the unburnt section correspond to a premixed methane flame at fixed equivalence ratio ER = 0.8 and under constant initial pressure. The burnt conditions are initialized at equilibrium conditions. The chemical reaction: 81
CH4+ 2 O2CO2+ 2 H2O is defined using a 1-step chemical mechanism (Kb= 0). (3) Initial values are: T(x, 0) = 300 K for x < 1 2xUnburnt 2011 K for x > 1 2xBurnt , p(x, 0) = 101325 Pa, Mass fraction Unburnt Burnt YCH40.0445 0.0 YN20.7328 0.7328 YO20.2227 0.0360 YCO20.0 0.1270 YH2O0.0 0.1042 Table 7.4: Initial mass fractions for gas composition at ER = 0.8 (3)See the Autoignition use-case chapter 7.1.4 for more details regarding chemical reactions and its coefficients 82
•Specific heat(6):cp It is assumed constant at: cp= 1012 J kg ·K Units: [cp] = J kg ·K •Specific enthalpy of each specie k:hk Species Specific enthalpy (J/kg) CH4-4666.97834 N20.0 O20.0 CO2-8941.70577 H2O-13423.368 Units: [hk] = J kg •Coefficients of species kfor the reaction: νk ν0 k→Reactants species ν00 k→Products species Units: Adimensional magnitude •Reaction rate constant: Kf Kf=Afe−Ea RT Units: [Kf] = m3(n−1) s·mol(n−1) where nis the order of the reaction. •Reaction rate progress: Q Units: [Q]=[Kf]·mol m3Pkν0 k •Pre-exponential factor: Af Units: [Af] = [Kf] (6)The specific heat is actually function of the concentrations of the species. It is assumed constants in these use-cases 89
•Activation energy: Ea Units: [Ea] = kJ mol 7.2 Parallel execution analysis Finite-difference stencil computations are very common in numerical modeling and they exhibit high degree of data parallelism and regular structure. In this section we analyse the scalability of the application premixed laminar flame setting the following parameters: •Number of steps: 200 time-steps •Temporal discretization factor: 5 ns •Z dimension: 8 cm •X, Y dimensions: 100 µm •Spatial discretization factor: 20 µm •Total number of spatial points: 1 ·105 7.2.1 Platform We describe here the hardware used to collect real performance data on the Saiph application. The platform used is Marenostrum III cluster, comprised (among others resources) of: •3108 IBM dx360 M4 compute nodes. •Every IBM dx360 M4 node has: –2x E5-2670 SandyBridge-EP 2.6HHz cahce 20MB 8-core –32GB of RAM The networks that interconnect the cluster using 296 switches are: •Infiniband Network: High bandwidth network used by parallel applications communications (MPI).l’ •Gigabit Network: 10GbitEthernet network used by the GPFS Filesystem. The results that follow are intrinsically subjected to this architecture. 90
7.2.2 Experimental Setup In order to start the evaluation, we first of all, install the application in the Marenostrum cluster. Saiph applications allow sequential and parallel (MPI and/or OpenMP) executions. To create the desired executable, we use a Makefile for configuring the compilers, linkers, and their command line flags. Finally, in order to submit jobs we have created scripts according to the requirements of the machine. Inside those scripts we can finally tune the number of nodes and/or threads we want to use for the execution. At that point, we want to test if Saiph applications can be advantageously executed in a distributed environment. Because Saiph still lacks on efforts devoted to increase performance, we only present results from inter-node parallel executions. For a good use of the resources, we bind 1 MPI process per core resulting in 16 MPI processes per node. As said, OpenMP parallelism is not set. 7.2.3 Scalability Results The complete sequential execution took around 28 min to finish. On the other hand, the most resource-consuming execution tested (160 MPI processes), took less than 12 s. The following figure shows the execution times and Speed up of several parallel executions taking the sequential one as reference. Fig. 7.16: Scalability plot for the Saiph application premixed laminar flame. Linear speed up is reached up to 10 nodes, which corresponds to 160 MPI processes. 91
8|Summary The computational modelling of any physical problem is composed by three important steps: (1) the problem definition, (2) the mathematical model and (3) the computer simulation. Saiph has been extended in this project in order to ease the whole modelling process for those physical problems related to fluid mechanics and chemistry theory. The problem definition, being the first natural step, is devoted to define the problem of interest in terms of a set of relevant quantities. Initial and boundary conditions are thus defined at that point. For this first step, Saiph provides an easy way to define and initialize variables and constants of the problem. Through the use of Terms,ConstTerms and units constructions users can unambiguously define their problems. Regarding initialization, Saiph offers the possibility to set variable values through spatial-dependent functions and a large set of operations over units, allowing mathematical relations between sets of dependent variables. In particular, Saiph provides intuitive constructions to well-define a spatial discontinuity over the physical domain ensuring a proper behaviour of linked variables at the interfaces. Although the domain expert is in charge of this first stage, Saiph put at his disposal a scientific high-level syntax to allow him to define the problem by directly translating his on-paper physical problem definition. The second step of the modeling process is to represent the physical reality by a mathematical model: the governing equations of the problem. This task also belongs to the domain expert, but again, Saiph allows the direct and intuitive translation of the governing equations into Saiph’ equations. Our tool, permit to express vector equations, partial differential equations (first and second order) and non-derivative equations commonly used to close PDE systems to define coupled problems. Users can correctly combine any of the aforementioned type of equations turning to the adequate use of Saiph’ operators. For this two first steps, the domain expert has been in charge, devolving upon him the responsibility of the correct problem definition and mathematical model statements. The rest of the modelling process is conceived within Saiph to be completely transparent to the users. After the selection of an appropriate mathematical model, together with suitable boundary and initial conditions, we can proceed to the numerical solution through the computer simulation. Is in that point where all the specific numerical methods are applied. From methods for the resolution of PDEs and non-derivative equations, to specific meth- 92
ods directly related to the computation of specific terms from fluid mechanics and/or chemistry problems. Alternatives to Euler’s method have been added for the nonderivative equations, methods for modelling convective terms, internal operators to be combined for the computation of diffusive terms, identification of such terms... everything being transparent to the user. Nowadays a fourth step on the described computational modelling process, should be take into account, that is the parallel execution. Saiph also takes care internally of adapting the applications for being executed in parallel. MPI and OpenMP parallelization are thus implemented to allow Saiph’ applications to be efficiently executed in a high-performance environment. The described 4-steps process has been successfully followed by the different fluid mechanics and chemistry use-cases faced in this project. Saiph appears to be a powerful tool that can be advantageously used by scientists without knowledge on numerical methods and supercomputing while internally providing the advantages of such expertise. 93
9|Conclusions and future work In this project, general user-level functionalities have been added to Saiph enlarging and easing the modelling constructions offered to the users. Internally, new features and optimizations have also been implemented in order to ensure the specific and correct computation of those new available user-constructions. Saiph provides more and easier features. Still, is important to remark that some of those extensions are subjected to the specific scientific domain faced. Those extensions still lack of genericity before being implicitly and systematically applied to any Saiph application. The development of Saiph should continue being driven by use-cases, whose requirements and impositions can light up the development progress. New use-cases can require the computation of more nesting derivatives levels or will need a convective gradient computation in a nonfirst-order differential equation or could contain a non-derivative equation enclosing a spatial differentiation as well as other situations leading, currently, to incorrect results. Therefore, some of the specific optimizations performed, are still not as general as desired but have resolved the problems and necessities encountered in this fluid mechanics and chemistry support extensions. In that sense, we have proposed solutions displaying the potential of Saiph ant its layer structure and they can be seen as first approaches to face more general requirements that can be encountered in the future. As a present and future recommendation, all the new features and functionalities should be integrated without breaking backward compatibility of the tool and trying to take into account all the possible situations that can be confronted in the future. Saiph’ extensions should be general enough to be applied for any computational modelling of any physical problem expressed through a partial differential equation system. Facing more use-cases from different scientific domains is a must for the future development of Saiph. From the numerical point of view, lot of work can be done; The addition of an internal check of the numerical stability, the dynamic computation of the more efficient time discretization factor at each computational step, the support to either 1D, 2D or 3D simulation problems are just examples of features that can be incorporated to Saiph to ease and enlarge its correctness, usability and efficiency. Regarding high performance complexities, we have demonstrated that a real and expensive Saiph application can be executed in a distributed environment without wasting the available resources. Nevertheless, in the current scenario, after validating the functioning of the tool, Saiph performance should be faced intensively. 94
A|Scala This appendix introduces the most basic concepts, constructions and features of Scala that are being used in Saiph applications. Variables The most relevant basic types for Saiph users are: Int,Float,Boolean and String. Scala has type inference, therefore, it automatically deduces the type of the initializing expression when it is known at compile time. Yet, this is not always the case, as it can be seen in line 4, if a value is initialized with an empty list, the type of this list should be specified either in the value or in the constructor. Values in Scala are declared as: 1val azero = 0 2val pi = 3.1416 3val l1 = List(1, 2, 3) 4val l2 : List[Int] = List() // Type specified as the value type 5val l3 = List[Int]() // Type inferred from the constructor type Functions Functions are defined using the def keyword. Specifying the formal parameter types is mandatory and, for recursive functions, the return type must also be specified: 1def add(x: Int, y: Int) = x + y 2def fibonacci(n: Int) : Int = { 3if (n < 0) -1 4else if (n==0||n==1)n 5else fibonacci(n-1) + fibonacci(n-2) 6} 95
Objects and classes Scala provides classes, objects and traits. These language constructs are used to implement abstract data types. Objects are created through class instantiation so, through keyword class. Scala provides singleton objects which act as group of static functions (they operate on no particular implicit instance) declared as object. If a class and an object share the same name they are called companion classes/objects. Companions objects and classes have access to each other’s private members. Scala allows declaring values, methods and types as abstract. Abstract type members are used to build generic components. Abstract classes cannot be instantiated and its abstract members need to be defined in their subclasses. This is achieved through the extends keyword. Subclasses inherit non-private members of its superclasses. In Scala, multiple inheritance is not allowed, meaning classes cannot inherit from multiple superclasses. Traits and mixin components Traits are declared in a similar way as regular classes with the exception that the programmer uses keyword trait instead of keyword class. A trait is actually, a special form of an abstract class which does not have any value parameters for its constructor. Consider the following abstraction for iterators. 1trait AbsIterator[T] { 2def hasNext: boolean 3def next: T 4} Traits can be used in all context where other abstract classes appear but only traits can be used as mixins. Mixin class composition is a form of multiple inheritance. By mixing in several traits into classes Scala provides stackable composition. The following code illustrates how a trait extends AbsIterator with a new method (foreach method): 1trait RichIterator[T] extends AbsIterator[T] { 2def foreach(f: T => unit): unit = 3while (hasNext) f(next) 4} Scala classes can mix in several traits with the keywords extends and with. The order in which traits are mixed in matters. 96
B|Lightweight Modular Staging Building a DSL The definition of a DSL in LMS consists of three main parts: •DSL interface The interface of the DSL must be defined with types and operations the programmer will use in the application. We build Vector DSL as an example. This DSL provides a generic type VT[_] and vector addition operation. The interface of Vector DSL is as follows: 1trait VectorOps extends Base { 2class VT[O] 3def infix_+[O:Manifest](x: Rep[VT[O]], y: Rep[VT[O]]) = 4vector_plus(x,y) 5def vector_plus[O:Manifest](x: Rep[VT[O]], y: Rep[VT[O]]): 6Rep[VT[O]] 7} The basic type of the language, VT[_], is represented here by an empty Scala class (line 2). In line 3, operation for adding two vectors is defined. The body of this method consists on a call to an abstract method vector_plus (line 5). This abstract method will be implemented in a later phase of the process. The meaning of having type Rep[VT] is that xand yrepresent a computation that will yield a VT in the next stage. For example, type Rep[Int] indicates that the staged computation will result in type Int in the next stage[5]. VectorOps is a trait mixed in with Base.Base is a part of LMS library. •Internal representation The following code shows the implementation of the Vector DSL: 97
1trait VectorOpsExp extends VectorOps with Expressions { 2case class VtPlus[O:Manifest](x: Exp[VT[O]], y: Exp[VT[O]]) 3extends Def[VT[O]] 4def vector_plus[O:Manifest](x: Exp[VT[O]], y: Exp[VT[O]]) = 5(x,y) match { 6case _ => VtPlus(x, y) 7} 8} The implementation is defined in trait VectorOpsExp (line 1). It implements the interface of our DSL, VectorOps. The trait Expressions provides an infrastructure for implementing an intermediate representation (IR) of our DSL as expression tree. The tree contains IR nodes of our DSL. The IR nodes are implemented as case classes (line 2) which take arguments of type Exp[_]. This LMS type constructor represents constants and symbols. Each case class extends a parametrized type constructor Def[_] which represents definitions. Symbols are bound to definitions. Each composite construct (such as case class VtPlus) refers to its parameters through symbols. Line 4 shows the body of method vector_plus. This method was declared abstract in the interface. This is the way the implementation is bound to its interface. However, this binding is loose, meaning interface and implementation of the DSL are implemented as separate traits. As we can see in the previous code, definitions are implemented as Scala case class, so they can be pattern-matched. This in turn allows the implementation of optimizations as we are going to see later. Here, since there is only the default case, a regular addition IR node is emitted (VtPlus) each time any argument is passed to the + operator. •Code generation This last stage, implements code generator for the DSL to target language. The following code shows the code generetor to C++ of the Vector DSL: 1trait VectorCppGen extends CGen { 2val IR: VectorOpsExp 3import IR._ 4override def emitNode(sym: Sym[Any], rhs: Def[Any]): Unit = 5rhs match { 6case VtPlus(x, y) => emitValDef(sym, 7quote(x) + "+"+ quote(y)) 8case _ => super.emitNode(sym, rhs) 98
140 left_value + (((right_value - left_value)/FLAME_THIKNESS)* (x -FLAME_START_X)) 141 } 142 143 // Mass fraction 144 val Y = Term(Unitless)("Yk, mass fractions", mesh, { x => 145 if (x < FLAME_START_X) UNBURNT 146 else if (x > FLAME_END_X) BURNT 147 else linear_window_vector(x, UNBURNT, BURNT) 148 }, GAS_NAMES) 149 Y.setDirichlet(CFaceXMIN)(UNBURNT) 150 Y.setNeumann(CFaceXMAX)(YFLUX) 151 152 // Temperature 153 val T = Term(Temperature)("Temperature", mesh, { x => 154 if (x < FLAME_START_X) INIT_T_UNBURNT 155 else if (x > FLAME_END_X) INIT_T_BURNT 156 else linear_window_scalar(x, INIT_T_UNBURNT, INIT_T_BURNT) 157 }) 158 T.setDirichlet(CFaceXMIN)(INIT_T_UNBURNT) 159 T.setNeumann(CFaceXMAX)(TFLUX) 160 161 // Pressure 162 val p = Term(Pressure)("Pressure", mesh, INIT_P) 163 p.setDirichlet(CFaceXMIN)(INIT_P) 164 p.setNeumann(CFaceXMAX)(PFLUX) 165 166 // Density 167 val rho = Term(Kg_m3)("Density", mesh, { x => 168 if (x < FLAME_START_X) DENSITY_UNBURNT 169 else if (x > FLAME_END_X) DENSITY_BURNT 170 else { 171 val vec = linear_window_vector(x, UNBURNT, BURNT)/vW 172 val sum_win = vec(0) + vec(1) + vec(2) + vec(3) + vec(4) 173 INIT_P / sum_win / (R_VALUE * linear_window_scalar(x, INIT_T_UNBURNT, INIT_T_BURNT)) 174 } 175 }) 176 177 // Velocity 178 val u = Term(Speed)("Velocity", mesh, { x => 179 if (x < FLAME_START_X) V_UNBURNT 105
180 else if (x > FLAME_END_X) V_UNBURNT * (DENSITY_UNBURNT/ DENSITY_BURNT) 181 else { 182 val vec = linear_window_vector(x, UNBURNT, BURNT)/vW 183 val sum_win = vec(0) + vec(1) + vec(2) + vec(3) + vec(4) 184 V_UNBURNT * (DENSITY_UNBURNT / (INIT_P / sum_win / (R_VALUE * linear_window_scalar(x, INIT_T_UNBURNT, INIT_T_BURNT)))) 185 } 186 }, List[Rep[String]]("X","Y","Z")) 187 u.setDirichlet(CFaceXMIN)(V_UNBURNT) 188 u.setNeumann(CFaceXMAX)(UFLUX) 189 190 // Mass flow (rho*u = cte) 191 val rho_u = Term(Kg_m2s)("Rho * u", mesh, { x => DENSITY_UNBURNT * V_UNBURNT }, List[Rep[String]]("X","Y","Z")) 192 193 // Rho * Y 194 val rho_Y = Term(Kg_m3)("Rho * Y", mesh, { x => 195 if (x < FLAME_START_X) DENSITY_UNBURNT * UNBURNT 196 else if (x > FLAME_END_X)DENSITY_BURNT * BURNT 197 else { 198 val vec = linear_window_vector(x, UNBURNT, BURNT)/vW 199 val sum_win = vec(0) + vec(1) + vec(2) + vec(3) + vec(4) 200 (INIT_P / sum_win / (R_VALUE * linear_window_scalar(x, INIT_T_UNBURNT, INIT_T_BURNT))) * linear_window_vector(x, UNBURNT, BURNT) 201 } 202 }, GAS_NAMES) 203 204 // Rho * T 205 val rho_T = Term(KgK_m3)("Rho * T", mesh, { x => 206 if (x < FLAME_START_X) DENSITY_UNBURNT * INIT_T_UNBURNT 207 else if (x > FLAME_END_X) DENSITY_BURNT * INIT_T_BURNT 208 else { 209 val vec = linear_window_vector(x, UNBURNT, BURNT)/vW 210 val sum_win = vec(0) + vec(1) + vec(2) + vec(3) + vec(4) 211 (INIT_P / sum_win / (R_VALUE * linear_window_scalar(x, INIT_T_UNBURNT, INIT_T_BURNT))) * linear_window_scalar(x, INIT_T_UNBURNT, INIT_T_BURNT) 212 } 213 }) 214 215 106
216 // Omega. Species source term 217 val omega_species_k = Term(Kg_m3s)("Species source terms", mesh, Vector(0 * Kg_m3s, 0 * Kg_m3s, 0 * Kg_m3s, 0 * Kg_m3s, 0 * Kg_m3s), GAS_NAMES) 218 219 // Omega. Heat release 220 val omega_heat = Term(J_m3s)("Heat release", mesh, 0 * J_m3s) 221 222 223 // Premixed laminar flame equations 224 225 // Species source term 226 // Rate constant 227 val Kf = Af * exp(Ea / (R*T)) 228 // Species concentrations 229 val XCH4 = rho_Y(0) / MolarMassVector(0) 230 val XO2 = rho_Y(2) / MolarMassVector(2) 231 // Reaction rate progress 232 val Q = Kf * XCH4 * XO2 * XO2 233 val omegak = Equation(omega_species_k, (MolarMassVector.comp * nu .comp * Q)) 234 235 // Heat release 236 val omegaT = Equation(omega_heat, - (sum(cwiseprod(h, omega_species_k)))) 237 238 // Equation 1: Continuity equation 239 val density = Equation(dt(rho), -div(rho_u)) 240 241 // Equation 2: Momentum equation 242 val momentum = Equation(dt(rho_u), -((rho_u * grad(u.comp)) + (u. comp * div(rho_u)) + grad(p).comp) + (mu_cte * mu * der2(DirX)( u.comp))) 243 244 // Equation 3: Species equations 245 // Convective term 246 val Yconv = - ((rho_u * grad(Y.comp)) + (Y.comp * div(rho_u))) 247 // Diffusion term 248 val Ydiff = div((lambda / cp) * grad(Y.comp)) 249 val rho_species = Equation(dt(rho_Y), Yconv + Ydiff + omega_species_k.comp) 250 251 // Equation 4: Temperature equation 107
252 // Convective term 253 val Tconv = - (cp * ((rho_u * grad(T)) + (T * div(rho_u)))) 254 // Diffusion term 255 val Tdiff = div(lambda * grad(T)) 256 val rho_temperature = Equation(dt(rho_T), (Tconv + Tdiff + omega_heat) / cp) 257 258 // Auxiliar equations: 259 // Species 260 val species = Equation(Y, rho_Y.compWithOffset(0) / rho.toff(0)) 261 262 // Temperature 263 val temperature = Equation(T, rho_T.toff(0) / rho.toff(0)) 264 265 // Velocity 266 val velocity = Equation(u, rho_u.compWithOffset(0) / rho.toff(0)) 267 268 // Equation 5: State equation (pressure) 269 val pressure = Equation(p, rho_T.toff(0) * R * sum(Y.toff(0) / MolarMassVector)) 270 271 val flame1D = Problem(DELTA_TIME, N_STEPS, mesh)(omegak, omegaT, density, momentum, rho_species, rho_temperature, species, temperature, velocity, pressure) 272 273 EulerSolver(flame1D)("FLAME", OutputFormat.VTI, SamplingMethod. Periodic, 1) 274 } 275 } 276 def main(args: Array[String]): Unit = { 277 new Flame1DProg with SaiphOpsExp { self => 278 val codegen = new SaiphCGen { val IR: self.type = self } 279 codegen.emitSource(Flame1D _, new PrintWriter(Console.out)) 280 } 281 } 282 } 108
Bibliography [1] Zachary DeVito, Niels Joubert, Francisco Palacios, Stephen Oakley, Montserrat Medina, Mike Barrientos, Erich Elsen, Frank Ham, Alex Aiken, Karthik Duraisamy, et al. Liszt: A domain specific language for building portable mesh-based pde solvers. 2011. 5 [2] Anders Logg, Kristian B. Ølgaard, Marie E. Rognes, and Garth N. Wells. FFC: the FEniCS Form Compiler, chapter 11. Springer, 2012. 6 [3] Todd Dupont, Johan Hoffman, Claus Johnson, Robert C Kirby, Mats G Larson, Anders Logg, and L Ridgway Scott. The FEniCS project. Chalmers Finite Element Centre, Chalmers University of Technology, 2003. 6 [4] Martin Odersky and al. An Overview of the Scala Programming Language. Technical Report IC/2004/64, EPFL, Lausanne, Switzerland, 2004. 7 [5] Tiark Rompf and Martin Odersky. Lightweight modular staging: a pragmatic approach to runtime code generation and compiled dsls. In Proceedings of the ninth international conference on Generative programming and component engineering, GPCE ’10, pages 127–136, New York, NY, USA, 2010. ACM. ISBN 978- 1-4503-0154-1. doi: 10.1145/1868294.1868314. URL http://doi.acm.org/10. 1145/1868294.1868314. 7, 97 [6] Adriaan Moors, Tiark Rompf, Philipp Haller, and Martin Odersky. Scalavirtualized. In Proceedings of the ACM SIGPLAN 2012 workshop on Partial evaluation and program manipulation, PEPM ’12, pages 117–120, New York, NY, USA, 2012. ACM. ISBN 978-1-4503-1118-2. doi: 10.1145/2103746.2103769. URL http://doi.acm.org/10.1145/2103746.2103769. 7, 10 [7] Martin Odersky, Philippe Altherr, Vincent Cremet, Burak Emir, Sebastian Maneth, St´ephane Micheloud, Nikolay Mihaylov, Michel Schinz, Erik Stenman, and Matthias Zenger. An overview of the scala programming language. Technical report, 2004. 9 [8] Tiark Rompf and Martin Odersky. Lightweight modular staging: a pragmatic approach to runtime code generation and compiled dsls. In Acm Sigplan Notices, volume 46, pages 127–136. ACM, 2010. 10 109
[9] Jacques Carette, Oleg Kiselyov, and Chung-chieh Shan. Finally tagless, partially evaluated: Tagless staged interpreters for simpler typed languages. J. Funct. Program., 19(5):509–543, September 2009. ISSN 0956-7968. doi: 10.1017/ S0956796809007205. URL http://dx.doi.org/10.1017/S0956796809007205. 10 [10] William Gropp, Ewing Lusk, and Anthony Skjellum. Using MPI: portable parallel programming with the message-passing interface, volume 1. MIT press, 1999. 30 [11] Barbara Chapman, Gabriele Jost, and Ruud Van Der Pas. Using OpenMP: portable shared memory parallel programming, volume 10. MIT press, 2008. 31 [12] TJ Poinsot and DP Veynante. Combustion. Encyclopedia of Computational Mechanics. 33, 79 [13] Scott Meyers. Effective Modern C++: 42 Specific Ways to Improve Your Use of C++ 11 and C++ 14. ” O’Reilly Media, Inc.”, 2014. 45 [14] Amy Henderson, Jim Ahrens, Charles Law, et al. The ParaView Guide. Kitware Clifton Park, NY, 2004. 45 [15] Thomas Williams and Colin Kelley. many others, gnuplot 4.4: an interactive plotting program, 2010. 45 [16] Extrae. User guide manual -for version 2.5.1. URL https://www.bsc. es/computer-sciences/performance-tools/trace-generation/extrae/ extrae-user-guide. 45 [17] Paraver: a flexible performance analysis tool . URL https://www.bsc.es/ computer-sciences/performance-tools/documentation. 45 [18] Hugo Winter and John Thuburn. Numerical advection schemes in two dimensions. 2011. 54 [19] Dale R Durran. Numerical methods for wave equations in geophysical fluid dynamics, volume 32. Springer Science & Business Media, 2013. 54 [20] G. Sod. A survey of several finite difference methods for systems of nonlinear hyperbolic conservation laws. Journal of Computational Physics, 27(1):1–31, 1978. ISSN 00219991. URL http://dx.doi.org/10.1016/0021-9991(78)90023-2. 64 [21] Ali Ben Moussa and Hatem Ksibi. Numerical simulation of a one-dimensional shock tube problem at supercritical fluid conditions. International Journal of Fluid Mechanics Research, 35(1):38–50, 2008. ISSN 1064-2277. 66 [22] Gas dynamics: The riemann problem and discontinuous solutions: Application to the shock tube problem. In Ionut Danaila, Pascal Joly, SidiMahmoud Kaber, and Marie Postel, editors, An Introduction to Scientific Computing, pages 213–233. Springer New York, 2007. ISBN 978-0-387-30889-0. doi: 10.1007/978-0-387-49159-2_10. 69 110
[23] M. Moragues. Variational multiscale stabilization and local preconditioning for compressible flow. phd thesis submitted to universitat polit´ecnica de catalunya. 147, 2015. 69 [24] T. Mantel, F.N. Egolfopoulos, and C.T. Bowman. A new methodology to determine kinetic parameters for one- and two-step chemical models. Center for Turbulence Research, Proceedings of the Summer Program, 1996. 73 [25] Eduardo Fern´andez-Tarrazo, Antonio L. S´anchez, Amable Li˜n´an, and Forman A. Williams. A simple one-step chemistry model for partially premixed hydrocarbon combustion. Combustion and Flame, 147(1-2):32–38, 2006. 73 [26] M.M. Holton and College Park. Mechanical Engineering University of Maryland. Autoignition Delay Time Measurements for Natural Gas Fuel Components and Their Mixtures. University of Maryland, College Park, 2008. ISBN 9780549957867. 77, 78 [27] Dipl-Ing Dieter Kaufmann and Ing Paul Roth. The method of fractional steps applied to laminar flat flame calculations. Forschung im Ingenieurwesen A, 53(4): 113–117, 1987. 79 [28] D. Mira, M. Zavala, M. Avila, Herbert Owen, J.C. Cajas, G. Houzeaux, and M. V´azquez. Heat transfer effects on a fully premixed methane impinging flame, 17-10 Sept. 2014. 87 [29] LMS Official website. URL http://scala-lms.github.io/. 99 111