134

Computation of phase equilibria in uid mixtures

Embed Size (px)

Citation preview

Page 1: Computation of phase equilibria in uid mixtures

Computation of phase equilibriain uid mixturesby

Egil BrendsdalThesis submitted for partial ful�llmentof the requirements for the degree of

Doktor Ingeni�rAvdeling for teknologiske fagH�gskolen i TelemarkPorsgrunn

Page 2: Computation of phase equilibria in uid mixtures
Page 3: Computation of phase equilibria in uid mixtures

AcknowledgmentsMy main supervisors have been prof. dr. techn. Sven J. Cyvin, present occupation full timephilatelist, and dr. ing. Tore Haug-Warberg. They both deserve special thanks for their contri-butions, both in discussions, guidance and for organizing the study. I would also like to thankMarsha Torsteinsen for helping me to prepare the document.Financial support for this project was provided by Norges Teknisk-NaturvitenskapligeForskningsr�ad, project number 221822, Norges Forskningsr�ad, project number 100591/410, andInstitutt for Energiteknikk.

Page 4: Computation of phase equilibria in uid mixtures
Page 5: Computation of phase equilibria in uid mixtures

SummaryThis thesis outlines a general approach to the computation of thermodynamic equilibrium andphase diagrams based on existing mathematical models for thermodynamic properties.The general equations governing thermodynamic equilibria are presented in a form suitablefor a uni�ed solution strategy, and the mathematical transforms enabling equilibrium computa-tions at alternate constraint speci�cations are explained. An algorithm for computation tasksis proposed. This algorithm requires analytical �rst and second-order derivatives of the thermo-dynamic models. The algorithm is based on a Newton-Lagrange scheme utilizing step lengthadjustment. The algorithm has second order convergence independent of constraint speci�ca-tions, and the phase stability problem is resolved by a method that can be speci�c to eachphase model. A trajectory method suitable for stability computations based on equation ofstate phase models is described. Computational results, including calculations of four-phaseequilibria at alternate constraint speci�cations and stability computation of partially open andreacting systems, are shown in the text.A simple procedure for the construction of phase diagrams is proposed. In addition tothe prerequisites of the algorithm for equilibrium computations, this procedure requires aninitial equilibrium point consisting of the maximum number of phases that can coexist in thethermodynamic system. The phase envelopes are described by ordinary di�erential equationsand the phase diagrams are computed by a simple predictor corrector scheme. Computationalresults, included a phase diagram of a near-critical azeotrope and a ternary system with afour-phase envelope, are reported.

i

Page 6: Computation of phase equilibria in uid mixtures
Page 7: Computation of phase equilibria in uid mixtures

PrefaceI began studying thermodynamics, not inspired by any particular interest in the subject, butmore as a result of the annoyance of not understanding it. When trying to get accustomed tothe material, I found the postulational formulation of thermodynamics very useful. Althoughpostulates do not add anything to the understanding of thermodynamics, they provide themathematical basis for equilibrium computations. Computations, on the other hand, havealways fascinated me. In the process of learning, I also �nd developing algorithms very useful;First, as a prerequisite for all computations, one must gain enough knowledge of the material inorder to explain the problem to the mindless equipment commonly referred to as the computer.Next, when the algorithm is tried in action, the computer will relentlessly reveal the weak partsof the chosen strategy.Back in 1993, I started the dr. ing. project with the intention to investigate alternativenumerical schemes for equilibrium computations based on equations of state models. However,I gradually became more interested in the general nature of equilibrium thermodynamics. I alsorealized the ine�ciency in my approach to test alternative strategies of equilibrium computa-tions. I missed especially having a tool for rapid prototyping allowing easier investigation ofnew methods and general trouble-shooting. Being a novice to object oriented programming, Iassumed a class library suitable for prototyping could be achieved within the project period.However, this idea resulted in programming 4 500 general purpose functions before I returnedto the main objective of the project.Nearly at the end of the project, I suddenly realized that typesetting the thesis was themost challenging part of the job. According to the TEXbook [25], material requiring onemonth of experience is, upon completion of the thesis, still completely incomprehensible to me!Unfortunately, time did not allow any �ne-tuning of the mathematical formulae or layout of thetext.

Premature optimization is the root of all evil{ Donald E. Knuthiii

Page 8: Computation of phase equilibria in uid mixtures
Page 9: Computation of phase equilibria in uid mixtures

ContentsSummary iPreface iiiContents vNotation ix1 Introduction 11.1 Organization of the thesis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Theory 52.1 Equilibrium thermodynamics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Computation of thermodynamic equilibria . . . . . . . . . . . . . . . . . . . . . 72.3 Calculation of phase diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Existing methods 133.1 Computation of thermodynamic equilibria . . . . . . . . . . . . . . . . . . . . . 133.2 Phase diagram construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.3 Stability testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.4 Trajectory methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 Algorithms 174.1 Computation of phase and reaction equilibrium . . . . . . . . . . . . . . . . . . 174.1.1 Transformation of thermodynamic surfaces . . . . . . . . . . . . . . . . . 174.1.2 Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204.1.3 Solution of the �rst-order conditions . . . . . . . . . . . . . . . . . . . . 204.1.4 Updating the phase assembly . . . . . . . . . . . . . . . . . . . . . . . . 224.1.5 Initialization of phase stability analysis . . . . . . . . . . . . . . . . . . . 244.1.6 Update of a metastable phase assembly . . . . . . . . . . . . . . . . . . . 244.2 Computation of phase diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.2.1 Combinations of coexisting phases . . . . . . . . . . . . . . . . . . . . . . 274.2.2 Tracing of lines in phase diagrams . . . . . . . . . . . . . . . . . . . . . . 284.2.3 Locating points in a phase diagram . . . . . . . . . . . . . . . . . . . . . 304.3 Stability analysis by a trajectory method . . . . . . . . . . . . . . . . . . . . . . 324.3.1 Governing equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324.3.2 Numerical considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 Computational results 355.1 Phase diagrams of a binary system . . . . . . . . . . . . . . . . . . . . . . . . . 36v

Page 10: Computation of phase equilibria in uid mixtures

vi Contents5.1.1 Pressure-composition diagram . . . . . . . . . . . . . . . . . . . . . . . . 365.1.2 Temperature-composition diagram . . . . . . . . . . . . . . . . . . . . . 375.1.3 Pressure-temperature diagram . . . . . . . . . . . . . . . . . . . . . . . . 385.2 Stability of minerals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405.2.1 Stability computation of reacting system . . . . . . . . . . . . . . . . . . 405.2.2 Phase diagram construction . . . . . . . . . . . . . . . . . . . . . . . . . 435.2.3 Thermodynamic models . . . . . . . . . . . . . . . . . . . . . . . . . . . 455.3 Phase diagrams with several critical points . . . . . . . . . . . . . . . . . . . . . 465.4 Critical azeotrope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485.4.1 Phase diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485.4.2 Equilibrium computations . . . . . . . . . . . . . . . . . . . . . . . . . . 505.5 Ternary mixture with tricritical point . . . . . . . . . . . . . . . . . . . . . . . . 515.5.1 Phase diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515.5.2 Equilibrium computations . . . . . . . . . . . . . . . . . . . . . . . . . . 535.6 Stability analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596 Discussion 63References 67A Models of thermodynamic properties 71A.1 Pure component chemical potential . . . . . . . . . . . . . . . . . . . . . . . . . 71A.2 Ideal gas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72A.3 Cubic equation of state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73A.3.1 Model speci�c parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 73B Miscellaneous mathematical formulae 75B.1 Partial derivatives and matrix notation . . . . . . . . . . . . . . . . . . . . . . . 75B.2 Taylor's Theorem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77B.3 Sherman-Morrison formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77B.4 Matrix identities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78B.5 Homogeneous functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78B.5.1 Functions of arbitrary degree of homogeneity . . . . . . . . . . . . . . . . 78B.5.2 First-order homogeneous functions . . . . . . . . . . . . . . . . . . . . . 79C Transforms of thermodynamic functions 81C.1 Legendre transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81C.1.1 De�nition of the Legendre transformation . . . . . . . . . . . . . . . . . 81C.1.2 The �rst-order derivatives of a Legendre transformed function . . . . . . 82C.1.3 Second order derivatives of Legendre-transformed function . . . . . . . . 82C.2 The inverse Legendre transformation . . . . . . . . . . . . . . . . . . . . . . . . 83C.3 Implicit functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84D Constrained optimization 87D.1 Constrained minimization conditions . . . . . . . . . . . . . . . . . . . . . . . . 87D.2 Descent properties of the Newton direction . . . . . . . . . . . . . . . . . . . . . 88D.3 Optimum of a sum of �rst-order homogeneous functions . . . . . . . . . . . . . . 89D.3.1 First-order conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89D.3.2 First-order conditions of a system of thermodynamic functions . . . . . . 90D.3.3 Optimization of Legendre transformed functions . . . . . . . . . . . . . . 91

Page 11: Computation of phase equilibria in uid mixtures

Contents viiD.3.4 Optimization of implicit functions . . . . . . . . . . . . . . . . . . . . . . 92D.4 The Newton-Lagrange scheme for a sum of �rst-order homogeneous functions . . 93D.5 Pathfollowing of curves of local minimizers . . . . . . . . . . . . . . . . . . . . . 94E Numerical algorithms 99E.1 Newton's method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99E.1.1 Taylor expansion of inverse functions . . . . . . . . . . . . . . . . . . . . 99E.1.2 Newton iteration formulae . . . . . . . . . . . . . . . . . . . . . . . . . . 103E.2 Pathfollowing using Euler predictor and Newton's method as corrector . . . . . 103E.3 Canonical forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104E.4 Automatic di�erentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105F Design of a data type representing thermodynamic surfaces 107F.1 Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107F.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111Index 115

Page 12: Computation of phase equilibria in uid mixtures
Page 13: Computation of phase equilibria in uid mixtures

NotationIt is has been tried to provide as complete an index as possible and the page numbers where asymbol is used are included in the index. Hopefully, this will provide the necessary informationto resolve the symbol con icts. However, symbols used consistently throughout the thesis some-times refer to only the page where the symbol is de�ned or used for the �rst time. Furthermore,the notation of thermodynamic variables is also summarized in a separate table on page xii.A Helmholtz energy 6A Arbitrary symmetric matrix 78A Constraint matrix in optimization problem 89A Constraint matrix in equilibrium computation 9, 11, 20B Arbitrary symmetric matrix 78C Arbitrary matrix 78G Gibbs energy 6H Enthalpy 6H Hessian of a �rst-order homogeneous function 93H Hessian of thermodynamic surface 12, 20fH Rank-one updated Hessian of shifted �rst-order homoge-neous function 23, 93I Identity matrix 76L Legendre transform 17-19, 53L-1 Inverse Legendre transform 17, 19, 55M Number of distinct phase models in an equilibriumcomputation 20M Number of zero sized phases on a boundary 11, 28N Number of coexisting phases 6, 9, 20, 36N Number of nonzero sized phases on a boundary 11, 28N Sum of mole numbers 72P Pressure 5P Permutation matrix 9, 11, 20, 89P Massieu function 17-18, 56R Recursive function generating permutations 28R Gas constant, 8.3143 J K-1 mol-1 [59]. 72R Hessian of r 85R Formula matrix 18S Entropy 5S Shifted surface 17, 57T Temperature 5ix

Page 14: Computation of phase equilibria in uid mixtures

x NotationU Internal energy 5U Hessian of u 82V Volume 5V Hessian of v 83W Weighting matrix 29a A set of nonzero sized phases 28b A set of zero sized phases 28b Constraint vector in optimization problem 89b Constraint speci�cation in equilibrium computation 9, 11, 20c Constant phase size in phase diagram construction 11, 28c Molar heat capacity 50, 58, 71e Constant vector in phase diagram construction 11, 28f First-order homogeneous function 89f Thermodynamic surface 9ef Shifted �rst-order homogeneous function 23, 93g Transposed gradient of �rst-order homogeneous function 93g Transposed gradient of function in global optimizationproblem 15g Vector of �rst-order derivatives of thermodynamic surface f 9, 11, 20eg Gradient of shifted �rst-order homogeneous function 23, 93h Molar enthalpy 71l Lagrange function 87, 93l Liquid phase 51m Mass [16] 80, 90m Merit function 22, 30m Polynomial in acentric factor 73n Mole number 5n Vector of mole numbers 7, 74p Pressure [16] 80, 90p Permutation matrix in the constraint speci�cation of molenumbers 18s Molar entropy density 37s Molar entropy in a one component system 71t Independent variable in autonomous ODE 27, 32, 59t Temperature [16] 80, 90v Vapor phase 51x Mole fraction 36x Variable in optimization problem 89x Phase coordinates in equilibrium computation 9, 20x Phase coordinates in phase diagram construction 11�max Speci�ed maximum relative variation of extensive coordi-nates in the corrector step 30� Linear relation between constraint speci�cations 30, 95 Grand canonical potential, = �PV 6� Phase label 26, 37� Phase size 20, 24� Step length in Newton direction 22, 30� Phase label 26, 37

Page 15: Computation of phase equilibria in uid mixtures

Notation xi Phase label 26, 37� Di�erence between variables in two iteration steps 93� Number of zero eigenvalues of a symmetric matrix 23� Internal energy [16] 80, 90� Small positive number 64� Entropy [16] 80, 90� Smallest eigenvalue of Hessian 33, 60� Vector of Lagrange multipliers 9, 11, 20, 87, 93� Homotopy parameter 15� Arbitrary parameter 78� Lagrange multiplier 8� Vector of chemical potentials 7� Chemical potential 5-6, 80, 90� Number of negative eigenvalues of a symmetric matrix 23� Computed increment of phase size in the Newton-Lagrange scheme 25, 94� Number of positive eigenvalues of a symmetric matrix 23� Phase stability test function 27, 38, 64, 91! Acentric factor 50, 73Mathematical symbols and functionsO Bachmann-Landau order of magnitude symbol, the \big oh" 27, 78IR The real numbers 75, 103corank For A 2 IRn�m, corank of A is equal to the dimension ofthe nullspace of A 93diag Diagonal matrix, e.g. diag(�12�) = �10 02� 20rank Number of linearly independent rows in a general matrix 24� Kronecker delta. �ij = n1 if i = j0 if i 6= j 32, 93, 100, 104� The signature of a symmetric matrix 23, 92n Set minus 28r Gradient operator 75[ Union 28� Derivative with respect to independent variable in au-tonomous ODE, ( _ ) = d( )dt 12, 16, 27-29, 32-34, 38, 60, 103; Empty set. 28AbbreviationsEOS Equation Of State 48LP Linear Programming 24ODE Ordinary Di�erential Equation 28, 32PR Peng-Robinson 59QP Quadratic Programming 23SRK Soave-Redlich-Kwong 48

Page 16: Computation of phase equilibria in uid mixtures

xii NotationSuperscripts0; 1 : : : Iteration count 20T Transposed 8� Equilibrium value 6, 24� Minimum value 64� Speci�ed equilibrium value 8� Constrained value 11, 18� Reference state 50, 73^ Shifted �rst-order homogeneous function 8ig Ideal Gas 73Subscripts1; 2 : : : Component number 18C Critical state 73P Constant pressure 50, 58, 71SVn Constraint speci�cation 19, 24W Weighted inner product 29, 97, 104� Phase label 26� Phase label 26 Phase label 26h Homogeneous solution 29, 33-34, 97, 104i Component number 6j Component number 6k Phase number 6p Particular solution 29, 33-34, 97, 104Table 1: Notation of thermodynamic quantities. Corresponding symbols used in the literatureis included in the table. According to the notation of Gibbs, mass and not mole number is theindependent variable. The energy functions are in [16] referred to as \quantities", especially,the phrase \Gibbs energy" is not used. Gibbs [16, page 87] Callen [8]Entropy S � SVolume V v VMole number n m NTemperature T t TPressure P p PChemical potential � � �Internal energy U � UHelmholtz energy A FEnthalpy H � HGibbs energy G � G

Page 17: Computation of phase equilibria in uid mixtures
Page 18: Computation of phase equilibria in uid mixtures
Page 19: Computation of phase equilibria in uid mixtures

Chapter 1IntroductionComputation of phase and reaction equilibria is nowadays performed routinely, and it is reason-able to raise a critical question: Should thermodynamics and computation of thermodynamicequilibria still be the subject for research? Those working in the area of scienti�c computingwill perhaps be even more critical and claim that the computational problem is not particularlyinteresting. Such criticism is indeed sound. The theory of Gibbsian thermodynamics appears tobe fully explained more than one century ago and it is not likely that anything can be added orimproved. It is also true that there exists a variety of software tools for computation of phaseand reaction equilibria, but each program is, in general, capable of solving only a few types ofproblem. Such programs will, irrespective of the thermodynamic system considered, solve thesame equilibrium relations. Thus, instead of having one program for computing thermodynamicequilibria in metallurgical systems and another for computing phase behavior of hydrocarbonmixtures etc., why not design a program that deals with all kinds of equilibrium problems?A computer program that solves every imaginable thermodynamic problem will, of course,never see the light of day, and it is perhaps wrong to think that a uni�ed solution strategy issuitable in thermodynamic computations. Nevertheless, one of the goals of this work has beento formulate the conditions of thermodynamic equilibrium with the fewest possible restrictionsto enable the solution of di�erent problems by the same formalism.To achieve the desired generality it was found useful to formulate the equations in termsof generalized thermodynamic surfaces. It is exempli�ed that the energy surfaces described byexisting phase models can, by appropriate mappings, be transformed into suitable generalizedsurfaces whenever needed. In addition to the transforms described in the literature, i.e. theLegendre transform and the Massieu function [8], two additional transforms are needed for thetask. These are referred to as shifted surface and inverse Legendre transform, respectively. Bythese transforms, the most important constraints speci�cations in equilibrium computations,e.g. isothermal ash, constant volume computation, isenthalpic ash, isentropic ash etc., areall covered by the chosen formalism. Furthermore, due to the generality of the formalism,reacting systems as well as open systems and partially open systems can be dealt with. It is,however, assumed that the equilibrium state is characterized by a set of common generalizedintensive variables, and the formalism will accordingly not cover problems involving e.g. rigidsemipermeable membranes and curved surfaces where phases coexist at di�erent pressure.A major part of the work has been devoted to the design of a C++ data type [56, 57, 58]representing the generalized thermodynamic surfaces that are used to formulate the equilibriumconditions. Traditionally, scienti�c computation algorithms operate on simple data types likeintegers and real numbers and one main obstacle in programming has been to formulate theoverall problem in such low level objects. However, modern computer languages have provisionfor building more complex data types, and the proposed data type for thermodynamic surfaces1

Page 20: Computation of phase equilibria in uid mixtures

2 Chapter 1: Introductionhas some features that make the algorithmic part of the programming a pleasant job. Onepeculiarity of the data type is that transformation of objects is implemented. This enables oneobject representing e.g. a Gibbs energy surface to be transformed to a Helmholtz energy surface.Furthermore, there are no restrictions on the data type modeling thermodynamic surfaces. TheHelmholtz surface can e.g. be transformed to an internal energy surface and subsequently toan entropy surface, if this is appropriate in the problem considered. Since the data type isused in numerical analysis, some functionality for accessing the properties of the surface arealso provided. An object, irrespective of what thermodynamic surface it represents, e�cientlycomputes both the �rst and the second order derivatives of the corresponding thermodynamicfunction. The functionality for returning the second order derivatives has been implementedwith emphasis on using a Newton-Lagrange method for computing the equilibrium state.Another part of the work has been to develop two algorithms based on the designed datatype, one algorithm for equilibrium computation, including phase stability testing, and onealgorithm for the phase diagram construction. The equilibrium computations are formulatedas optimization problems and solved with a Newton-Lagrange iteration sequence. In short,the equilibrium algorithm is based on transformations of generalized thermodynamic surfaceswhich in every situation lead to an optimization problem with linear constraints. Thus, asa spin-o� from designing the thermodynamic surfaces as objects, the numerical computationof the Newton step is tremendously simpli�ed. In the algorithm, few assumptions are madewith respect to the thermodynamic models. The implementation of a new phase model in thealgorithm requires only the analytical �rst and second-order derivatives of the fundamentalequation. The actual variables of the fundamental equation is of no concern, the algorithm willautomatically perform the transformations required for computations at arbitrary constraintspeci�cations.An important part of the equilibrium computation is to verify, by stability analysis, that apossible solution is the true equilibrium state. Although the equilibrium problem considered isof a general nature, it is not required to establish a corresponding generalized stability analysis.In the developed algorithm, it is possible to provide one speci�c stability test strategy for eachphase model used to describe the thermodynamic system. In this way it is possible to exploit anypeculiarity of the phase models, i.e. for a simple phase model like the ideal gas, the stability testis simpli�ed to an analytic expression. For more complex equation of state phase models, thealgorithm invokes a novel trajectory method. This trajectory method is, however, not suitablefor any other phase models.Another task has been to study the construction of phase diagrams. Here too, a generalapproach is chosen and the equations applied at a boundary in the phase diagram are formulatedin terms of generalized thermodynamic surfaces. By this approach, the phase envelopes can,even in the general situation, be described as the solution set of a system of equations consistingof linear constraints and the conditions for thermodynamic equilibria.Summarized, the objectives of this work have been to:� Formulate the equations of thermodynamic equilibria in a form suitable for a uni�ed solu-tion strategy.� Design an appropriate C++ data type for modeling of generalized thermodynamic surfaces.� Develop an algorithm for equilibrium computations where also the stability test problemis considered.� Outline a method for phase diagram construction.

Page 21: Computation of phase equilibria in uid mixtures

Chapter 1: Introduction 31.1 Organization of the thesisThe following material starts with a brief summary of the theory of equilibrium thermodynamics.In Section 2.2, the theory is extended to include inverse Legendre transforms and shifted surfaces.Furthermore, it is indicated that these transformations enables the equilibrium computation atalternate constraint speci�cations by a uni�ed approach. Some theory on how to constructphase diagrams is outlined in Section 2.3, and a continuation method well suited for the phasestability problem is shown in the last section of Chapter 2.Some relevant literature is summarized in Chapter 3. The summary of literature on existingmethods of equilibrium computation and phase diagram construction is rather brief.The algorithms are presented in Chapter 4. Both the algorithm for equilibrium compu-tation, Section 4.1, and the algorithm for phase diagram construction, Section 4.2, are basedon the tailor-made data type for representing thermodynamic surfaces. As a consequence ofthe object oriented design, only a few additional numerical routines are required to implementthe algorithms. The design of the data type is, however, presented as source code of the C++programming language. This will probably appeal only to those familiar with the language, andthe implementation of the data type is outlined only brie y in Appendix F. Some mathemati-cal results are involved in the algorithms. These results are presented in separate parts of theappendices in order to reduce symbol con icts. The mathematical foundation of transformedthermodynamic functions is shown in Appendix C. The algorithms for equilibrium computationand phase diagram construction are both based on one particular type of optimization problemwhich is outlined in Appendix D.Some material used in the design phase of the algorithms is also included in the appendices.The technique called automatic di�erentiation, see Appendix E.4, was especially valuable in thedesign of the trajectory method as it provides a fast and convenient way to check the calculatedderivatives of thermodynamic phase models.Whenever possible, matrix notation is used in both the theory part and in the presentationsof the algorithms. Of course, this is not a necessity, but the matrix notation is compact andeasy to read when one becomes familiar with it. It has also been tried to use symbols inaccordance with the literature in the di�erent parts of the thesis. This will inevitably leadto some symbol con icts but the alternative, a fully consistent notation, has rather extremeconsequences; denoting mole fractions by x will i.e. exclude the symbol x from the mathematicalformulae.The thermodynamic variables are referred to in the following material as either intensiveor extensive. A more precise classi�cation is due to Gri�ths et al. [19] where the variableswhich are identical in coexisting phases are denoted �elds. The counterpart to the �elds is thedensity variables. In the following, the term intensive variable is used only for quantities thattake on identical values in coexisting phases. This could be stated more precisely by denotingthe variables as �elds. However, when thermodynamic variables are divided into �elds anddensities, the constraint speci�cation in the thermodynamic computations will be nonlinear.For this reason, the classi�cation scheme in [19] is not adopted.

Page 22: Computation of phase equilibria in uid mixtures
Page 23: Computation of phase equilibria in uid mixtures

Chapter 2Theory2.1 Equilibrium thermodynamicsThe laws and equations governing thermodynamic equilibria may be stated in numerous ways.In the literature of chemical equilibrium thermodynamics, a common approach is to deduce theconditions of equilibria from the laws of thermodynamics. However, one of the earliest and stillmost concise formulation of a condition for thermodynamic equilibria is due to Gibbs [16]:POSTULATE For the equilibrium of any isolated system it is necessary and su�-cient that in all possible variations of the state of the system which do not alter itsentropy, the variation of its energy shall either vanish or be positive.Accordingly, the equilibrium condition is equivalent to an optimization problem, an approachpursued by Gibbs. The consequences of the postulate above is thoroughly discussed by Gibbs,but his discussion is unnecessarily voluminous. A postulate that reproduces all of Gibbs resultsis the following1:POSTULATE The internal energy of a homogeneous phase is a �rst-order homoge-neous function of its entropy, volume and mole numbers.COROLLARY The energy of a heterogenous phase assembly is the sum of energycontributions from each homogeneous phase.First-order homogeneous functions are considered on page 79, and by the mathematical prop-erties of such functions it is possible to write Euler's theoremU(S; V; n1; n2; : : : ) =@U@SS+ @U@V V+Pj @U@njnj= TS+(�P )V+Pj �jnjwhere U , S, V and nj are internal energy, entropy, volume and mole number of componentj, respectively. The partial derivatives of the internal energy have the physical interpretationstemperature, T , pressure, P and chemical potential of component j, �j. The last postulatecompleting the theoretical foundation of equilibrium thermodynamics is the non-negativity offundamental variables:POSTULATE The quantities entropy, volume and mole numbers can only attainnon-negative values.1In this short survey of theory, �rst-order homogeneous properties of the energy function is postulated. Inthe literature, see i.e. [8], this property is presented as a direct result of the additivity over homogeneoussubsystems. However, all extensive variables are additive over subsystems, and it is not clear how a speci�cfunctional relationship can be deduced from the additivity property.5

Page 24: Computation of phase equilibria in uid mixtures

6 Chapter 2: TheoryThe third law of thermodynamics guarantees the entropy to be positive at �nite temperatures,the non-negativity of volume and mole numbers are evident. Numerous corollaries of the threepostulates can be established. These are somewhat tedious to present in a general form, andthe presentation below is limited to elementary relations concerning thermodynamic systemswithout chemical reactions. Chemical reactions and exclusion of components from a phaseimposes linear constraints on the system. Details of such situations are described later. Thecriteria for several phases to coexist is found from the conditions of a minimum of a sum of�rst-order homogeneous functions, see Appendix D.3.2,T1 = T2 = : : : = TN = T ��P1 = �P2 = : : : = �PN = �P ��j1 = �j2 = : : : = �jN = ��j for all components j,for each of the N phases which are assumed to be present in the phase assembly. Furthermore,( Tk(Sk; Vk; n1k; n2k; : : : )�T � )Sk+ (�Pk(Sk; Vk; n1k; n2k; : : : )+P � )Vk+ Pi( �ik(Sk; Vk; n1k; n2k; : : : )� ��i )nik > 0for all possible phases k which are not present at equilibrium. The latter of these criteria isthe phase stability criterion, see [16, page 109]. Both criteria are the results of considerationsconcerning simple, closed systems. Other situations, like constant temperature or pressure spec-i�cation, may also be treated as minimization problems. By the properties of Legendre trans-formed functions2, a series of minimization problems can be set up, each of them correspondingto di�erent constraint speci�cation. By turning the notation for Legendre transformation, seeAppendix C.1 page 81, into symbols commonly used in connection with thermodynamics, one�nds the following minimization principles:Function Transform of With respect to Constraint speci�cationU S; V ;n1;n2;: : :H U V S;�P ;n1;n2;: : :A U S T ; V ;n1;n2;: : :...G U S;V T ;�P ;n1;n2;: : :G H S T ;�P ;n1;n2;: : :G A V T ;�P ;n1;n2;: : :... U S; n1;n2;: : : T ; V ;�1;�2;: : : A n1;n2;: : : T ; V ;�1;�2;: : :As can be seen from the table, there are alternative transformation routes to the energy func-tions which have two or more intensive variables as their fundamental variables. Since an energyfunction must be the function of at least one extensive variable, the total number of possibleenergy functions is PN+1i=0 �N+2i � = 2N+2 � 1 when a N -component system is considered. Thetable above indicates which energy function the energy extremum principle applies to at di�er-ent constraint speci�cations for the primal variables. This one-to-one correspondence betweenprimal variables and energy functions can be used to enlarge the number of constraint spec-i�cations in the equilibrium computations. It is pointed out by Gibbs [16, page 56] that the2The Legendre transformation is a pure mathematical technique which adds nothing new to the theory ofthermodynamic equilibria. The only purpose of performing the Legendre transformation is to obtain otherthermodynamic potential functions (H;A;G; : : : ) better suited for speci�c purposes than the internal energy U .

Page 25: Computation of phase equilibria in uid mixtures

Chapter 2: Theory 7energy extremum principle is equivalent to another extremum principle of the entropy. In sucha situation, the entropy should be considered as a function of internal energy, volume and molenumbers. This equivalency may be established merely by treating the entropy as an implicitfunction of the above mentioned variables and express variations of the entropy by derivatives inthe energy function formalism. By the properties of such implicit functions, see Appendices C.3and D.3.4, one �nds that a minimum of the energy corresponds to a maximum of the energyat positive temperature. However, such considerations are not restricted to internal energy andentropy; the principle applies equally well to all other extensive variables treated as implicitfunctions of the corresponding energy function. Some of the extremum principles that may beestablished are indicated in the table below.minimumS;V;n1;n2;::: U(S; V; n1; n2; : : : ) � maximumU;V;n1;n2;::: S(U; V; n1; n2; : : : ) if T > 0� maximumS;U;n1;n2;::: V (S; U; n1; n2; : : : ) if �P > 0� maximumS;V;U;n2;::: n1(S; V; U; n2; : : : ) if �1 > 0...minimumS;n1;n2;::: H(S;�P; n1; n2; : : : ) � maximumH;n1;n2;::: S(H;�P; n1; n2; : : : ) if T > 0� maximumS;H;n2;::: n1(S;�P;H; n2; : : : ) if �1 > 0...In the literature, the entropy formulation of these principles has received most attention. Theobject function in this case is denoted a Massieu function, and by appropriate Legendre transfor-mations a new series of extremum principles can be found. The concept of generalized Massieufunctions [8], establishes functions that typically have reciprocal intensive coordinates, ( 1=T ,1=(�P ), 1=�j, : : : ) ratios of intensive coordinates ( T=P , ��j=T , : : : ) and a (generalized)energy function as their natural variables.2.2 Computation of thermodynamic equilibriaThe modeling of thermodynamic systems and the subsequent computation of thermodynamicequilibria requires a numerical solution of the equilibrium conditions reviewed in the previoussection. Since there is a variety of alternate constraint speci�cations, it lies in the nature ofthermodynamic computations that it will in general be impossible to formulate a thermody-namic model in the same coordinates as the constraints are speci�ed in. Hence, one has toseek a method that is capable of handling both the constraint speci�cations of the problemand the mathematical model of the thermodynamic properties the best way. How to design atool for numerical computations therefore depends on how the thermodynamic model is repre-sented. Some thermodynamic models are reviewed in Appendix A and these models fall intothe following three categories:� Ideal models. The phase models ideal gas and ideal mixture share the property that theyde�ne convex energy-surfaces only. Such models do not exhibit intrinsic instabilities. Thesemodels have simple mathematical structure, e.g. the ideal gas model can be cast intoformulations that are explicit in either T; V;n, T; P;n or T; V;�.� Equation of state. Such models are explicit in the coordinates T; V;n. The mathematicalstructure of these models is still relatively simple, but it is impossible to derive closedexpressions in other coordinates.

Page 26: Computation of phase equilibria in uid mixtures

8 Chapter 2: Theory� Incompressible phases. These models do not have any pressure (nor volume) dependency,and they hence fail to model the internal energy properly.As can be seen, all the thermodynamic models considered have arguments in accordance withthe energy formalism, incompressible phases have coordinates in the Gibbs energy formalism,equations of states naturally belong to the Helmholtz formalism. Concerning cubic equationsof state, a common approach [21, 32] is to treat the model as T; P;n-dependent by the implicitrelation V = V (T; P;n). However, in such models V can, in general, not be a unique functionof T , P and n, and it has been experienced that special precautions are required in order toapply the implicit relation V = V (T; P;n). An alternative to transforming the model-variablesis to set up an optimization problem that is explicit in the model-variables. How this can bedone, is best illustrated by some examples.A situation where optimization principle and thermodynamic model has a mismatch invariables, is an equilibrium computation where the constraint speci�cations are T; P;n andthermodynamic model is an equation of state. Now, if the volume is incorporated intothe optimization problem, it has to be an unconstrained variable, and, as a consequence,the corresponding derivative must vanish at equilibrium. An object function providing theseproperties is A�(�P �)V since it has mole number derivatives in common with the unshiftedHelmholtz function and a volume derivative (�P )� (�P �) that vanishes at the equilibriumpressure P �.This method is not restricted to a shift in one intensive variable. E.g. for the constraintspeci�cation T; V;�, the appropriate shifted function is A���Tn. A slightly more complicatedsituation arises if some of the chemical potentials are �xed in a reacting mixture. As an example,let the system H2, O2, H2O be subject to constrains in the chemical potential of oxygen andthe total amount of hydrogen:At equilibrium, the chemical potentials are linearly related by24 �H2O�O2�H2 35 = 24 1 22 00 2 35� �1�2 �where �1 and �2 are (unknown) Lagrange multipliers. In the matrix above, the coe�cientscan be recognized as the number of elements per formula unit of the components. Now, bythe de�nitions �1 = 12��O2 and �2 = �, the linear equation is equivalent to24 �H2O�12��O2�O2 � ��O2�H2 35 = 24 101 35�The left-hand side of this linear system is identical to the gradient of an energy functionbeing composed of the terms (�H2O� 12��O2)nH2O+(�O2���O2)nO2+�H2nH2 . The derivativewith respect to nO2 vanishes at equilibrium, and nO2 enters the optimization problem as anunconstrained variable.A corresponding technique also applies when an energy function is among the constraintspeci�cations. An example illustrating this situation is the equilibrium computation at givenH;P;n assuming the model to be an explicit function of T; V;n.In this case the function U(S; V;n) def= U � (�P �)V = TS + �(�P ) � (�P �)�V + �Tn isde�ned. Now, by the properties of implicit functions, @S@V = 1T (P �P �) when S = S(U ; V;n).Hence, it follows that if the volume is an unconstrained variable in the extremum principle ofS, the corresponding derivative vanishes only if the pressure is equal to the speci�ed pressureP �. Furthermore, it is seen from the de�nition of U that U = H = H� at P = P �.

Page 27: Computation of phase equilibria in uid mixtures

Chapter 2: Theory 9Note, however, that the introduction of the arti�cial function U does not give any informa-tion on how to map (variations of) U ; V;n into the model variables T; V;n. On the other hand,the examples above demonstrate the following important feature of the extremum principlesrelated to equilibrium computations:In situations where the thermodynamic model is not explicit in the intensive variablesof the constraint speci�cations, an optimization principle in the corresponding extensivevariables of the thermodynamic model still exists.The concept of shifted surfaces applies when the constraint speci�cation involves an intensivevariable and the thermodynamic model is explicit in the corresponding extensive coordinate.There are also situations where the mismatch between constraint and model variables are ofthe opposite nature: The thermodynamic model is explicit in an intensive property but thecorresponding extensive coordinate is involved in the constraint speci�cation. With the ther-modynamic models considered here, this situation arises in all non-isothermal ash computationssince all the models are explicit in temperature. The transformation which enlarges the numberof extensive coordinates of a surface is explained in Appendix C.2, page 83, and the techniqueis here referred to as inverse Legendre transform.By the di�erent transformations introduced above, it is possible to formulate the equilib-rium computation as an optimization problem. In the most general case, see Appendix D.4, theoptimization problem readsoptimizex1; ::: ;xN NXi=1 fi(xi) subject to A� NXi=1 P Ti xi � b � = 0 (2.1)where fi, without exception, is a �rst-order homogenous function of xi. The various othersymbols in Problem (2.1) are explained below. The governing equations are the �rst-orderconditions of Problem (2.1), gi + P iAT� = 0 (2.2)for the i = 1 : : : N coexisting phases together with the constraint speci�cationA� NXi=1 P Ti xi � b � = 0 (2.3)where b is the vector describing the extensive coordinates of the system. In the �rst-orderconditions, gTi is the gradient with respect to the extensive variables xi of the fundamentalfunction for phase i, fi. A fundamental function here will be an energy function, a shifted energyfunction or any transform of such functions. The matrix A accounts for linearly dependentconstraint speci�cations, e.g. chemical reactions. To handle situations where the coordinates ofeach phase are not similar, i.e. when some of the components are not present in a phase, thematrices P i have to be introduced to rearrange the coordinate vectors to make the summationpossible. � is a vector of Lagrange multipliers. The role of A and P i is made clear in thefollowing example:The linear constraints of a reacting system composed of the species H2O, O2 and H2 atspeci�ed temperature and pressure can be written� 1 2 02 0 2 �� 24 100 35 � nH2O �+ 24 1 0 00 1 00 0 1 3524 nH2OnO2nH2 35� 24 n�H2On�O2n�H2 35 � = � 00 �

Page 28: Computation of phase equilibria in uid mixtures

10 Chapter 2: TheoryIt is here assumed that two phases can be present at equilibrium: One aqueous phase ofpure H2O, x1 = [nH2O]T, and a gaseous phase where all three components are present,x2 = [nH2O nO2 nH2 ]T. Furthermore, it is assumed that the thermodynamic models areexplicit functions of T and P such that iterative solution of the temperature and the pressureis not required. The equilibrium conditions, see Equation (2.2), will in this example be� �H2O �+ � 1 0 0 � 24 1 22 00 2 35� �1�2 � = � 0 � and 24 �H2O�O2�H2 35+ 24 1 22 00 2 35� �1�2 � = 24 000 35The other part of the equilibrium computation is to decide whether the phase assembly isthermodynamically stable. In terms of generalized coordinates, the stability criterion readsxj(gj + P jAT�) > 0(2.4)where � is the vector of Lagrange multipliers found by simultaneous solution of Equations (2.2)and (2.3). Equation (2.4) must be ful�lled for all possible phases j. One may note that Equa-tion (2.4) is derived from the conditions of a minimum of a sum of �rst-order homogeneousfunctions, see Appendix D.3.2, and the criterion applies only when the computation is minimiza-tion of energy functions. There is, however, no need to establish stability criteria in alternatecoordinates since the common intensive coordinates of the phases in the system, T;�P; �i : : :,always can be computed.2.3 Calculation of phase diagramsIn order to compute the equilibrium state subject to any arbitrary constraint situation, agree-ment between the constraint speci�cation and the problem variables is required. When thephase envelopes of a thermodynamic system is constructed, a set of solutions of the �rst-orderconditions is sought and it is not required that coordinates of the phase diagram are identicalto the variables of the fundamental equations of the phases. To outline this freedom of activevariables, one may consider three choices of coordinate sets:(i) The natural variables of the phase models,(ii) a set of generalized variables where the governing equations of phase boundaries may beformulated and solved, and(iii) the variables of the phase diagram.As shown in the previous section, there exists transformations which enable a phase model toserve as a base for a generic surface, and the sets (i) and (ii) above are independent from acomputational point of view. Transformations also exist between variable sets (ii) and (iii),and the lines of the phase diagram can, hence, be traced in generalized variables, the quantitiesto appear in the phase diagram can be obtained by a �nal transformation. The last step maybe considered as a post processing of the results.The equations de�ning phase envelopes are derived from the conditions of thermodynamicequilibrium. The conditions governing the boundary between N and (N + 1) phase regionsis outlined �rst. Inside as well as at the boundary of a (N + 1) phase region the �rst-orderconditions gi + P iAT� = 0(2.5)

Page 29: Computation of phase equilibria in uid mixtures

Chapter 2: Theory 11must be ful�lled for all of the i = 1 : : :N+1 coexisting phases. On the boundary between N and(N +1) phase regions, it is assumed that phase number N +1 vanishes. One way to state that aphase is at the stability point is to require that the N remaining phases ful�ll the constraints ofthe extensive coordinates of the system. However, since a phase diagram is a two-dimensionalprojection, the number of constraints must be reduced by two compared to the correspondingconstraints of an equilibrium computation:B( NXi=1 P Ti xi � b) = 0 (2.6)where B is obtained by erasing two rows in A. The number of unknowns in the simultaneoussolution of the �rst-order conditions (2.5) and the constraint speci�cation (2.6) are two morethan the grand total number of equations. In addition, the phase left out from the constraintspeci�cation is assigned a �nite size, i.e.eTN+1xN+1 � cN+1 = 0 (2.7)where eN+1 and cN+1 are constants. The Equations (2.5), (2.6) and (2.7) together form asystem with one degree of freedom where the complete set of solutions x1; : : : ;xN ;� is thephase envelope in generalized coordinates.As an example of how Equations (2.5) to (2.7) are used in the computations, consider theconstruction of a pressure composition diagram of a binary mixture of �ctitious componentsA and B. For simplicity reasons, only a two-phase envelope is considered and it is assumedthat the thermodynamic model is given in terms of temperature, volume and mole numbers.However, in order to make the example a bit more complicated one of the coexisting phasesis assumed to be pure component A. The temperature is held constant, and the coordinatesof the two phases are x1 = � nAV �Phase 1 and x2 = 24 nAnBV 35Phase 2Note that the phase volumes are amongst the primary variables in the phase envelope con-struction. The intention is to compute a pressure composition diagram, but the internalvariables of the algorithm are, without exception, extensive coordinates. The transposedgradients corresponding to x1 and x2, i.e. the �rst-order derivatives of the Helmholtz poten-tials, are g1 = � �A�P �Phase 1 and g2 = 24 �A�B�P 35Phase 2Furthermore, since A = I in the constraint speci�cation for non-reacting systems, the equi-librium conditions are, see Equation (2.5),� �A�P �Phase 1+ � 1 0 00 0 1 �24 �1�2�3 35 = � 00 � and 24 �A�B�P 35Phase 2+24 1 0 00 1 00 0 1 3524 �1�2�3 35 = 24 000 35When a Px diagram is constructed, there are few restrictions in the choice of the matrixB and the constraint vector b in Equation (2.6), i.e. by specifying the active constraintaccording to � 1 0 0 �8<:24 1 00 00 1 35� nAV �Phase 1 � 24 n�An�BV � 359=; = � 0 �

Page 30: Computation of phase equilibria in uid mixtures

12 Chapter 2: Theorythe mole number of component A in phase 1 is forced to be equal n�A at the phase boundary.In this example, Phase 2 is interpreted as a phase vanishing at the phase envelope but thephase is assigned a �nite size in the computation scheme, see Equation (2.7). A reasonablephase size is e.g. c2 = 1 mol, and by using e2 = � 1 1 0 �T, Equation (2.7) imposes thatthe total mole number of Phase 2 is constant.It is straightforward to also set up the equations that apply on the boundaries when severalphases vanish simultaneously. When M phases vanish simultaneously, the �rst-order conditionsgi + P iAT� = 0 must be ful�lled for i = 1 : : :N +M . The appropriate matrix B is found byerasing M + 1 rows in A, and, �nally, the size of the M vanishing phases are kept �nite byrequiring eTN+1 xN+1 � cN+1 = 0eTN+2 xN+2 � cN+2 = 0...eTN+MxN+M � cN+M = 0(2.8)The solution set of Equations (2.5), (2.6) and (2.8) is the phase diagram. The phase diagramcan alternatively be de�ned in terms of di�erential equations. Straightforward di�erentiationof Equations (2.5), (2.6) and (2.8) yields,dd t� gi + P iAT� � =H i _xi + P iAT _� = 0 for i = 1 : : :Ndd t�B( NXi=1P Ti xi � b) � = B NXi=1P Ti _xi = 0dd t� eTjxj � cj � = eTj _xj = 0 for j = N + 1 : : :N +MwhereH i =rxigi. In order to locate consecutive points on the phase envelope, it was found thata predictor-corrector scheme using Euler's predictor formula was an e�ective solution method.To apply this method, the tangent _x1; : : : ; _xN ; _� de�ned at the boundaries of the phase diagramand the derivatives of the vanishing phases, _xN+1; : : : _xN+M must be computed, see Appendix E.2

Page 31: Computation of phase equilibria in uid mixtures

Chapter 3Existing methods3.1 Computation of thermodynamic equilibriaThe extent of literature describing computation of thermodynamic equilibria is considerable.One way to get an idea on both the volume of relevant literature and the common approachin such calculations is to perform some kind of computerized literature search. A search in adata base restricted to literature published the last ten years, using keywords \Gibbs energy"and \minimization", provided close to 1000 references. It is, hence, impossible to review thisinexhaustible source of literature, but some milestones in the development of computationaltools can be mentioned.The earliest proposals on how to perform chemical equilibrium computation date backto the year of the �rst digital computer. In 1947, Brinkley [7] published an algorithm forcalculating the equilibria of multiphase systems where also the possible non-ideality of thephases is discussed. An often cited paper by White et al. [63] appeared in 1958. This paperdemonstrated the advantages of formulating the governing principle as a minimization probleminstead of a system of nonlinear equations.During 1960 and 1970, attention was drawn towards the computation of phase equilibriain nonideal, non-reacting systems. The isothermal ash problem discussed by Michelsen [32] isregarded as one of the reference works in computation of uid phase equilibria. The computationof phase equilibria at constraint speci�cations di�erent from constant pressure and constanttemperature has also been considered by Michelsen [34]. In [34], the isenthalpic and isentropic ash problem is discussed. However, the Euler homogeneous nature of the thermodynamicfunctions is not exploited by Michelsen, and it seems di�cult to pursue the strategies outlinedin [34] to other, more general constraint speci�cations.A more general approach to equilibrium computations is described by Haug-Warberg [21].By exploiting the mathematical properties of the thermodynamic functions, Haug-Warberg de-veloped an algorithm solving equilibrium problems involving alternate constraint speci�cations.Both chemical reactions and phase equilibria are considered in [21].In recent years, the development of powerful computers have enabled more robust methodsin the computation of phase and chemical equilibria. Computer-intensive strategies like globalminimization and continuation methods have received considerable attention, such methods arereviewed by Seider [51].After �ve decades of research, there is, however, no sign of settling on a generally acceptedway to perform equilibrium computations. The current state of the art is precisely depicted byKarpov et al. [24] in a list of crucial questions that require additional e�orts1:1Item 2 and 3 are abbreviated. 13

Page 32: Computation of phase equilibria in uid mixtures

14 Chapter 3: Existing methods1Choice of a convenient and constructive symbolic notation and description of the struc-ture of thermodynamic models.2Explicit analytical notation of the necessary and su�cient conditions of equilibrium inmulticomponent, multiphase, and multiaggregate systems that allow aqueous electrolyte,gas mixtures, liquid hydrocarbons, single-component minerals, and mineral solid solu-tions, melts, et cetera to exist simultaneously, ...3Development of a reliable algorithm for equilibrium calculations as an \engine" of acomputer technology for modeling physico-chemical processes. ...3.2 Phase diagram constructionConstruction of phase envelopes for multicomponent uid mixtures has been studied byMichelsen [30]. In [30], both the mathematical foundation and the details on the implementationof the algorithm are reported, but the algorithm is limited to two-phase equilibrium in non-reacting, multicomponent2 systems. Michelsen later extended the theory to enable computationof 2-phase/3-phase boundaries, see [33]. The equations that apply at the phase boundaries, arein [33] formulated in terms of equilibrium factors and fugacity coe�cients. By using equilibriumfactors, the governing equations become unnecessarily complicated, and the level of complexitywill increase if phase boundaries with a higher number of coexisting phases are resolved byMichelsen's method.Nghiem et al. [38] describe a more general method for phase diagram construction. In [38]it is shown that di�erent types of phase diagrams can be computed by rearranging the primalvariables of the algorithm.An algorithm for the construction of diagrams of systems possibly containing solid phases isdescribed by Connoly et al. [9]. This reference clearly illustrates the major di�erence between thecomputations of phase diagrams of uid systems and material systems. In the latter situation,an additional combinatorial problem must be resolved since a high number of condensed phasescan possibly be present at equilibrium.3.3 Stability testingThe question on how to decide whether a phase is thermodynamically stable or not, did notreceive much attention in the �rst decades of thermodynamic equilibrium computation. Theimportance of stability testing seems to be rediscovered by Baker et al. [4] who proved a seriesof theorems on Gibbs energy tangent plane analyses3. One of the earliest investigations on howto resolve the stability problem numerically, is due to Michelsen [31]. The algorithm proposedin [31] utilizes di�erent initial estimates in the search for the global minimum of the Gibbsfree energy of mixing. Trangenstein [61] applied a method that, to some degree, eliminates theneed for initial estimates in the stability test. In Trangenstein's work, a de ation techniqueoriginally proposed by Goldstein et al. [17] is utilized to prevent trivial solution of the phasestability problem. Besides being an excellent paper, [61] is, thus, one of the earliest works that2The system of equations that are solved during construction of the phase envelope in [30] is based onequilibrium factors (\K-values"). In a two-phase one-component system the equilibrium factor is equal to one,and the Jacobian matrix applied in [30] is singular. Hence, \multicomponent" is a prerequisite in this algorithm.3The results presented in [4] were already known by Gibbs [16]. Furthermore, in these two alternativeformulations of the conditions for thermodynamic stability, the one due to Gibbs is of a much more generalnature.

Page 33: Computation of phase equilibria in uid mixtures

Chapter 3: Existing methods 15applies a technique with the potential of performing global minimization. The algorithm shownin [61] is, however, restricted to two-phase systems4.Homotopy-continuation methods in general have been reviewed by Seider [51]. In connec-tion with stability test problems, homotopy-continuation methods have been studied by Sunet al. [60]. The approach chosen in [60] is based entirely on the minimization of a tangent planedistance at a speci�ed temperature and pressure. The search space of the trajectory methodis thus restricted to the mole fraction plane. This problem formulation imposes some potentialproblems in the continuation method. There will inevitably be situations where the pressureequation has several roots, and in such cases the derivatives of the tangent plane distance ceaseto be continuous. The strategy proposed by Sun et al. depends heavily on the initial estimateof the composition at stationary tangent plane distance. However, the results reported by Sunet al. are compelling. All states with stationary tangent plane distance are located for a varietyof mixtures with complex phase behavior.Interval analysis has been applied to the stability problem by Hua et al. [23]. The theoryof interval analysis provides a mathematical guarantee that the optimum can be located, themethod proposed by Hua et al. is, hence, initialization independent. In [23] all examples arebased on cubic equation of state models. There are, however, no assumptions made with respectto model speci�c properties and the method proposed in [23] may be utilized on virtuallyany phase model. The equations describing the tangent plane distance in [23] are formulateddi�erently from the common approach. Hua et al. elegantly avoids any problems with non-smooth partial derivatives and multiple pressure roots merely by regarding the pressure formof the equation of state as a separate equation and performing the interval analysis in terms ofmole fractions and molar volume5.3.4 Trajectory methodsAlgorithms for minimization of functions with relevance to stability tests in computation ofphase equilibria, have been presented by i.e. Trangenstein [61] and Michelsen [31]. The problemof �nding the global minimum of a general function, however, has been approached in a numberof di�erent ways. The more mathematically oriented literature [13, 14, 27, 37] describes severalinteresting strategies, and such methods may also be suited for the phase stability problem.The ultimate goal of the phase stability problem is the global optimization, and one widelyconvergent method, the trajectory method, seems adequate for the problem.Trajectory methods are also referred to as Davidenko path methods or continuation meth-ods, and they aim to enlarge the region of convergence in Newton methods by transformingthe original problem into a sequence of subtasks that are more easily solved. According toFletcher [15], the foundation of a trajectory method is to construct a parameterized systemh(x; �) which satis�es h(x; 0) = g(x) and h(x1; 1) = 0 for the original nonlinear system ofequations g(x) = 0. The equation above is the �rst-order necessary conditions for an optimumif g is the gradient of the object function.4The method described in [17] has some pros and cons. In the stability test problem, it is, at least in principle,possible to apply the method also when the stability function has several optima. In such situations, recursivede ation of the object function yield an algorithm of astonishing beauty. This is a typical \pro". The argumentagainst the method is that it does not work, see i.e. [13] where it is explained that locating the optimum of ade ated function is not easier than performing global minimization of the untransformed function. The methodcan, however, be valuable as a �rst trial in the phase stability test.5In [23], the stability criterion is based on the distance from tangent plane to Gibbs energy surface of mixing.By utilizing the corresponding tangent plane distance in the Helmholtz formalism, a speci�c pressure is notrequired. The dimensionality of the problem, in terms of number of equations, will then be slightly reduced.

Page 34: Computation of phase equilibria in uid mixtures

16 Chapter 3: Existing methodsThe most intuitive construct is probablyh(x; �) = g(x)� �g(x1) = 0(3.1)Successive solutions of Equation (3.1) with decreasing � will, at � = 0, give the solution ofg(x) = 0. Equation (3.1), with the parameter � 2 [0; 1], de�nes a trajectory from the initialpoint, x1, to a stationary point of the object function. However, to locate the global minimum,all stationary points of the object function must be located. In this respect, a considerableimprovement of the Davidenko trajectory concept has been suggested by Branin [6, 27]. Thefoundation of Branin's method is to de�ne the trajectory by a di�erential equation, and thetrajectory should in principal run through all stationary points of the object function.The governing equations in [6] are closely related to Equation (3.1). With rxg = H,the derivative with respect to � of Equation (3.1) is Hdx=d� = g(x1) = ���1g(x). Thisdi�erential equation is cast into an autonomous system by the substitution � = exp(�t):H _x = �g where _x = dxd t(3.2)During integration, the sign of �g in Equation (3.2) is altered when the trajectory passes a pointwhere H is singular. In other words, the Newton direction is reversed outside regions where His positive de�nite. Integration of Equation (3.2) can be done with arbitrary degree of accuracysince the analytical solution is known in terms of the gradient, Equation (3.1). Experimentalresults reported by Branin [6] show that continuation methods may be extremely powerful. Itis demonstrated that the method is capable of locating all extrema of a variety of test problems,and it seems worthwhile to investigate trajectory methods for the phase stability test problemtoo. However, it is well known that Branin's method has some aws. The method is di�cultto implement [13, 14] due to singularities in Equation (3.2), and examples revealing non-globalconvergence have been reported.

Page 35: Computation of phase equilibria in uid mixtures

Chapter 4Algorithms4.1 Computation of phase and reaction equilibriumThe equilibrium computations are performed by a second order Newton method. Both thetheory and implementation of this method is straightforward, the steps of the algorithm thatrequire special attention is the inclusion and removal of phases during iteration. Furthermore,it can be shown that the second order convergence properties of the Newton scheme are alsoobtained when the object function is a sum of generic, thermodynamic surfaces.4.1.1 Transformation of thermodynamic surfacesIn the most general case, the required input to the algorithm is made up of a constraint speci�-cation and a set of phase models. The main feature of the phase model is its ability to constructenergy surfaces. An instance of a surface is throughout this section referred to as a phase.However, in order to explain how the algorithm works, some additional terms must be clari�ed.First, a surface constructed by a phase model is called a basic surface. Basic surfaces are calcu-lated in the natural variables of the phase models. A basic surface may have coordinates thatare incompatible with the constraint speci�cation, and transformed surfaces are hence required.Accordingly, some kind of classi�cation of the surfaces must be established in order to �nd aset of surfaces that can serve as the foundation of the optimization problem. In this respect, anotation for the transformed thermodynamic functions is shown in Table 4.1.Table 4.1: Notation used for transformed thermodynamic functions. In the de�nition of theshifted surface, it is assumed that f is a homogeneous function of x with gradient rxf = gT.Legendre transform L[r] (u(r; t)) = v(s; t), see Appendix C.1.1Inverse Legendre transform L-1[s] (v(s; t)) = u(r; t), see Appendix C.2Massieu function P[r] (u(r; t)) = r(u; t), see Appendix C.3Shifted surface S[g�]( f(x) ) = xT(g � g�)By the notation in Table 4.1, it is possible to characterize the basic energy surfaces as Legendretransforms. As an example, two phase models with natural coordinates T; V;n and T;�P;n,17

Page 36: Computation of phase equilibria in uid mixtures

18 Chapter 4: Algorithmsrespectively, can construct the following basic surfaces:Functional form Classi�ed as Required constraintsA(V;n j T ) A(V;n) TA(T; V;n) L[S]U(S; V;n)G(n j T;�P ) G(n) T;�PG(T;n j �P ) L[S]H(S;n) �PG(�P;n j T ) L[V ]A(V;n) TG(T;�P;n) L[S;V ]U(S; V;n)One may note that only the Legendre transform is required to classify the basic surfaces. Fur-thermore, it is seen that only the extensive coordinates S; V; n1; n2 : : : appear in the classi-�cation scheme. Thus, the basic surfaces can be classi�ed merely by stating their extensivecoordinates and the transformed coordinates, the actual name of thermodynamic function, U ,G, H etc., is irrelevant.The classi�cation scheme for thermodynamic surfaces can also be used to specify the con-straint type of the equilibrium computation: The constrained variables in the computation canalways be identi�ed as the coordinates of a generalized thermodynamic function. To specifyan arbitrary thermodynamic function, i.e. either a generalized energy function or a generalizedMassieu function, one addition transformation is required. By the transform P in Table 4.1,it is possible to characterize an arbitrary function in terms of a transformed energy function.Some of the most important object functions in equilibrium computations can be summarizedas follows: Constraint speci�cation Object function Characterized asS ; V ;n U U(S; V;n)S ;�P ;n H L[V ]U(S; V;n)H ;�P ;n S P[S](L[V ]U(S; V;n))U ; V ;n S P[S]U(S; V;n)By the common classi�cation of the basic surfaces and the constraint type, it is possible to�nd transforms of the basic surfaces such that the set of most derived surfaces conform to theoptimization problemoptimizex1;:::;xN NXi=1 fi(xi) subject to A� NXi=1 P Ti xi � b � = 0(4.1)The structure and number of non-zero elements of the constraint matrix A depends on whetherthe thermodynamic system is reacting or non-reacting. In the problem setup, chemical reac-tions are most conveniently speci�ed by linear constraints that are decoupled from the rest ofthe constraint speci�cations. Chemical reactions are incorporated into the problem by linearconstraints in the mole numbers, R� NXi=1 pTi ni � n� � = 0(4.2)where R is the formula matrix.As an example of R in Equation (4.2) consider again the reacting mixture of H2O, O2 andH2. The linear constraints are:� 1 2 02 0 2 �� 24 100 35� nH2O �+ 24 1 0 00 1 00 0 1 3524 nH2OnO2nH2 35� 24 n�H2On�O2n�H2 35 � = � 00 �

Page 37: Computation of phase equilibria in uid mixtures

Chapter 4: Algorithms 19and the matrix R equals �12 20 02�.A matrix R equal the identity matrix corresponds to phase equilibrium computation of a non-reacting system. In alternate constraint speci�cations, the constraint matrix must be modi�ed,but it is still possible to specify all possible reactions by a proper R-matrix. The constraintmatrix in the general case, see Equation (4.1), can be calculated by taking into account thetransforms de�ning the object function. When the chain of transformations is traversed fromright to left, the following two rules apply:C1 If the object function is untransformed, compute A = ASVn = 24 1 0 0T0 1 0T0 0 R 35.C2 If the object function is a Legendre transform, modify A to account for shifted surfaces.In an algorithm, the steps C1 and C2 are conveniently implemented by recursion. Step C2is explained in Section 5.2.1. One may note that modi�cation of A is not required to handleMassieu functions.Similar to the constraint matrix, the individual surfaces that enter the optimization problemmust be cast to suitable forms. First, one basic surface is constructed for each of the phase-models. The actual type of basic surface constructed depends on the constraint speci�cation.In situations where intensive properties are constrained, it may be possible to avoid unnecessarytransforms of the basic surfaces. As an example, consider the basic surfaces constructed by aphase model of natural coordinates T; V;n. In computations at constant temperature speci�ca-tion, the appropriate basic surface is A(V;n). If the temperature is not known in advance, thebasic surface will be L[S]U(S; V;n).The �rst step in the overall transformation of the basic surfaces is to eliminate inten-sive coordinates. This is required since the governing principle of the equilibrium computa-tion is optimization of a sum of �rst-order homogenous functions, and an intensive coordi-nate amongst the variables excludes homogeneity in the entire variable set. Thus, for thebasic surface L[S]U(S; V;n), the appropriate mapping is the inverse Legendre transform yield-ing U(S; V;n) = L-1[T ]A(T; V;n). After similar transformations on each basic surface, the derivedsurfaces will all be �rst-order homogeneous functions.Any further transformations depend on the constraint speci�cation. When the objectfunction is de�ned in terms of a series of transforms of U(S; V; n1; n2; : : : ), it is straightforwardto �nd the most derived surfaces f1; f2; : : : that enter the optimization problem. By traversingthe chain of transformations in the de�nition of the object function, each derived surface fi canbe transformed to proper form by the following three rules:S1 If the object function is untransformed, �nd P i by comparing the coordinates of the objectfunction and the coordinates of the basic surface.S2 If the object function is a Legendre transform, transform the surface to a shifted surface.S3 If the object function is a Massieu function, transform the surface by permuting functionand Massieu-transformed coordinate.Recursion is also here a powerful technique, see Figure F.1 on page 109 for an example on howto implement the overall transformation.

Page 38: Computation of phase equilibria in uid mixtures

20 Chapter 4: Algorithms4.1.2 InitializationAn initial phase assembly is required for the Newton iteration scheme. In case the optimizationvariables coincide with the variables of the thermodynamic model, e.g. computation of reactionequilibria at constant temperature and pressure speci�cation with models implemented as Gibbsenergy surfaces, the initialization stage may be formulated as a sequence of linear programmingproblems, see [21] and [52]. However, in the general case, there are no linear relations to exploit,and the basic surfaces are given an initial state without invoking any separate initializationscheme. After the basic models are initialized, it is possible to compute the corresponding initialcoordinates x0i of all the thermodynamic surfaces that may appear in the optimization problem.Due to the homogeneity property of extensive thermodynamic coordinates, these coordinates canbe scaled, and the initial phase assembly is chosen as the solution of the quadratic programmingproblem minimize�1; ::: ; �M ������ diag(Ab)-1A� MXi=1 P Ti x0i�i � b � ������2 subject to �i > 0(4.3)The solution of Problem (4.3) corresponds to the least number of phases that possibly canful�ll the constraint speci�cation. A scale factor �j = 0 implies that phase j is removed fromthe assembly. For non-zero scale factors, the coordinates of a phase i is updated according tox1i �i x0i .4.1.3 Solution of the �rst-order conditionsThe initialization starts with a subset of possible surfaces that may ful�ll the constraints spec-i�cation, and the �rst-order necessary conditions of an optimum of a system of �rst-orderhomogeneous functions is solved by Newton's method. The calculation of the Newton step isdiscussed in Appendix D.4. However, the iteration formulae in Appendix D.4 is establishedunder the assumption of linear constraints. It is hence not evident that this iteration formulaapplies equally well in the generic situation where the governing principle is either maximiza-tion or minimization subjected to nonlinear constraints in the variables of the thermodynamicmodels.By a Taylor expansion of the linear constraints and the �rst-order conditions, it is possibleto demonstrate that the computation of the Newton step according to Equation (D.22) or Equa-tion (D.29) and subsequent mapping of the Newton direction does not hamper the convergenceproperties of the Newton method. The general �rst-order conditions are, see Appendix D.4,gi +P iAT� = 0 8 i = 1 : : :N; N = number of coexisting phases, and the constraints readA�PNi=1P Ti xi � b � = 0. To avoid writing endless ellipses, only the situation N = 1, P i = I isconsidered. In terms of variables of the governing optimization principle, the expansion of the�rst-order condition can be written1� g(x+ �x) +AT(�+ ��)A(x+ �x� b) � = � g(x) +AT�A(x� b) �+ � H ATA O � ��x���+ � � �(4.4)In Equation (4.4)H is the Hessian rxg. Furthermore, Equation (4.4) is identical to a Newton-Lagrange scheme when the left-hand side equals the zero-vector. In computing the equilibriumstate in the general case, the variable x of the governing principle is some (nonlinear) transformof the coordinates of the underlaying thermodynamic model. By the implicit relation x = x(y),1Indices on x and g are left out.

Page 39: Computation of phase equilibria in uid mixtures

Chapter 4: Algorithms 21the corresponding Taylor expansion in terms of y is� g(y + �y) +AT(�+ ��)A(x(y + �y)� b) � = � g(y) +AT�A(x(y)� b) �+ � H ATA O � � ryx OO I � ��y���+ � � � (4.5)Similar to the expansion in terms of x, the Newton step in the untransformed coordinates,�y, is obtained by assigning the zero-vector to the left-hand side of Equation (4.5). Hence, bycomparing the two systems of equations, it is seen that the Newton step in the two alternatecoordinate sets are related by �y = (ryx)-1�x =rxy �xThere is, of course, no restriction on the number of transforms in the route leading from thecoordinates of the thermodynamic model to the variables of the optimization problem. For twotransforms, i.e. x = x(y(z)), the di�erent Newton steps are related by�z =ryzrxy �x =ryz �yOne should note that the computed Newton step in terms of the coordinates of the untrans-formed model is exact2, irrespective of the number of transforms in the chain. Without theknowledge of the foundation of Newton-like iteration formulae, one may be tempted to set upan optimization problem with nonlinear constraints. This strategy will, however, be less appeal-ing since the Hessian of each individual constraint will appear in the Newton-Lagrange scheme.Secondly, the Newton direction will depend on the Lagrange multipliers and an additional,nontrivial stage of initialization will then be required.Another nice feature with the concept of modeling thermodynamic surfaces as a sequenceof transformations is that the computation is split into a series of small, well de�ned subtasks,see Appendix F for suggestions on how to model thermodynamic surfaces and transforms ofthermodynamic surfaces by a high-level computer language.Hitherto, only the computation of the Newton step has been discussed. The optimizationliterature, however, contains several modi�cations of the Newton method. Amongst others,two widely used technics are step length adjustment and modi�cation of Hessian matrices [15].In minimization problems, the Newton direction is guaranteed to be descent if the Hessian ispositive (semi)de�nite. It is also possible to show that the computed direction is descent ifthe Hessian in the Newton scheme is replaced by positive (semi)de�nite matrices. To replaceinde�nite Hessians with positive semide�nite matrices in the computation of thermodynamicequilibria seems quite hazardous. In situations where the phase assembly has fewer phasesthan the equilibrium assembly, the states solving the �rst-order conditions may all be in regionswhere some Hessians of the individual surfaces are inde�nite. The Newton method is successfullyterminated only if the �rst-order conditions are ful�lled, and hence, if the Hessians matricesare forced to be positive (semi)de�nite, the modi�ed Newton method may diverge or at leastloose it's second order convergence property. This is highly undesirable, and modi�cations ofHessians are not performed for this reason.The other technique, step length adjustment, enlarges the convergence region of Newtonmethods considerably. In connection with constrained optimization, a possible merit functionfor the computation of step length is some norm of the residual of the �rst-order conditions.It is shown [28] that the Newton direction is a descent direction for the square sum of theresidual. It is also trivial to verify that any weighted square sum shares the same property, see2By \exact" it is here meant \no additional approximations are involved". The result �z = ryz �y is byno means unexpected, but without the analysis, the substitution �z = ryz �y would indicate that a �rst-orderapproximation is involved in a second order method.

Page 40: Computation of phase equilibria in uid mixtures

22 Chapter 4: AlgorithmsAppendix D.2. From this knowledge, there are several candidates for weighting factors. Onechoice that was found suitable is the merit functionm(�) = ���� diag(�)A� NXi=1 P Ti xi(yi + � �yi)� b � ����2+ NXi=1 ���� diag(xi) ( gi(yi + � �yi) + P iAT� ) ����2(4.6)In Equation (4.6), the individual terms can be recognized as the elements of the right-handside vector of the Newton-Lagrange scheme, see Equation (D.22). These are residuals of the�rst-order conditions evaluated at a fraction � along the Newton step. The step in the Newtondirection is, however, performed in the coordinates of the untransformed thermodynamic sur-faces. In Equation (4.6), this is indicated by the functional relations xi = xi(yi) and gi = gi(yi).The merit function does not depend on the update of the Lagrange multipliers ��, but theelements of � are included as weighting factors. Due to the linear constraints, the value of theLagrange multipliers can always be chosen such that �� = 0 which makes �, as it appears in themerit function, unambiguous. One should note that the merit function applies equally well inboth minimization and maximization problems since only the �rst-order conditions are solvedin this part of the computation.To compute the step-length, the merit function (4.6) is minimized by Brent's method [42].An exact minimization is not sought, and Brent's method is used to isolate the minimum �� toa fractional precision of 120 . However, su�cient close to the solution of the �rst-order conditionsthe step-length should be unit. To eliminate the e�ect of an inaccurate minimization of themerit function in the vicinity of the solution, a step-length � = 1 is chosen if j�� � 1j < 120 .One of the problems that arise by formulating the equilibrium computation as a genericoptimization problem, is the risk of having a poorly scaled problem. It is also di�cult to �nda reliable convergence criterion that applies at all constraint speci�cations. The variables mayvary by several orders of magnitude, and it is not evident how to decide when the �rst-orderconditions and the constraint speci�cation are ful�lled simultaneously. Hence, in order to notterminate prematurely, the Newton iteration is run until maximum accuracy is obtained. Thetest for maximum attainable accuracy is due to Dahlquist et al. [11], see also [61]. Accordingto [11], the iteration is terminated after an increase in the norm of the Newton step. Byexperience, this is found to work perfectly since the Newton steps will uctuate randomly whenthe limiting accuracy is reached.4.1.4 Updating the phase assemblyThe equilibrium state is located when the �rst-order conditions are satis�ed, and all phases,both possible phases and phases present in the assembly, satisfy the stability criterion. Theiteration sequence outlined in Section 4.1.3 will, in general, not terminate at the equilibriumstate, and the phase assembly must be rearranged and a new Newton iteration started.Such situations can occur in at least two ways3. First, the size of a phase can approach zeroin the Newton iteration. This divergence is easily recovered since the phase can be removed fromthe iteration scheme without signi�cantly enlarging the residual in the constraints. When to3Formally, there exist other situations where the Newton scheme will diverge. If the vectors P 1x1 : : :PNxNare linearly dependent, the Newton iteration will diverge due to singularity in Equation (D.22). Equation (D.22)will be singular also if any of the Hessians Hi has corank greater than one (critical points, mechanical spinodalcurves, chemical spinodal curves etc.). These kinds of singularities have, however, not been experienced inpractice.

Page 41: Computation of phase equilibria in uid mixtures

Chapter 4: Algorithms 23exclude a phase from the assembly is decided by monitoring the maximum, feasible step that canbe taken along the Newton direction. The e�ect of a nearly vanishing phase k will dominate left-hand side of the Newton-Lagrange scheme since the elements ofHk approach in�nity. Hence, ifa nearly vanishing phase is far from equilibrium, only a short step can be taken along the Newtondirection before a model dependent non-negativity constraint is violated. In the computations,a phase is removed if the maximum step length is less than a speci�ed threshold. A thresholdas low as 10�5 ensures that the phase is not removed prematurely.The second situation that require adjustment of the phase assembly is when a convergedsystem is not at the global optimum, i.e. some phase in the assembly is either intrinsic unstableor perhaps metastable. The way the algorithm handles the two kinds of instabilities di�ersconsiderably and the discussion of updating a metastable phase assembly is postponed untilSection 4.1.6.Intrinsic instability may be inspected by enumeration of positive and negative eigenvalues ofthe Hessians H i. An inde�nite H i implies intrinsic instability irrespective of what transformsof thermodynamic surfaces that are parts of the optimization problem. When H i is neitherpositive semide�nite nor negative semide�nite, no conclusions can be drawn without additionalknowledge of the optimization problem. In minimization problems, i.e. when thermodynamicsurfaces are energy functions, a phase i characterized by surface fi will be intrinsically stableif H i is positive semide�nite. It is, however, possible to derive the required information onthe signature4 of each Hessian from results already obtained during the computation of theNewton step. Inverted rank-one updates of Hessians de�ned by fH i = H i + efi -1 egiegTi must becomputed in order to apply Equation (D.29), and attempted Cholesky factorizations of eachfH i are, therefore, already computed. To establish the relation between �(H i) and �(fH i), onemust, however, take into account that the sign of efi in uences the eigenvalues of the rank-oneupdated matrices. By the interlocking eigenvalues lemma [28], one has:�(fH i) = (�; �; �) , �(H i) = ( (� � 1; � + 1; � ) if efi > 0(�; � + 1; � � 1) if efi < 0A Hessian H i will hence be positive semide�nite for efi > 0 ^ � = 0 _ efi < 0 ^ � = 1, negativesemide�nite for efi>0 ^ �=1 _ efi<0 ^ �=0.After inspecting the number of positive and negative eigenvalues of the Hessians, unstablephases are replaced by stable ones in the iteration scheme. Stable phases are most convenientlylocated in terms of the natural variables of the basic surfaces. For each intrinsic unstable phase,two stable ones are located by searching in both directions of the negative curvature of the localHessian. The trial phases are located by a combination of steepest descent and Newton's method,and the search is terminated at stationary tangent plane distance. The exact minimization ofthe phase stability test function is somewhat expensive. It may also seem directly wasteful sinceseveral of the minimizations may converge to the same state. However, this strategy ensuresthat the trial phases are separated by inde�nite regions. On the other hand, the phases returnedfrom the stability computation can, in general, not be included in the iteration without violatingthe constraint speci�cation. Analogously to the initialization of the equilibrium computation,the residual of the constraints can be reduced by solving QP-problem (4.3).4The signature a symmetric matrix A is de�ned by �(A) = (�; �; �) where �, � and � are the number ofpositive, zero and negative eigenvalues of A, respectively. In terms of the signature, Sylvester's law of inertia,see [55], can be summarized as �(CACT) = �(A) where C is a square matrix with corank 0.

Page 42: Computation of phase equilibria in uid mixtures

24 Chapter 4: Algorithms4.1.5 Initialization of phase stability analysisThe phase stability criterion shown in Appendix D.3.1 is derived from the conditions of globaloptimum of a system identical to that now being solved. In terms of the variables of theoptimization problem, the stability criterion readsxj(gj + P jAT�) > 0(4.7)for all possible phases j not present in the assembly. The Lagrange multipliers are known at endof iteration, and stability testing can, in principle, be performed in coordinates compatible withthe constraint speci�cation. This, however, is not necessary since the phase stability problemcan be resolved in any set of coordinates. The set of coordinates best suited is undoubtfullythe natural variables of the untransformed surface. The only disadvantage by performing thestability test in alternate coordinates is that the corresponding Lagrange multipliers must becalculated. On the other hand, this computation is trivial since all intensive variables in theS; V;n formalism are either �rst-order derivatives or natural coordinates of the untransformedsurfaces. Thus, in S; V;n coordinates, the counterpart to the overdetermined systemg1 + P 1AT� = 0g2 + P 2AT� = 0...is guaranteed to have a solution. Intensive coordinates needed in order to test stability arehence found as [ T � �P � ��T ]T = �ATSVn�SVn where �SVn is i.e. the least square solution.4.1.6 Update of a metastable phase assemblyIf the converged system is metastable, i.e. one trial phase with a negative tangent plane distanceis located, the stability search is terminated and the phase is included in the assembly. It turnsout that this update of the assembly must be done in two distinct ways depending on thenumber of phases already present in the system. This can be seen from Equation (D.29): Theleft-hand side of this linear system will be singular if N (number of phases) exceeds rank(A)(number of constraints). Thus, when a converged system consists of N = rank(A) phases, thetrial phase must replace one of the phases already present in the assembly in order to start anew cycle of Newton iterations. By letting the trial phase for the moment be phase numberN + 1, the size �i of each phase i in the updated assembly can be found as the solution to thelinear-programming-problem5maximize�1; : : : ; �N+1 �N+1 subject to A� N+1Xi=1 P Ti xi �i � b � = 0�1 > 0...�N+1 > 0(4.8)According to Problem (4.8) the size of the trial phase is maximized at ful�lled constraints. Oneshould note that this principle is entirely independent on the object function in Problem (4.1).5Problems (4.3) and (4.8) are QP and LP-problems respectively, and it may seem that two distinct numericalalgorithms are required to apply current method. This is, however, not the situation since both QP and LP-problems can be formulated as complementary problems. See i.e. [45] for the nice features of the complementarypivoting method.

Page 43: Computation of phase equilibria in uid mixtures

Chapter 4: Algorithms 25Since the linear constraints in Problem (4.8) have one degree of freedom, the optimal solutionwill have exactly one �i equal to zero. Hence, after the replacements xi �i xi, there are againN nonzero phases in the assembly and the trial phase has been introduced without violatingthe constraints.When a trial phase is included in an assembly consisting of N < rank(A) phases, sometrivial precautions can be taken to ensure that the Newton-Lagrange iteration will proceedsmoothly. First of all, it is possible to introduce the phase in zero amount thus avoiding toviolate the constraint speci�cation. This initial step is performed by updating the coordinatesof the N converged phases, but only the size of the trial phase is adjusted. This update ofthe assembly is achieved by performing one Newton step towards the solution of the somewhatarti�cial problemoptimizex1;:::;xN;�N+1 NXi=1 fi(xi) + fN+1(�N+1xN+1) subject to A� NXi=1 P Ti xi + P TN+1xN+1 �N+1 � b � = 0 (4.9)where �N+1 is the size of the trial phase. Equation (4.9) is valid in both minimization andmaximization problems since the Newton direction is not in uenced by the actual problem type.In order to �nd the Newton direction, it is possible to take advantage of the similarity betweenProblem (4.9) and Problem (D.9) shown on page 89. As shown in Appendix D.4, the Lagrangefunction corresponding to Problem (4.9) can be set up and the equations for the updates can betransformed to a system of equations similar to Equation (D.29). One can note that the objectfunction in Problem (4.9) is linear in �N+1 and neither the Hessian HN+1 nor fH -1N+1 will appearin the Newton-Lagrange scheme. Furthermore, at �N+1 = 0 the Newton-Lagrange scheme isidentical to Equation (D.29) for �N+1 = ��N+1. It can be shown that the computed �N+1 alwaysis positive. The Newton step in terms of x1; : : : ;xN are as shown in Equation (D.27), whereas,xN+1 should be updated according to xN+1 �N+1xN+1.

Page 44: Computation of phase equilibria in uid mixtures

26 Chapter 4: Algorithms4.2 Computation of phase diagramsThe di�erential equations to be integrated along the boundary of coexisting phases is summa-rized in Section 2.3. These equations are of a general nature and the theoretic framework forcomputing a general phase diagram is already established. Due to the fact that there exists awide range of di�erent types of phase diagrams, see i.e. [47], a single algorithm that is capableof constructing phase diagrams of systems of arbitrary complexity is completely out of scope.However, when a multi-phase point can be located and used as an initial point in the com-putation, it is possible to suggest a strategy that, in some situations, draws the entire phasediagram. The algorithm is explained by the help of Fig-�� �j�; =0�j�; =0

j�;�=0��j =0 � j�=0� j�=0� � ��

1111

11

1 1 1 1 1 1_______ _ _ _ _ _ _ _

�j =0�j�=0�j�=0

�j =0 j�=0

j�=0

zzzzzz

D D D D D D

kkkkk

%%%%%%%

S S S S S

� �� �� ��

Figure 4.1: Schematic phase diagram showing athree-phase region, three two-phase regions andthree one-phase regions.

ure 4.1. In Figure 4.1, the region labeled �� indicates a three-phase region. Each pointin the three-phase region is a solution ofgi + P iAT� = 0, A (PiP Ti xi � b ) = 0 fordi�erent choices of b. In the constraint spec-i�cation, the summation is over all phasesi 2 f�; �; g. There is no need for specify-ing the general coordinates xi or the num-ber of components in the system. Any phasediagram showing three-phase equilibria will,in the vicinity of the three-phase region, betopological equivalent to that shown in Fig-ure 4.1 as long as rank(A) > 3. Further-more, as shown in Figure 4.1, the boundariesof the three-phase regions are labeled by sym-bols where the vanishing phase is indicated bya subscript. According to this syntax, ��j =0 means that the three phases �, � and are inequilibrium and that phase has zero size. This part of the three-phase boundary, is, see Sec-tion 2.3, characterized by the equilibrium criterion gi+P iAT� = 0 for i = �; �; together withthe constraint speci�cation B (Pi 6= P Ti xi � b ) = 0 where rank(B) = rank(A)� 2. Since theconstraint speci�cation does not involve phase , the actual size of this phase can be arbitraryin the computation. The boundary of the three-phase region must, however, be characterizedby a system of equations with one degree of freedom. Imposing a �nite size of phase providesthe �nal equation that is required.In the phase diagram, points inside the three-phase region and on the boundary are thusof the following nature:Point inside three-phase region �� Points on three-phase boundary ��j =0gi + P iAT� = 0 gi + P iAT� = 0A (PiP Ti xi � b ) = 0 B (Pi 6= P Ti xi � b ) = 0eT x � c = 0Hence, if an initial point inside the three-phase region can be provided, it is straightforwardto locate one point on the boundary. One possible method to locate a point exactly on theboundary is outlined later. If the boundary ��j =0 is of any interest in the construction of thephase diagram6, the line can be obtained by integration of corresponding di�erential equation6Situations exist where a line of a phase diagram in generic coordinates adds nothing to the �nal projection.A trivial example is a temperature-pressure phase diagram of a one-component system. The generic coordinateswill in this example be S; V;n. In the TP projection, all points where three phases coexist will be mapped ontoa triple point.

Page 45: Computation of phase equilibria in uid mixtures

Chapter 4: Algorithms 27in both directions. At the terminal points of this line, one of the coexisting phases vanishes,i.e. at �j�; =0 phase � is still in equilibrium with the phases � and , but the size of phase � iszero. The equations for the terminal point are closely related to the governing equations of thephase boundary:Points on three-phase boundary ��j =0 Terminal point �j�; =0gi + P iAT� = 0 gi + P iAT� = 0B (Pi 6= P Ti xi � b ) = 0 B ( P T�x� � b ) = 0eT�x� � c� = 0eT x � c = 0 eT x � c = 0As can be seen, the system of equations for �j�; =0 has no degree of freedom, and hence, the pointcan be located by an ordinary root �nding technique. Due to the similarity of the governingequations of ��j =0 and �j�; =0, any point on the three-phase boundary ��j =0 will be a goodinitial estimate.To continue the tracking of lines in the phase diagram, the corners of the three-phase regionrequire some special attention. At each of these corners, a line in the diagram can be traced inone direction only. To outline how the direction of integration may be found, the equations ofa terminal point and a one-phase/two-phase boundary are compared:Terminal point �j�; =0 Points on two-phase boundary �j�=0g� + P �AT� = 0 g� + P �AT� = 0g� + P �AT� = 0 g� + P �AT� = 0g + P AT� = 0 xT (g + P AT�) > 0B ( P T�x� � b ) = 0 B ( P T�x� � b ) = 0eT�x� � c� = 0 eT�x� � c� = 0eT x � c = 0To continue integration from the terminal point along the boundary of the two-phase �� region,the equilibrium condition for phase is replaced by the stability criterion7 xT (g +P AT�) > 0.One should note that no properties of phase appear in the governing equations for the line�j�=0, and, when the line is parameterized by t, the derivative of the phase stability test function�(t) = xT �g +P AT�(t)� is merely _�(t) = xT P AT _�(t). Furthermore, if the parameterizationis such that t = 0 at the point �j�; =0, the phase stability test function will trivially be �(0) = 0due to equilibrium. Thus, by Taylor expansion of the phase stability test function,�(�t) = xT P AT _�(0)�t +O��t2� > 0and it is seen that the tangent to the phase boundary must be chosen such that xT P AT _�(0) > 0if the line is integrated with increasing t.4.2.1 Combinations of coexisting phasesThe discussion on how to traverse some of the boundaries in a phase diagram shown above,corresponds to the computation of boundaries between N and N+1-phase regions8 as described7This stability criterion does, however, only apply in situations where the thermodynamic surface for phase isa (generalized) energy surface. When phase is characterized by a (generalized) Massieu function, the relationsymbol in the criterion should be \6" if the derivative of the Massieu function with respect to transformedcoordinate is positive.8In Section 2.3 the equations describing N=(N +M) phase boundaries are outlined but case M > 1 is nottaken into consideration in the proposed algorithm.

Page 46: Computation of phase equilibria in uid mixtures

28 Chapter 4: Algorithmsin Section 2.3. In some situations, it is possible to draw the entire phase diagram by �ndingpoints on phase boundaries and, as a next step, integrate along these boundaries in either one ortwo directions. The overall problem thus consists of three parts. First, all possible combinationsof coexisting phases must be generated. Next, the equilibrium state of each assembly must beexactly located before a pathfollowing strategy can be initiated. The �rst subtask is moreor less a combinatorial problem. Any algorithm that generates ordered permutations can beapplied. This permutation problem is an especially good candidate for recursion. The desiredcombinations can be generated by a function de�ned i.e. as R(N;M; a; b) where N and Mare the number of ordinary and zero-sized phases, respectively. a and b are sets of phases, aconsists of N phases, b of M . In the function R(N;M; a; b), di�erent procedures are invokeddepending on current value of the number of zero-sized phases. Furthermore, the recursivefunction outlined below performs pathfollowing only if number of phases ful�lling the constraintspeci�cation satis�es Nmin 6 N 6 Nmax. It should be emphasized that the intention of thefunction shown below is to generate phase combinations for testing the phase tracking algorithm.In the modeling of complex thermodynamic systems involving a high number of energy surfaces,recursion will not be a suitable technique.R(N;M; a; b):M = 0 For each phase fj 2 a, reference R(N � 1; 1; a n fj; fj). At exit from this loop, allboundaries are traversed.M = 1 If N > Nmin, reference R(N � 1; 2; a n fj; b [ fj) for each fj 2 a. If N > Nmax,the diagram is complete. Otherwise, �nd a point on the boundary and integratein both directions.M = 2 If N > Nmin, choose one fj 2 a and reference R(N � 1; 1; an fj; fj). The diagramis complete if N > Nmax. Otherwise, locate the terminal point and integrate inthe directions which do not violate the stability criterion.4.2.2 Tracing of lines in phase diagramsThe recursive function shown in Section 4.2.1 utilizes a phase assembly in equilibrium as initialstate. If this initial state consists of N phases, the �rst reference of the procedure is R(N; 0; a; ;).During the recursion, the algorithm will locate points on a phase boundary and subsequentperform pathfollowing. The location of a point on a boundary is quite similar to the correctorstep of the pathfollowing algorithm, and a method to trace boundaries is presented �rst.The equations for the phase envelopes are derived in Appendix D.5 where also a simplepathfollowing algorithm is suggested. This algorithm, Euler predictor and Newton's methodas corrector, have been chosen solely due to its simple nature. If the pathfollowing problem isviewed as an ODE, Euler's method would de�nitely not be the correct solution scheme. However,since a corrector step is performed, the extra computational cost to �nd the Euler predictor ismoderate. This can be seen from the equations of the tangent to the phase boundary:Point on a (N+1)/N{phase boundary Corresponding di�erential equationgi + P iAT� = 0 _gi + P iAT _� =H i _xi + P iAT _� = 0B ( NXi=1 P Ti xi � b ) = 0 B NXi=1 P Ti _xi = 0eTN+1xN+1 � cN+1 = 0 eTN+1 _xN+1 = 0(4.10)From the linear system of equations, the right part of (4.10), it can be seen seen that theelements of the coe�cient matrix for computation of the tangent _x1; : : : ; _xN+1; _� is identical

Page 47: Computation of phase equilibria in uid mixtures

Chapter 4: Algorithms 29to the Newton scheme for determination of a point on the phase boundary9. The system ofequations for the tangent is homogeneous, _x1; : : : ; _xN+1; _� hence is in the null-space of thecoe�cient matrix. Furthermore, as shown in Appendix D.5, this implies that the correctorstep is not unique. This problem is resolved, see [6], by computing a corrector step that isorthogonal to the tangent. At �rst sight this may look as a trivial task, but an unambiguousnorm is needed in order to conclude that vectors are orthogonal. In thermodynamics, normshave been suggested [39], but such approaches are far too complicated to be utilized as subtasksin iteration sequences. Nevertheless, it seems likely that a weighted square sum may re ect theproperties of a norm. The corresponding inner product of the tangent and the corrector step isN+1Xi=1 (�xi; _x)Wxi + (��; _�)W� = N+1Xi=1 (Wxi �xi)T(Wxi _xi) + (W� ��)T(W� _�) (4.11)where the elements of Wx1 ; : : : ;W� are weighting factors. There are no obvious choices ofweighting matrices. The individual terms in the square sum, must, however, all have the samephysical dimension. By this criterion, some possible weighting matrices may be summarized asfollows: Table 4.2: Some possible weighting matrices in the innerproduct of the tangent and the correction vector.Weighted square sum Wxi W�i = 1; : : : ; N i = N + 1Dimensionless form diag(xi)-1 diag(xi)-1 diag(�)-1Dimension as f 2i diag(gi) O diag(Ab)Dimension as f 2i diag(P iAT�) O diag(Ab)In Table 4.2, the weighting factors corresponding to phase number N + 1 are zero when theresulting square sum is not dimensionless. Phase number N +1 is interpreted as the phase thatvanishes at a boundary. However, in the formulation of the constituting equations of the phasediagram, the actual size of this phase is quite arbitrary and it may not even be in the same orderof magnitude as any of the phases that together ful�ll the constraints. Hence, phase N + 1 isin such cases excluded from the norm function. Furthermore, it is also possible to exclude theweighting matrix corresponding to the Lagrange multipliers without a�ecting the dimension ofthe inner products in Equation (4.11).The general solution of the linear system of equations in (4.10) is shown in Appendix D.5.In Appendix D.5, the homogeneous and particular solution are indicated by subscripts h andp, respectively. The homogeneous solution will be codirectional with the tangent when theboundary is reached. By utilizing the weighted inner product, it is possible to compute thecorrector step by requiring orthogonality. In terms of the coordinates of the phases, the correctorstep reads �xi = �xip � PN+1i=1 (�xip; �xih)Wxi + (��p; ��h)W�PN+1i=1 (�xih; �xih)Wxi + (��h; ��h)W� �xihConcerning the weighting matrices, the di�erent alternatives shown in Table 4.2 have beentried. By measuring e�ciency by number of iterations required to converge the system, it was9See also Appendix E.2.

Page 48: Computation of phase equilibria in uid mixtures

30 Chapter 4: Algorithmsnot possible to draw any conclusions: A set of weighting matrices that resulted in few iterationsin one case performed poorly in other situations.When the nonlinear system of equations in (4.10) is converged, i.e. a new point on thephase envelope is located, the homogenous solution is, to within an arbitrary scalar, identicalto the tangent of the boundary line. The Euler predictor is hence obtained straightforwardas xi(t + �t) = xi(t) + �t �xih. How the time step is determined, depends primarily on thedesired resolution of the phase diagram. One possible method to specify the distance betweenconsecutive points on the boundary is to specify an upper bound on relative variation in extensivecoordinates. By denoting this upper bound �max, the following time step criterion was foundto work satisfactorily:maximizei;j �t subject to �t j(�xih)jj 6 �max j(xi)jj(4.12)In Equation (4.12), vector elements are indicated by an extra subscript. Thus, (�xih)j and (xi)jare the j'th element of the vectors �xih and xi, respectively.4.2.3 Locating points in a phase diagramAt various stages in the computation of a phase diagram, location of two types of boundarypoints are needed. Of these two kinds, a univariant point on a (N + 1)=N{phase boundarymay be found by a method analogous to the corrector step in the pathfollowing algorithm.When pathfollowing is performed, the Euler predictor provides a reasonable good estimate.However, to start the pathfollowing, the �rst point on the boundary must be computed withouta good initial estimate. To resolve this problem, the radius of convergence of the correctorstep is enlarged by performing a line search. A suitable merit function is found by exploitingthe similarity between the conditions for thermodynamic equilibria, see e.g. Equations (2.2)and (2.3), and the equations governing the phase envelope. Even though the number of linearconstraints varies between these two problems, the physical interpretation of the Lagrangemultipliers are identical in both situations. The multipliers are used as weighting factors in themerit function (4.6). In the merit function for computing a point on the phase envelope, onlymultipliers conjugated to the active constraints are taken into account. The active constraintsduring pathfollowing is speci�ed by the matrix B which is obtained by erasing two rows in theconstraint matrix A. The actual constraints that apply on the phase boundaries are problemspeci�c, but the relation between A and B can always be written�A = Bwhere� has the same structure as the matrices P i. In pathfollowing with two active constraints,examples of possible � matrices are �10 01 00 00�, �10 00 01 00� and �10 00 00 01�. In terms of the matrix �,the subset of Lagrange multipliers conjugated to the active constraints can be written ��, anda possible merit function ism(�) = ���� diag(��)B � NXi=1 P Ti xi(yi + � �yi)� b � ����2+ N+1Xi=1 ���� diag(xi) ( gi(yi + � �yi) + P iAT� ) ����2(4.13)Only one type of invariant points is considered in the algorithm. This type of point is character-ized by two phases vanishing simultaneously. Compared to the problem of locating a univariant

Page 49: Computation of phase equilibria in uid mixtures

Chapter 4: Algorithms 31point on an envelope, the situation is now less complicated since the extra vanishing phase addsone equation to the nonlinear system. The system of equations can thus be solved by ordinaryNewton iteration, the Newton step is found from Equation (D.35) which in this case has aunique solution. A suitable merit function has a functional form as Equation (4.13), but thenumber of coexisting phases must be adjusted. Thus, when the invariant point characterizedby two vanishing phases is sought, an appropriate merit function readsm(�) = ���� diag(��)B � NXi=1 P Ti xi(yi + � �yi)� b � ����2+ N+2Xi=1 ���� diag(xi) ( gi(yi + � �yi) + P iAT� ) ����2 (4.14)

Page 50: Computation of phase equilibria in uid mixtures

32 Chapter 4: Algorithms4.3 Stability analysis by a trajectory methodThe most well known trajectory method was brie y discussed in Section 3.4. In an attemptto improve the performance of this method, an alternative trajectory is proposed. The currentalgorithm is a Davidenko path method, and it has some features that make it more suitable forthe phase stability test problem.4.3.1 Governing equationsThe basic idea behind this strategy is, in accordance with Equation (3.1), to construct a syn-thetic, parameterized system. A homotopy that intuitively seems suitable, is to locate allminimum points at concentric circles centered in the initial point x�. When such a circle hasradius c, the equation de�ning the circle may be written 12(jjx� x�jj2�c2) = 0. The correspond-ing Lagrangian is l(x; �) = f(x) � 12 �(jjx� x�jj2 � c2), and, by di�erentiation, the �rst-orderconditions for f being stationary on the concentric circle areg � �(x� x�) = 0(4.15)In Equation (4.15), the initial point x� can be arbitrary, i.e. f can be stationary at x�. Inanalogy with Branin's method [6], a system of ordinary di�erential equations may be derivedfrom Equation (4.15). However, it seems that an explicit function relating � and the inde-pendent variable in the di�erential equation implies no advantages. Hence, the derivative ofEquation (4.15) with respect to t is for the moment written as(H � �I) _x = (x� x�) _�(4.16)where H = rxg. Compared to the di�erential equation in Branin's method, this ODE hassome nice features. First, at a stationary point where � = 0, the system (4.15) is not necessarilysingular. In addition, if the trace is initiated at a stationary point x� x� = 0, the parameter� can be identi�ed as an eigenvalue of the Hessian and _x must be codirectional with thecorresponding eigenvector. This feature is vital to the phase stability problem, since it isgranted that one can traverse the trajectory away from the trivial local minimum of the testfunction.As stated above, the direction of _x is known at the trivial stationary point, but some extrae�ort has to be made to explicitly establish its relation to _�. Without matrix/vector notation,line i in Equation (4.16) readsXj � @2f@xi@xj � �ij � � _xj � (xi � x�i ) _� = 0(4.17)By the chain rule, the derivative of Equation (4.17) isXj �Xk @3f@xi@xj@xk _xk � �ij _� � _xj +Xj � @2f@xi@xj � �ij � � �xj � _xi _�� (xi � x�i )�� = 0(4.18)At x � x� = 0, the term involving �� cancel in Equation (4.18). Next, by multiplying Equa-tion (4.18) by _xi and sum over all i, the term PjfPi( @2f@xi@xj � �ij �) _xig�xj vanishes since _x isproportional to the eigenvector of the Hessian. Therefore, at x� x� = 0, _� is related to _x bythe equation Xi Xj Xk @3f@xi@xj@xk _xi _xj _xk � 2 _�Xi _x2i = 0(4.19)

Page 51: Computation of phase equilibria in uid mixtures

Chapter 4: Algorithms 334.3.2 Numerical considerationsHitherto, no considerations on how to integrate ODE (4.16) have been made. It turns outthat the best strategy is to apply alternate methods on di�erent segments of the trajectory.Integration towards a stationary point of the object function is most conveniently done withthe homotopy parameter � equal to the independent variable of the ODE. With � = t, Equa-tion (4.16) is simpli�ed to (H � t I ) _x = x� x� (4.20)and this ODE can be integrated from an initial t to t = 0, a singular point of the underlyingfunction, without numerical di�culties. It turns out that the choice of a numerical scheme tointegrate ODE (4.20) is not crucial since the gradient solution of (4.20) can be exploited in acorrector step. Details on the corrector step are presented below.In the other situation, integration away from a stationary point of the underlying function,Equation (4.20) must be abandoned. The purpose of the current continuation method is to�nd a trajectory that runs through more than one stationary point. � in Equation (4.16) canhence not be monotonic along the trajectory, and one has to integrate Equation (4.16) until� possesses an extremum. At the very point where � is extreme, _� = 0, and Equation (4.16)reveals that � is equal to an eigenvalue of the Hessian. To integrate ODE (4.16) smoothlythrough the neighborhood of such points, the trajectory is parameterized by jj _xjj = 1. Theparameter t hence becomes identical to the arc length of the trajectory.(H � � I ) _x = (x� x�) _�_xT _x = 1 (4.21)Without additional information, the system (4.21) cannot be uniquely solved since there is achoice of sign involved in the normalization of the directional derivative. A convenient wayto ensure that the trajectory is traversed in the desired direction, is to require the directionalderivative to be continuous in t, i.e. by comparing the current vector of directional derivativesto the one computed at the previous time step. Alternatively, the direction can be derivedby analytical considerations: At points where _� = 0, � is equal to an eigenvalue � of H.Accordingly, _� and � � � change sign simultaneously. The signs of the eigenvalues shifted by �can be obtained without additional numerical cost from the attempted Cholesky factorizationof H � �I.As stated in the beginning of this section, the trajectory can be obtained very precisely byexploiting the gradient solution. The corrector step presented below follows closely the methodproposed by Branin [6], and is indi�erent whether the predictor is based on Equation (4.20)or (4.21). Let r be the error in the gradient solution, see Equation (4.15), at the predicted pointx(t+�t): r(x; �) = g � �(x� x�) (4.22)The homotopy parameter � in Equation (4.22) can be estimated by �(t+�t) = �(t)+�t _�, butit was experienced that computing � as the least square solution of r = 0 yield better numericalperformance. To �rst order, the error vector in Equation (4.22) can be expanded asr(x+ �x; �+ ��) = r(x; �) + (H � �I ) �x� (x� x�) �� (4.23)By solving r(x+ �x; �+ ��) = 0, one obtains the homogeneous and (one) particular solution� �xh��h � = � (H � �I)-1(x� x�)1 � and � �xp��p � = � �(H � �I)-1r0 �

Page 52: Computation of phase equilibria in uid mixtures

34 Chapter 4: AlgorithmsConsequently, the most general solution is� �x�� � = � �xp��p �+ � � �xh��h �(4.24)where � is an arbitrary scalar. One should here note that the homogeneous solution aboveis identical to _x solving Equation (4.16), and a component of x along xh will not serve asa correction. To compute the correction vector, the parameter � in the general solution ischosen such that the correction vector is orthogonal to the homogeneous solution. Hence, byEquation (4.24) and orthogonality, 0 = �xTp�xh + ��xTh�xh . Successive corrections with �xfrom Equation (4.24) will give points on the trajectory with desired precision. The convergencerate in the corrector step is of second order.One of the strengths of the homotopy de�ned in Equation (4.15) is that the initial pointcan be arbitrary. It is especially important that the initial point can be a stationary point of f .This can be exploited to locate all the stationary points of f without computing the completetrajectory, and it makes the homotopy well suited for phase stability computations.A strategy for locating the stationary points then consist of three steps. First, it is assumedthat a stationary point of f is known in advance. In the phase stability test, this assumptionis always ful�lled, and the stationary point is used as the initial point on the trajectory. Atthe initial point, the tangent of the trajectory is an eigenvector of the Hessian H. The secondstep in the procedure is to integrate ODE (4.21). The integration can, however, be terminatedwhen _� change sign. As a step number three, the next stationary point of f can be located byan ordinary root �nding technique.Thus, when one stationary point of f is known, there is a method for locating anothernearby stationary point. This enables restarting the algorithm, and the global optimizationproblem is simpli�ed to a sequence of ODE integrations and subsequent solutions of g(x) = 0 .

Page 53: Computation of phase equilibria in uid mixtures

Chapter 5Computational resultsThe forthcoming examples fall into two categories. First, some examples have been includedto demonstrate how the phase diagram construction and the equilibrium computations can beformulated in terms of generalized thermodynamic surfaces. The main purpose of the examplesin Sections 5.1 and 5.2 is to outline the details of the problem setup, and a large part of the textis devoted to the identi�cation of functions, vectors and matrices described in the theory. Thethermodynamic systems covered in the �rst part do not require any sophisticated numericalmethods to be characterized.More complex phase behavior is studied in Sections 5.3 to 5.5. The performance of thealgorithms at near-critical conditions is given special attention in these examples. In addi-tion to systems exhibiting ordinary 2-phase critical points, the examples include a near-criticalazeotrope, Section 5.4, and a system with tricritical point, Section 5.5.In the test examples, where the uids are characterized by equation of state phase models,the trajectory method described in Section 4.3 is used in the stability computation. In thiscomputation, only parts of the trajectory are computed in order to locate the local minima ofthe phase stability function. However, when the phase stability test function is known to haveseveral minima, it is of interest to compute the entire trajectory to check the global propertiesof the continuation method. Examples of complete trajectories are shown in Section 5.6.

35

Page 54: Computation of phase equilibria in uid mixtures

36 Chapter 5: Computational results5.1 Phase diagrams of a binary systemIn this example, the setup for the construction of Px, Tx and TP diagrams for a C1{C10mixture are presented. In all the examples in this section, the phase properties have beencomputed by the Soave-Redlich-Kwong model, implemented as a Helmholtz surface. The idealgas chemical potentials have been computed assuming constant heat capacities. The referencechemical potentials of the components have conveniently been set to zero since no chemicalreactions are involved. Parameters in the model are shown in Table 5.1.5.1.1 Pressure-composition diagramThe algorithm for constructing phase envelopes uses extensive coordinates as the primary vari-ables. With an equation of state model, the pressure-composition diagram is hence one of themost trivial phase diagrams to generate: The temperature is constant and held outside the com-putation. The primary variables are thus the volume and the mole numbers and these variablescoincide with the natural coordinates of the model. In short, the diagram in the two-phaseregion can be traced by(i) locating an initial point on the phase boundary i.e. by a T; V;n- ash,(ii) �nding all the V;n-points satisfying a two phase equilibrium where one phase is present inzero amount and the other ful�ll the constraint speci�cation.The general constraint speci�cation is A�PNi=1P Ti xi� b � = 0, and the constraint speci�cationfor the T; V;n- ash in step (i) can be written24 1 0 00 1 00 0 1 358><>:24 nC1nC10V 35vapor + 24 nC1nC10V 35liquid� 24 n�C1n�C10V � 359>=>; = 24 000 35The matrices P i in the general constraint speci�cation in this example will all be equal toidentity since the coordinates xi = [ nC1 nC10 V ]Ti are similar in both phases. The constraintmatrixA in the equilibrium computation andVap/Liq

Critical Point

xC10P=bar

10.80.60.40.20

400350300250200150100500Figure 5.1: Px diagram of C1{C10 at 100 �C.

phase boundary principle is merely the iden-tity matrix. In step (ii), the nonzero phase issubjected to the constraint B(x1 � b) = 0where, see Section 2.3, the number of lin-ear constraints accounted for by the matrixB is two less than the number of linear con-straints in the ash problem. The most in-tuitive way to achieve this is to reject theconstraints on volume and mass of one com-ponent. Hence, a possible constraint matrixin the phase boundary principle isB = � 1 0 0 �. This matrix accounts forthe conservation of mass of C1. However,keeping the volume �xed and allowing the equilibrium phases to have arbitrary mole num-bers also allows the entire pressure-composition plane to be traversed, and one of the matricesB = � 0 1 0 � or B = � 0 0 1 � may also well be used. The Px diagram is shown inFigure 5.1. Tracing of the boundary with the latter B-matrix was initiated at the equilibriumpoint corresponding to 50 bar in the �gure. No problems were encountered when the phase

Page 55: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 37envelope was constructed. Hence, the whole diagram can be plotted from only one trajectory inthe V;n space. By integration from initial point towards the critical point, the trajectory runssmoothly through the critical point and terminates at P = 0:0944044 bar for pure C10.5.1.2 Temperature-composition diagramThe phase boundary algorithm works in extensive coordinates, and transformations of energysurfaces must be done to construct the Tx diagram. First, since the temperature is not constant,the basic Helmholtz surfaces are inverse Legendre transformed with respect to temperature togenerate internal energy surfaces. Next, to handle the pressure speci�cation, the internal energysurfaces are shifted such that the derivatives with respect to the volume vanish at a speci�edpressure. Since the phase boundary is traced in generic coordinates, these transformations donot in uence on how the algorithm works, but the problem speci�c matrices A and B will bedi�erent from the corresponding matrices in Example 5.1.1. In analogy with the construction ofthe Px diagram, an initial point is required. At moderate pressures the model predicts three-phase equilibria in the C1{C10 system. The three-phase point is easily located by a S; P;n- ashwhere appropriate constraints are:24 1 0 0 00 1 0 00 0 0 1 358>>><>>>:2664 nC1nC10VS 3775vapor + 2664 nC1nC10VS 3775liquid 1 + 2664 nC1nC10VS 3775liquid 2 � 2664 n�C1n�C10V �S� 37759>>>=>>>; = 24 000 35 (5.1)The shift in the gradients of the internal energy surfaces is performed by subtracting the vec-tor [ 0 0 (�P �) 0 ]T where P � is a speci�ed pressure. Note that this vector is in the nullspaceof A, which is the leftmost matrix in Equa- Critical Point

Liq/LiqVap/LiqxC10

T=K10.80.60.40.20

700600500400300200100Figure 5.2: Tx diagram of C1{C10 at 30 bar.

tion (5.1). At P � = 30 bar the computed C10mole fraction of the three coexisting phasesare xC10 = 0:383698, 8:92237 �10�4 and2:43983 �10�9 respectively, the three-phasetemperature is 176.814 K.As in Example 5.1.1, the choice of theB-matrix in the boundary tracking setup isnot crucial, every matrix made up of one rowin A is feasible. The construction of the Txdiagram is most easily depicted if one con-siders the topology of the phase envelopes inthe two-dimensional s; x space, see e.g. theschematic phase diagram shown in Figure 4.1.In this space, the three coexisting phases, the initial point, form a triangle where the edges arethe three 3-phase/2-phase boundaries. The three-phase region is mapped onto the three-phaseline in the Tx projection. Two 1-phase/2-phase boundaries also emerge from each of the ver-tices, and these boundaries must be traced in order to �nd the two-phase envelopes of theTx diagram. Hence, at each of the vertices of the triangle, there are three coexisting phases:A phase � ful�lling the constraint speci�cation, a phase � present in zero amount that con-tinues to be in equilibrium with phase � at the one-phase/two-phase boundary and a phase that is in equilibrium with phases � and � at the initial point only. When the boundarytracking is initiated, the direction of the integration is found by applying the phase stabil-ity criterion to the latter of these phases. With �AT� equal to the parameterized commontangents of the phases on the two-phase boundary, the stability test function for phase is

Page 56: Computation of phase equilibria in uid mixtures

38 Chapter 5: Computational results�(t) = xT �g +P AT�(t)� where �(0) = 0 due to equilibrium. The stability criterion �(t) > 0for all x implies _�(0) = xT �P AT _�(0)� > 0 and a unique, initial direction of integration isfound by inspecting the sign of the inner product xT P AT _�(0).The Tx diagram is shown in Figure 5.2. The constraint speci�cation used in the boundarytracking algorithm is B = � 0 0 0 1 � whichLiq Liq/Liq

Vap/Liq

xC10T=K

0.0070.0060.0050.0040.0030.0020.0010

20018016014012010080Figure 5.3: Enlarged portion of Tx diagram ofC1{C10 at 30 bar.

ensures that nonzero phase on the boundaryhas constant entropy. Similar to the construc-tion of the Px diagram, the trajectory runsthrough the critical point without encounter-ing numerical instabilities. The upper vapor-liquid phase envelope in Figure 5.2 is hence asingle trajectory connecting two three-phasepoints. Due to the resolution of the plot,only the low temperature liquid/liquid enve-lope can be observed in Figure 5.2, and thecomposition of the C1-rich phase cannot beseen in details. This part of the diagram isenlarged and presented in Figure 5.3. Boththe temperature and the mole fraction reso-lution must be increased to see the vapor/liquid envelope below the three-phase line.Liq

Vap Vap/LiqVap/Liq

xC10T=K

10�88�10�96�10�94�10�92�10�90176.750176.775176.800176.825

(a)Liq Liq/LiqVap/LiqVap/Liq

xC10T=K

1:2�10�310�38�10�46�10�44�10�42�10�40176.750176.775176.800176.825

(b)Figure 5.4: Left boundary, a, and right boundary, b, of vapor/liquid region. Note thedi�erent units in the plots.5.1.3 Pressure-temperature diagramIn the computation of Px and Tx diagrams, the constraint speci�cation in the boundary trackingalgorithm is quite arbitrary. However, in the current example the PT diagram of one speci�ccomposition is considered, and the constraint speci�cation follows directly from the conservationof mass of each component. Constraints in the equilibrium computation and the boundarytracking may hence be summarized to:2664 1 0 0 00 1 0 00 0 1 00 0 0 1 37758>>><>>>:2664 nC1nC10VS 3775vapor + 2664 nC1nC10VS 3775liquid 1 + 2664 nC1nC10VS 3775liquid 2 � 2664 n�C1n�C10V �S� 37759>>>=>>>; = 2664 0000 3775

Page 57: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 39The constraint-matrix B = �10 01 00 00� accounts for the conservation of each component on thephase boundary, but allows both the volume and the entropy to be arbitrary in order to sweep theentire PT plane. The computation of the Single PhaseLiq/VapLiq/Liq/VapCritical End-PointCritical Point

v=litermol�1s=JK�1 mol�1

0.180.160.140.120.10.080.060.04

18016014012010080Figure 5.5: Volume-entropy diagram of C1{C10.

phase boundary in this case requires an extrainitialization in order to locate a point on the1-phase/2-phase boundary exactly. An arbi-trary equilibrium point inside the 2-phase en-velope was found to be su�cient as a startestimate to locate either a bubble point or adew point. From this point, the trajectoryin the S; V;n-coordinates was integrated inboth directions. This trajectory has terminalpoints in the zero and in�nite-pressure limit,and, as in the previous examples, traversingthrough the critical point did not impose anydi�culties. The phase diagram is shown inFigure 5.6a, and an enlarged portion showing the three-phase line is given in Figure 5.6b. Tolocate this line, the 3-phase point described in Section 5.1.2 was used as an initial point. Inthe PT projection, this line terminates abruptly at the critical end-point. However, the lineis computed in S; V;n-coordinates, see Figure 5.5. In this coordinate set, the trajectory is asmooth curve with both terminal points in the low temperature zero pressure limit. This ex-ample, hence, indicates that the proposed strategy for computation of phase boundaries canhandle both critical points and critical end-points.Critical End-Point

Critical Point

T=KP=bar

500450400350300250200150100

5004003002001000 (a)Three Phase Line !

Critical End-Point

T=KP=bar

200180160140120100

6050403020100 (b)Figure 5.6: Pressure-temperature diagram of C1{C10. The mole fraction of C1 is 0.1.Table 5.1: Critical data and acentric factors, !, according to Reid et al. [46]. Ideal gaspure component data at 1 atm and 25�C are from Aylward et al. [3]. m-factors enteringthe equation of state are related to the acentric factors by m = 0:48508 + 1:55171! �0:15613!2. The binary interaction coe�cient between C1 and C10 is 0.040.TC PC ! s� c�PK bar J mol�1K�1 J mol�1K�1C1 190.4 46.0 0.0109 186 36C10 617.7 21.2 0.4902 545 235

Page 58: Computation of phase equilibria in uid mixtures

40 Chapter 5: Computational results5.2 Stability of mineralsIn this example, the stability of the solid phases FeO, Fe2O3, Fe3O4 and FeSO4 in presence ofa gaseous phase composed of SO2 and SO3 is discussed. The thermodynamic models for thephases do not take solid solution e�ects into consideration, and the results could be obtained bypure analytical considerations. Nevertheless, the example has been included since it illustrateshow the equilibrium computation of a reacting system with mixed mass and chemical potentialconstraints can be formulated. It is also demonstrated how a simple phase diagram can beconstructed by equilibrium computation with alternate constraint speci�cations.5.2.1 Stability computation of reacting systemThe stability region of a condensed phase is often presented in a diagram where the partialpressure of the gaseous components are the independent variables. With an ideal gas phase,as is the case here, there is a trivial relation between the chemical potential and the partialpressure. In situations where the gas phase is governed by other models, partial pressure is notan adequate measure of chemical activity. The chemical potential, however, is well de�ned inevery respect, and by using chemical potentials instead of partial pressures, the diagrams shownbelow will be independent of the gas phase model.A �rst impression of the phase diagram isFeSO4Fe3O4Fe2O3FeO

�SO3=kJmol�1� SO 2=kJmol�1

-360-380-400

-200-240-280Figure 5.7: Stable phases found by equilibriumcomputations at speci�ed chemical potential ofSO2 and SO3 at 600 �C.

obtained by a series of equilibrium compu-tations where the chemical potentials of SO2and SO3 are varied, see Figure 5.7. In Fig-ure 5.7, the volume and the amount of Feare held constant. The actual constraint val-ues are irrelevant since only intensive quan-tities are shown. The �gure is constructedby assigning a unique symbol to each con-densed phase that is present at equilibrium.As in constant pressure calculations, the con-straints in the chemical potentials are han-dled by the concept of \shifted surfaces". Al-though this method is well suited for imple-mentation in computer codes, it seems not tobe described in the literature. Actually, howthe method works is best illustrated by an example, and the various steps in the computationis explained below. In this method, some book-keeping is required, and a route leading to thecorresponding optimization problem is obtained by considering the constraint speci�cation of aclosed system. In Equation (2.3), the linear constraints in the optimization problem of a sumof �rst-order homogeneous functions are A(PNi=1P Ti xi�b) = 0. Inserting the components and

Page 59: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 41phases that can be present in the assembly, yields:2664 1 2 3 1 0 0 01 3 4 4 2 3 00 0 0 1 1 1 00 0 0 0 0 0 1 37758<:266666666410000003777777775 � nFeO �+

266666666401000003777777775 � nFe2O3 �

+266666666400100003777777775 � nFe3O4 �+

266666666400010003777777775 � nFeSO4 �

26666666640 0 00 0 00 0 00 0 01 0 00 1 00 0 1

377777777524 nSO2nSO3V 35� 2666666664n�FeOn�Fe2O3n�Fe3O4n�FeSO4n�SO2n�SO3V �

3777777775 9=; = 2664 0000 3775 (5.2)The vectors x1 : : :x4 in the constraint speci�cation correspond to the coordinates (mole num-bers) of the Gibbs energy of the condensed phases. The gas phase is included in the thermo-dynamic system by a Helmholtz energy surface. Each row in matrix A de�nes a conservationequation. It should be emphasized that there is no unique constraint matrix A since the linearconstraints are a homogeneous system of equations. The nullspace of every feasible constraintmatrix, however, must have a common basis1. By elementary row operations, A can be trans-formed to its canonical form where the mole numbers of SO2 and SO3 are the basic variablesand the other rows are orthogonal. A constraint speci�cation equivalent to (5.2) may hence bewritten as2664 1=3 �1=3 0 1=3 1 0 0�2=5 1=5 �1=5 3=5 0 1 00 0 0 0 0 0 11=p15 2=p15 3=p15 1=p15 0 0 0 37758<:

266666666410000003777777775 � nFeO �+

266666666401000003777777775 � nFe2O3 �

+266666666400100003777777775 � nFe3O4 �+

266666666400010003777777775 � nFeSO4 �+

26666666640 0 00 0 00 0 00 0 01 0 00 1 00 0 1

377777777524 nSO2nSO3V 35� 2666666664n�FeOn�Fe2O3n�Fe3O4n�FeSO4n�SO2n�SO3V �

3777777775 9=; = 2664 0000 3775 (5.3)The �rst-order conditions for the optimum of a sum of homogeneous functions aregi + P iAT� = 0. The constraint matrix above is now in a form such that some of the Lagrangemultipliers can be identi�ed. By de�ning � = ����SO2 � ��SO3 �1 p15�2�T the �rst-order condi-tions can be written as shown in Equations (5.4) to (5.8), see page 42. From Equation (5.8), it isseen that the �rst-order conditions are ful�lled if and only if �SO2 = ��SO2 and �SO3 = ��SO3. Due1When solving the �rst-order conditions in the equilibrium computation, the constraint matrix is, due tonumerical considerations, replaced by rank(A) rows of rightmost matrix in it's singular value decomposition.

Page 60: Computation of phase equilibria in uid mixtures

42 Chapter 5: Computational results

� �FeO �1=3��SO2 +2=5��SO3 �+ � 1 0 0 0 0 0 0 �26666666640 10 20 30 10 00 01 0

3777777775� �1�2 � = � 0 �(5.4)� �Fe2O3 +1=3��SO2 �1=5��SO3 �+ � 0 1 0 0 0 0 0 �2666666664

0 10 20 30 10 00 01 03777777775� �1�2 � = � 0 �(5.5)

� �Fe3O4 +1=5��SO3 �+ � 0 0 1 0 0 0 0 �26666666640 10 20 30 10 00 01 0

3777777775� �1�2 � = � 0 �(5.6)� �FeSO4 �1=3��SO2 �3=5��SO3 �+ � 0 0 0 1 0 0 0 �2666666664

0 10 20 30 10 00 01 03777777775� �1�2 � = � 0 �(5.7)

24 �SO2 � ��SO2�SO3 � ��SO2�P 35+ 24 0 0 0 0 1 0 00 0 0 0 0 1 00 0 0 0 0 0 1 3526666666640 10 20 30 10 00 01 0

3777777775� �1�2 � = 24 000 35(5.8)

Page 61: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 43to the homogeneity of thermodynamic functions, it is possible to identify the leftmost vectorsin Equations (5.4) to (5.8) as the gradients of shifted energy functions and, consequently, theEquations (5.4) to (5.8) must be the gradient of a Lagrange function. Hence, the governingminimization problem involves the four shifted Gibbs energy surfaces,f1 = nFeO (�FeO �13��SO2+25��SO3); f2 = nFe2O3(�Fe2O3+13��SO2�15��SO3);f3 = nFe3O4(�Fe3O4 +15��SO3) and f4 = nFeSO4(�FeSO4�13��SO2�35��SO3)together with the shifted Helmholtz energy surface:f5 = nSO2(�SO2 � ��SO2) + nSO3(�SO3 � ��SO3) + V (�P )The corresponding constraint speci�cation in extensive coordinates is obtained by neglectingthe rows corresponding to the basic variables in Equation (5.3).The method may seem inadequate when one takes into account the numerous steps in thereasoning above, but it should be emphasized that its strength lies in its exibility and themethod is very easily formulated by a set of rules. In the general case, the method may besummarized as follows:When (generalized) intensive coordinates g�1, g�2, : : : are involved in the constraintspeci�cation, an optimization problem with solution at the speci�ed intensive coordi-nates is possible when shifted surfaces are introduced. For each constrained intensivecoordinate g�j , three steps are required.Step 1 Pivot one of the elements in A that corresponds to the conjugate of the con-strained intensive coordinate g�j . This step can be done by the singular valuedecomposition described in Appendix E.3.Step 2 Let the elements of vector a be equal to the elements of the row ofA that containsthe pivot element. Replace each surface fi by the shifted surface xi(gi�P iag�j ).Step 3 Update A by erasing the row that contains the pivot element.5.2.2 Phase diagram constructionThe proposed algorithm for locating boundaries in a phase diagramwould in this example involveeither a location of the two 4-phase points or a location of three 3-phase points, followed bytracing all possible 3-phase/2-phase boundaries and subsequent phase stability tests to reject anymetastable phases. However, applying the general method in the current example is an overkillsince the phase boundaries in Figure 5.7 can be found by variation of only one parameter. Byvariation of the chemical potential of SO3 and the total amount of sulphur, see Figure 5.8, the �vepossible three-phase regions emerge. Note that the amount of sulphur represents a constraintvalue in the minimization problem. Since the system is partially open by the constraint inchemical potential of a reacting component, this value will in general not be equal to the totalamount of sulphur in the thermodynamic system. The chemical potentials are of course nota�ected by the somewhat unclear interpretation of one constraint, and the potentials in eachthree-phase point in Figure 5.8 are presented in Figure 5.9.

Page 62: Computation of phase equilibria in uid mixtures

44 Chapter 5: Computational results

Fe3O4 FeOFe2O3 Fe3O4FeSO4 FeOFeSO4 Fe3O4FeSO4 Fe2O3FeSO4Fe3O4Fe2O3FeO

nSO3=mol� SO 2=kJmol�1

1.210.80.60.40.20-280-240-200

Figure 5.8: Stable phases found by equilibrium computations at speci�ed chemical potential ofSO2 and mole number of SO3 at 600 �C. Note that nSO3 is the nominal mole number of SO3,i.e. the mole number before reaction.FeSO4Fe3O4 Fe2O3

FeO

�SO3=kJmol�1� SO 2=kJmol�1

-360-380-400

-200-240-280Figure 5.9: The chemical potentials of SO2 and SO3 at the 3-phase equilibrium points shownin Figure 5.8. The three coexisting phases are the gaseous phase and two condensed phases.

Page 63: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 455.2.3 Thermodynamic modelsThe condensed phases are assumed to be incompressible with neglectable volume and hencecompletely characterized by their constant-valued chemical potentials. The gas phase is modeledby the ideal gas law implemented as a Helmholtz surface. For all the phase models, data forchemical potential of formation, entropy of formation and heat capacity are according to Stullet al. [59]. Reference chemical potentials at 600 �C are extrapolated from values at 900 K,see [59] and Table 5.2, under the assumption of constant heat capacities.Table 5.2: Pure component molar entropy, chemical potential and molar heatcapacity at 1 atm and 900 K according to Stull et al. [59].s� at 1 atm �� at 1 atm c�Pcal mol�1 K�1 cal mol�1 cal mol�1 K�1SO3SO2FeOFeSO4Fe2O3Fe3O478.10571.69328.74063.06156.24887.696

-74230-70822-50964-146185-140248-19666117.82312.80613.93036.51039.79248.000

Page 64: Computation of phase equilibria in uid mixtures

46 Chapter 5: Computational results5.3 Phase diagrams with several critical pointsThe phase model SRK EOS2 predicts an interesting phase behavior of the binary systemC2{n-C16. At the pressure 52.124152 bar, the system has three ordinary critical points. Fur-thermore, two of the critical points almost coincide in the temperature-mole fraction projectionand this system may hence be a severe test of both the algorithm for equilibrium computationand phase diagram construction.The phase diagrams of a binary mixture were discussed in Section 5.1.2. In this example,the phase behavior is more complex but no special requirements are needed to construct thephase diagrams. Thus, by applying the stepsVap/Liq

Critical Points

Critical Point

xC16T=K

10.80.60.40.20

700600500400300Figure 5.10: Tx phase diagram of C2{n-C16 at52.124152 bar. Two of the critical points areindistinguishable. Liq/Liq Vap/Liq

Vap/LiqCritical Point

Critical PointxC16T=K

0.0080.0070.0060.0050.0040.0030.0020.0010

309.246309.245309.244309.243309.242309.241309.240309.239309.238309.237Figure 5.11: Enlarged portion of Figure 5.10showing the three-phase region.

of phase diagram construction outlined in Sec-tion 5.1.2, the following results are obtained:A point in the three-phase region was lo-cated by equilibrium computation with con-straint speci�cation S; P;n. The mole frac-tions of C16 in the three phases are 1.248 �10�3,4.013 �10�3 and 6.118 �10�3, respectively.Computed temperature is 309.2425 K. Thethree-phase point was used as initial pointin the boundary tracking algorithm. In thissystem, both 1-phase/2-phase and 2-phase-3-phase boundaries were located.The entire Tx diagram is shown in Fig-ure 5.10. All the critical points cannot be seenin this �gure. Two additional critical pointsare seen in Figure 5.11 where the three-phaseportion of the diagram has been enlarged. Inthe diagram, every pair of points correspond-ing to triple point compositions are connectedby one 1-phase/2-phase boundary. This im-plies, when the boundary tracking is success-ful, that it is su�cient to trace only three1-phase/2-phase boundaries to construct theentire Tx diagram. However, in this exam-ple successful phase tracking cannot betaken for granted. At a critical point, theHessian of the internal energy has corank 2.Two critical points close to each other indi-cate that there is a region where an eigenvalueof the Hessian is close to zero. In such regions,the system of equations solved during boundary tracking will be ill-conditioned and numericalinstabilities may occur.By specifying the phase tracking setup exactly as described in Section 5.1.2, i.e. constantentropy of the system is the only active constraint on the boundary, the three 1-phase/2-phaseboundaries were computed without any numerical problems. It is, however, possible to for-mulate the governing equations of the phase boundaries such that some numerical problemsare encountered. From a mathematical point of view, it is arbitrary which constraint is active2The model parameters are shown in Table 5.3.

Page 65: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 47when the boundary is traversed3. When alternate constraint speci�cations were tested, it wasfound that the performance of the algorithm depends on the choice of active constraints. Bychoosing a B-matrix that speci�es constraint in one of the components, the corrector step inthe algorithm diverges at the critical points shown in Figure 5.11.In this example, the boundaries of theCriticalPoint

Critical PointSingle Phase Vap/Liq/LiqVap/Liq

xC16s=JK�1 mol�1

0.0080.0070.0060.0050.0040.0030.0020.0010

180.5180.0179.5179.0178.5178.0Figure 5.12: Three-phase region plotted in molarentropy, mole fraction coordinates.

3-phase region have also been calculated. Inthe Tx projection, all points on this boundaryare mapped onto the three-phase line. In or-der to view the 3-phase region, the plot mustbe presented in other coordinates, i.e. molarentropy and mole fractions as shown in Fig-ure 5.12. At this boundary, the compositionof each coexisting phase remain constant andthe computation of these boundaries is notparticularly challenging. What makes Fig-ure 5.12 more interesting is that it shows thetopology of a phase diagram with three-phaseequilibrium.Table 5.3: Critical data and acentric factors, !, accordingto Reid et al. [46]. Ideal gas pure component data at 1 atmand 25�C are from Aylward et al. [3]. m-factors enteringthe equation of state are related to the acentric factors bym = 0:48508+1:55171!�0:15613!2. The binary interactioncoe�cient between C2 and n-C16 is 0.TC PC ! s� c�PK bar J mol�1K�1 J mol�1K�1C2 305.4 48.8 0.0979 230 53n-C16 722.0 13.7 0.7384 778 372

3See Section 5.1.2 for a discussion of possible B-matrices.

Page 66: Computation of phase equilibria in uid mixtures

48 Chapter 5: Computational results5.4 Critical azeotropeThe linear systems of equations that are solved in connection with both equilibrium computationand phase diagram construction will become singular both at critical points and when thephase coordinates are linearly dependent. If the primary variables of an algorithm are T , Pand mole numbers, these singularities will be present simultaneously in systems that exhibitcritical azeotropy [38]. However, the proposed algorithms utilize a di�erent variable set, andthe purpose of this example is to demonstrate how the choice of primary variables can reducesthe problem with singularities. It is also demonstrated how nearly singular coe�cient matricesa�ects the performance of the algorithms.The theory for critical azeotropy is described by Gri�ths et al. [19] where the binary systemsCO2{C2H6, CO2{C2H4, C2H6{C2H2 and HCl{(CH3)2O are given as examples of mixtures thatexhibit critical azeotropy. Of these systems, CO2{C2H6 is chosen as the working example. Thecomputations are based on SRK EOS, see Table 5.4 for model parameters.5.4.1 Phase diagramsA Px diagram at 293.05 K is shown in Figure 5.13. The two-phase region is extremely nar-row, and from Figure 5.13, it is not possible to decide whether the two-phase region ends at anazeotropic point or critical point. A portion of the isotherm is enlarged and shown in Figure 5.14.Figure 5.14 shows that the system has a cri-CriticalPointLiqVap

xC2H6P=bar

0.30.250.20.150.10.050

63626160595857Figure 5.13: Px phase diagram of C2H6{CO2at 293.05 K.

condenbar at xC2H6 = 0:2538, whereas thecritical composition is xC2H6 = 0:2556. Thecorresponding vx projection is shown in Fig-ure 5.15. The isobars are included in this plot,and in the two-phase region there is a discon-tinuity in the slopes of the isobars. The slopedP=d xC2H6 approaches +1 in the left partof the �gure whereas dP=d xC2H6 is negativefor xC2H6 > 0:2538. The mole fractions of thecoexisting phases are identical at the pointwhere the tie-line is exactly vertical. Thiswill, however, be an azeotrope and not a crit-ical point.It is possible to bring the azeotrope andcritical point closer by increasing the temperature. At 293.095 K, see Figure 5.16, the system isa near critical azeotrope. One can note that the region shown in Figure 5.16 is approximately10�6 bar � 10�4 and the di�erence in compositions between the coexisting phases are henceextremely small.Although the system considered in this example exhibits critical azeotropy, the topologyof the phase diagrams in generic coordinates are relatively simple: Only two phases coexistat the envelope and the phase boundary is hence a smooth, continuous trajectory in i.e. V;n-coordinates. If numerical problems are avoided, the diagrams shown in Figures 5.13 to 5.16can be constructed by tracing only one phase boundary. However, some numerical problemswere detected in this example. From the initial point on a line in the phase diagram, i.e. thebubble point line, consecutive points on the phase boundary can be found by integration intwo directions. When the initial point is remote to the critical region, integration towardsthe boiling point of C2H6 was performed successfully. Along the other direction, no problemswere encountered at the cricondenbar. The algorithm thus seems to be insensitive to azeotropic

Page 67: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 49systems. This can be explained by the choice of primary variables. The phase coordinates in thealgorithm are xi = [ nCO2 nC2H6 V ]Ti for the i = 1; 2 coexisting phases. Due to di�erence in themolar volumes of the two phases, the phase coordinates x1 and x2 will be linearly independent.However, the compositions of the phases are identical at the azeotrope, and algorithms iteratingmole numbers may encounter a singularity.When the integration is continued, the algorithm fails in the vicinity of the critical point.In the critical region, the corrector step in the phase tracking algorithm diverges due to sin-gular coe�cient matrix4. The phase diagrams shown in this section are hence constructed byintegration along both the bubble point line and the dew point line. The discontinuity near thecritical point is, in terms of mole fractions, approximately 10�8.CriticalPointVap

LiqxC2H6

P=bar0.2560.2550.2540.2530.2520.2510.250

62.7926062.7925562.7925062.7924562.7924062.7923562.79230 xC2H6v=litermol-1

0.2560.2550.2540.2530.2520.2510.250

0.1350.1300.125Figure 5.14: Region near the criticalpoint at 293.05 K Figure 5.15: vx diagram at 293.05 K.Isobars are shown by dotted lines.

CriticalPointVapLiq

xC2H6P=bar

0.253800.253720.253640.25356

62.854101462.854101262.854101062.854100862.8541006 Figure 5.16: Region near the criticalpoint at 293.095 K4Linear systems of equations were solved by Crout factorization, [11, 42], utilizing partial and implicit pivoting.A matrix is considered to be singular if the one-norm of a pivoting element is less than 10�24.

Page 68: Computation of phase equilibria in uid mixtures

50 Chapter 5: Computational results5.4.2 Equilibrium computationsSome numerical instabilities were detected during construction of the Px phase diagrams. Theseproblems occurred in the vicinity of the critical point, and the ash algorithm has been testedwith constraint speci�cation within this region.The pressure and mole numbers have been varied in a series of ash calculations at tem-perature 293.05 K. The lowest pressure in the computations was 62.79232 bar and the pressurewas increased in uniform steps of 1.5 �10�6

xC2H6v=litermol-1

0.255610.255600.255590.255580.255570.12900.12950.1300

Figure 5.17: A vx projection of the near criticalregion at 293.05 K. Isobars are shown by dottedlines and successful two-phase computations areindicated by �lled circles.

bar. The di�erence in speci�ed mole frac-tion of C2H6 between two subsequent com-putations was approximately5 6 �10�7. Sincethe two-phase region is extremely narrow inthe Px projection, the results are presented asisobars in a vx phase diagram, see Figure 5.17.In Figure 5.17, the constraint speci�cations ofcomputations converging to two-phase solu-tions are shown by �lled circles. Furthermore,it is seen from Figure 5.17 that some compu-tations at constraint composition inside thetwo-phase region are erroneous. However, thealgorithm did not diverge in any of the com-putations. In the computations where single-phase equilibrium are erroneously reported,the stability search located a trial composi-tion not equal the trivial solution. The stability test function in these cases was not signi�cantlyless than zero and the trial phase was rejected.Table 5.4: Critical data and acentric factors, !, accordingto Reid et al. [46]. Ideal gas pure component data at 1 atmand 25�C are from Aylward et al. [3]. m-factors enteringthe equation of state are related to the acentric factors bym = 0:48508+1:55171!�0:15613!2. The binary interactioncoe�cient between CO2 and C2H6 is 0.136.TC PC ! s� c�PK bar J mol�1K�1 J mol�1K�1C2H6 305.4 48.8 0.0979 230 53CO2 304.1 73.8 0.2390 214 37

5In the computations, the speci�ed mole number of C2H6 was varied in uniform steps. The correspondingvariations in mole fractions are hence not exactly uniform.

Page 69: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 515.5 Ternary mixture with tricritical pointA tricritical point is a state where three coexisting phases become identical. Ternary andquaternary systems exhibiting tricritical points are review by Scott [50], and equilibrium com-putations of systems with tricritical points are reported by Diandreth et al. [12] who used PREOS to model the ternary system 2-propanol{H2O{CO2. Computed phase diagrams of theC1{C6{H2S system are shown by Haug-Warberg [22], Kohse et al. [26] and Michelsen [33]. Inall these references, the uid system is characterized by the SRK EOS. There are, however,some inconsistencies in the model parameters used in [22] and [26], and the computed tricriticalcompositions and phase diagrams in [22] and [26] are consequently not identical.Model parameters according to [22] have been used in the following examples. First, thephase diagram at tricritical composition is constructed, and in Section 5.5.2 the equilibriumcomputation algorithm is tested on di�erent constraint speci�cations.5.5.1 Phase diagramsThe phase diagrams presented in this section are all computed at tricritical composition. Atthe phase boundaries, the system mole numbers are constant, and as in Example 5.1.3, entropyand volume of the system are allowed to be arbitrary. The phase diagram computed in S; V;ncoordinates is shown in Figure 5.18. On should note that the volume axis of Figure 5.18a ismade logarithmic in order to include all the di�erent critical points in one diagram. Each criticalpoint has been given a number, the same numbering convention is used in all projections shownin this section. An enlarged portion of the four-phase region is shown in Figure 5.18b.I,II 2 Phase Critical Point on 3 Phase BoundaryIII Tricritical PointIV 2 Phase Critical PointV Critical End Point

V IVIII II Illvll!

lvvlv=litermol�1

s=JK�1 mol�1

1010.10.01

220200180160140120100 (a)V

IVIII II lllvlllllvll

lvvl

v=litermol�1s=JK�1 mol�1

0.080.070.060.050.04

160150140130120110100 (b)Figure 5.18: Phase diagrams in volume-entropy coordinates of the system C1{C6{H2Sat tricritical composition xC1 = 0:53572, xC6 = 0:024992 [22].Figure 5.18 indicates that the boundary of the four-phase region is rather special. As shownin Figure 5.18b, the lllv -region touches the two-phase ll -region. At this invariant point, one ofthe equilibrium phases at the 3-phase/4-phase boundary vanishes. This exotic phase behaviormakes the system well suited as a test object.To compute the phase diagram shown in Figure 5.18, an initial point in the lllv -regionis required. By choosing three of the equilibrium phase in the initial assembly, the algorithmshould compute the 4-phase envelope. Next, the algorithm should select two of the initial phases

Page 70: Computation of phase equilibria in uid mixtures

52 Chapter 5: Computational resultsI,II 2 Phase Critical Point on 3 Phase BoundaryIII Tricritical PointIV 2 Phase Critical PointV Critical End-Point

VIVIII II Illv

ll lvvl

T=KP=bar

350300250200

250200150100500 (a)V

IVIII II lllvlllllvll

lvvl

v=litermol�1T=K

0.080.070.060.050.04

320300280260240220200180 (b)V

IVIIIII Illvll

lvvl

h=Jmol�1P=bar

6000055000500004500040000

200150100500 (c)V

IVIII II lllvlllllvlllvvl

v=litermol�1u=Jmol�1

0.080.070.060.050.04

540005200050000480004600044000420004000038000 (d)Figure 5.19: Phase diagrams in di�erent projections of the system C1{C6{H2S attricritical composition xC1 = 0:53572, xC6 = 0:024992 [22].and locate the invariant 4-phase point and subsequent trace the 2-phase/3-phase boundaries.However, in this example the algorithm did not manage to locate the invariant 4-phasepoint. Furthermore, a trial and error variation of the initial 4-phase assembly did not yieldany convergence to the 4-phase point. Despite this failure in the algorithm, surprisingly smalle�ort was needed to compute the entire diagram. A point in the four-phase region was usedas start estimate in the computation. From this single inial point, both the 3-phase/4-phaseboundary and the 1-phase/2-phase boundary were obtained. Since the 4-phase point on thell -envelope was not located, the initial point on the 2-phase/3-phase boundaries is missing. To�nd the remaining 2-phase/3-phase boundaries, three additional initial estimates were required.Computations with one initial point in the llv -region and two initial points in the lll -regioncompleted the plot shown in Figure 5.18.Some numerical di�culties were encountered during the construction of the phase diagram.The corrector step diverged at the tricritical point III and at a 2-phase critical point on a 3-phaseboundary, point II in the diagram. However, these numerical problems do not raise any needfor additional, user-supplied initial estimates. The algorithm successfully located initial pointson the boundaries so that the critical points were approached from both directions.

Page 71: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 53Phase diagrams in di�erent projections are presented in Figure 5.19. No additional bound-ary tracking is required to produce these plots since all the phase properties at the boundariesare known when the phase diagram in S; V;n-coordinates have been constructed. A TP projec-tion is shown in Figure 5.19a. A computed TP projection of the same thermodynamic system isreported by Kohse et al. [26], but the model parameters used in [22] and [26] are not identical.The phase diagrams in Figure 5.19a and [26] are hence not identical, and one critical point isplaced di�erently in the two plots6: The critical point V in Figure 5.19a is not reported by Kohseet al. [26] and as a second mismatch, a 2-phase critical point on the ll/lll -boundary reportedin [26] does not appear in Figure 5.19a.5.5.2 Equilibrium computationsPhase diagrams in di�erent projections are shown in Section 5.5.1. With help of these diagrams,it is possible to investigate the convergence properties of the proposed ash algorithm. Thenumber of coexisting phases are known from the computation of the phase diagrams. Thus, byperforming a series of ash calculations and plotting predicted number of phases in the phasediagram, any erroneous ash calculation will be detected.Results from the equilibrium computations are presented below. Several types of constraintspeci�cations have been tested, and at each constraint speci�cation, two series of ash compu-tations have been run. In the �rst series, shown in sub-�gures \a", initialization of the iterationscheme is performed internally by the ash algorithm. In these computations, a single-phasesystem ful�lling the constraints is computed �rst and subsequent stability analysis and phasesplitting are performed as shown in Section 4.1.In the series labeled \b", the equilibrium phases found in previous equilibrium computationis used as initial estimate7.TV constraint speci�cationNo transforms of energy surfaces are involved in the equilibrium computations since the ther-modynamic model is an explicit function of the coordinates T; V;n. Furthermore, since theconstraints are linear in any respect, these constraint speci�cations should yield the optimiza-tion problems that are most easily converged.6 When phase diagrams are computed by the proposed algorithm, it is not possible to locate critical pointsaccurately. The critical points that are included in the �gures have been found by manual inspection of thefollowing characteristic feature of the coexisting phases:According to the theory of critical points in uid mixtures, see Mistura [35], a critical point is characterized by@2g1=@x2 = 0 @3g1=@x3 = 0 @4g1=@x4 > 0where the energy density g1 is a function of one density, x, and c = number of components intensive variables. Inthe current example, an appropriate energy density can be g1 = Ts�P regarded as a function of s and the �elds�, where s is the entropy density. From the theory of the Legendre transform, the second order derivative cor-responding to @2g1=@x2 is obtained by V @2@S2L[n]U(S; V;n). Thus, by inspecting the value of the second orderderivative for each phase on the boundaries, relative good estimates of the solution of V @2@S2L[n]U(S; V;n) = 0is obtained. It is, however, not possible to con�rm that the third order derivatives vanish at the same points.7 When the constraint speci�cations are varied, only one constrained value is changed between two subsequentcomputations. If the values that are varied cover the plane, as in a phase diagram, the sequence of subsequentpoints looks like �#� ! �"� ! : : : . A similar sequence is possible also when an arbitrary number of values are varied.

Page 72: Computation of phase equilibria in uid mixtures

54 Chapter 5: Computational results

v=litermol-1T=K

0.0650.060.0550.050.045

235230225220215210205200195190 (a) v=litermol-1T=K

0.0650.060.0550.050.045

235230225220215210205200195190 (b)Figure 5.20: Computed number of phases by T; V;n constraint speci�cation in tricrit-ical and four-phase region of the C1{C6{H2S system. A missing point in the plotsindicates failure/divergence in the ash computation. Computed number of phases arelabeled according to Single phase Two phase equilibriumThree phase equilibrium Four phase equilibriumHowever, the algorithm failed in some computations. In the computations where the initialphase assembly is a single phase, Figure 5.20a, the algorithm failed to locate one 3-phase andone 4-phase point. At T = 195 K, v = 0:0482 litermol-1, a constraint corresponding to 3-phaseequilibrium, the last successful converged assembly in the computation consisted of three phaseswhere one of the phases is intrinsically unstable. In the ash algorithm, an intrinsic unstablephase is replaced by two stable phases before the iteration is resumed. The algorithm thusattempts to converge a 4-phase assembly in a 3-phase region, and, during the iteration, the sizeof one phase will inevitably approach zero. The vanishing phase is excluded from the assembly.If the vanishing phase is one of the phases that recently have been introduced into the assembly,cycling will occur in the algorithm. This failure is hence an example of a major aw in theproposed ash algorithm.The algorithm also fails to compute a point in the 4-phase region at T = 200:6 K; v =0:0506 litermol-1. In this computation, a metastable 3-phase assembly was found without nu-merical di�culties and the stability search provided a fourth phase. This trial phase was includedin the assembly, but the size of the included phase found from Equation (4.9) turned out to beextremely small. The four-phase assembly was hence poorly initialized and the system did notconverge within a reasonable number of iterations.In the computations where the phase assembly found at a nearby constraint speci�cationis used as initial estimate, see Figure 5.20b, this four-phase point is calculated without anydi�culties. However, providing good initial estimates in multi-phase regions does not eliminateall the problems in the ash algorithm. Figure 5.20b shows that the algorithm still fails tocompute a three-phase equilibrium point. The reason for divergence is as explained above.

Page 73: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 55SV constraint speci�cationIn this example, there is a mismatch between the coordinates of the phase model and theconstraint speci�cation. Since the natural coordinates of the EOS are T; V;n, a transformationis utilized in the computations: Internal energy surfaces are provided by the inverse Legendretransform U = L-1[T ]A(T; V;n). Furthermore, computations at speci�ed S; V;n is a good testexample of the global convergency of the Newton method since the temperature is not initializedproperly.The results are shown in Figure 5.21. In the computations where initialization is performedinternally by the algorithm, Figure 5.21a, the correct number of phases are found in the single-phase, the two-phase and the four-phase regions. The algorithm fails to converge at a fewconstraint speci�cations in the three-phase region. In the three-phase region, the divergingcomputations all follow the same pattern. As explained in previse example, cycling occurs sincethe algorithm attempts to converge a four-phase assembly.In the computation where a converged assembly is used as initial estimate, Figure 5.21b,all the ash calculations were successful.

v=litermol-1s=JK-1 mol-1

0.0650.060.0550.050.045

130125120115110(a) v=litermol-1

s=JK-1 mol-10.0650.060.0550.050.045

130125120115110(b)Figure 5.21: Computed number of phases by S; V;n constraint speci�cation in tricrit-ical and four-phase region of the C1{C6{H2S system. A missing point in the plotsindicates failure/divergence in the ash computation. Computed number of phases arelabeled according to Single phase Two phase equilibriumThree phase equilibrium Four phase equilibrium

Page 74: Computation of phase equilibria in uid mixtures

56 Chapter 5: Computational resultsUV constraint speci�cationIn the previous examples, the computations are based on minimization of a sum of energy func-tions. With U; V;n constraints, the functions utilized by the algorithm are of the Massieu type,and the governing principle is a maximization problem. The Massieu functions are evaluatedaccording to P[S]L-1[T ]A(T; V;n), and the computed Newton directions in the algorithm are henceprojected twice before the coordinates of the basic surfaces are updated.In Section 4.1.3, it is claimed that the performance of the proposed algorithm is not in u-enced by the number of transforms in the thermodynamic functions. The computations withU; V;n constraints con�rm that the convergence properties is not reduced. The results of theUV - ashes shown in Figure 5.22 resemble Figure 5.21. A poor strategy for splitting of intrinsi-cally unstable phases is again revealed, but there are no signs of numerical problems due to theMassieu transformation.Similar to the computations with S; V;n constraints, divergence does not occur when goodinitial estimates are provided, see Figure 5.22b. The correct number of phases are not obtainedat every constraint speci�cation. At v = 0:0458 litermol-1; u = 42500 Jmol-1, a point in thethree-phase region, the computed number of phases is only two. However, this indicates afailure in the stability search and not an error in the equilibrium computation.

v=litermol-1u=Jmol-1

0.0650.060.0550.050.045

48000470004600045000440004300042000 (a) v=litermol-1u=Jmol-1

0.0650.060.0550.050.045

48000470004600045000440004300042000 (b)Figure 5.22: Computed number of phases by U; V;n constraint speci�cation in tricrit-ical and four-phase region of the C1{C6{H2S system. A missing point in the plotsindicates failure/divergence in the ash computation. Computed number of phases arelabeled according to Single phase Two phase equilibriumThree phase equilibrium Four phase equilibrium

Page 75: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 57HP constraint speci�cation, isenthalpic ashThe theory for the EOS based isenthalpic ash was brie y discussed in Section 2.2. As a resultof this constraint type, the thermodynamic functions involved in the computations will be acombination of Massieu type functions and shifted surfaces. By the notation in Table 4.1,the overall transform can be written concisely as P[S]S[0;�P �;0]L-1[T ]A(T; V;n) where P � is thepressure speci�ed in the constraint. One peculiarity with this Massieu function is that it is nota function of the enthalpy, but instead an implicit function of a shifted internal energy function.Since the object function in the optimization problem is quite special, the problem formulationis explained more detailed in this example.As shown in Section 2.2, the functional form of the shifted internal energy surface isU(S; V;n) = S[0;�P �;0]L-1[T ]A(T; V;n) = TS + �(�P ) � (�P �)�V + �Tn. The shifted internalenergy function U will be equal to the enthalpy at ful�lled pressure speci�cation. The variablesin the kernel routine of the equilibrium computation can be identi�ed from the �nal transformof the thermodynamic functions. In this example, the Massieu function can be writtenS(U ; V;n) = P[S]U(S; V;n) = 1T �U � �(�P )� (�P �)�V � �Tn�where the �rst-order derivatives are@S@U = 1T ; @S@V = � 1T �(�P )� (�P �)� and @S@ni = � 1T �iThe linear constraints of the isenthalpic ash can thus be written2664 1 0 0 0 00 0 1 0 00 0 0 1 00 0 0 0 1 37758>>>>><>>>>>:266664 UVnC1nC6nH2S

377775phase 1+266664 UVnC1nC6nH2S

377775phase 2+ � � � � 266664 H�V �n�C1n�C6n�H2S3777759>>>>>=>>>>>; = 2664 0000 3775When the isenthalpic ash is formulated in terms of U , the constraints in extensive coordinateswill be in accordance with the general linear constraints A�PiP Ti xi�b � = 0. In this example,the matrices P i will be identity since the coordinates of all phases agree in both number andorder. The �rst-order conditions that are solved, gi + P iAT� = 0, are, when written out indetails,2666664 1T� 1T (�P + P �)� 1T �C1� 1T �C6� 1T �H2S

3777775phase i+2666664 1 0 0 00 0 0 00 1 0 00 0 1 00 0 0 1

377777526664 �1�2�3�437775 = 2666664 1T + �1� 1T (�P + P �)� 1T �C1 + �2� 1T �C6 + �3� 1T �H2S + �4

3777775phase i=2666664 00000

3777775In addition to showing that the temperature and chemical potentials of each component attainidentical values in all phases, ful�lled �rst-order conditions also insure that the pressure in eachphase is equal to the pressure speci�ed in the problem formulation. As a consequence of P = P �,a shifted function U will be identical to the enthalpy.Results of the isenthalpic ash calculations in the four-phase region and the nearby two-phase and three-phase regions are presented in Figure 5.23. In the computations, three transfor-mations have been performed on the thermodynamic functions, and two of the transformationsare nonlinear. It seems, however, that the transformations have no in uence on the convergency

Page 76: Computation of phase equilibria in uid mixtures

58 Chapter 5: Computational resultsof the algorithm. The only failure in the computations, see Figure 5.23a, occur in the three-phase region. This divergence is due to the reasons as explained in the discussion of the TV ash problem. When good initial estimates are provided, Figure 5.23b, all the computationsare successful.

h=Jmol-1P=bar

45000446004420043800

62605856545250484644 (a) h=Jmol-1P=bar

45000446004420043800

62605856545250484644 (b)Figure 5.23: Computed number of phases by H;P;n constraint speci�cation in thefour-phase region of the C1{C6{H2S system. A missing point in the plots indicatesfailure/divergence in the ash computation. Computed number of phases are labeledaccording to Single phase Two phase equilibriumThree phase equilibrium Four phase equilibriumTable 5.5: Critical data, m-factors [22], binary interaction coe�cients and ideal gas pure com-ponent properties at 1 atm and 25 �C [3].Component PC TC m-factor Interaction coe�cients c�P s�Bar K CH4 H2S Jmol-1K-1 Jmol-1K-1CH4 46.0 190.4 0.501975089 36 186H2S 89.4 373.2 0.634278983 0.080 34 206C6H14 30.1 507.5 0.935083112 0.000 0.050 143 388

Page 77: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 595.6 Stability analysisThe trajectory method described in Section 4.3 is intended to be used in connection with thephase stability problem only, therefore, examples presented here are limited to such tests. Thehomotopy de�ned in Equation (4.15) may connect several optima of a function. The phasestability problem, see Appendix D.3.2, is in the most general form a criterion on non-negativityof a homogeneous function in several variables. The test stability function � is hence un-bounded and cannot, in its general form, be the object function in a continuation method.It is, however, trivial to formulate an equivalent stability criterion as a global minimizationproblem. One simple approach is i.e. to re- 200010000 nC10/mol0.40.30.20.10nC1/mol 0.80.6Trivial minimum#Trajectory#�=J

Figure 5.24: Stability test function visualized fora binary mixture.duce the number of independent variables byone and then seek the minimum. By keepingone variable constant, the function will looseits �rst-order homogeneity and consequentlybe bounded downward. In this approach, oneof the variables in the thermodynamic modelis constant in the stability search. One hashence to choose a speci�c extensive variableby some criterion. In situations where thethermodynamic model is explicit in tempera-ture, volume and mole numbers, it is naturalto exclude volume from the search space. By the notation in Table 1, the stability test functionsin this situation reads �(n j V; T �; P �;��) = V ��P�(�P �)�+nT(����) where T �, P � and ��are temperature, pressure and chemical potential at composition which is tested for thermody-namic stability. The function � is hence a function of several variables with one trivial optimum,and accordingly, the prerequisites for the trajectory method is ful�lled. So, by the substitutionsx n, f �, the trajectory method can be Eigenvalue �/50 J mol�2Homotopy parameter �/50 J mol�2Test function f/J

t=mol 1.51.2510.750.50.250-0.25

4002000-200-400-600-800Figure 5.25: Characteristic features along thetrajectory in Figure 5.24.

demonstrated on stability test functions.To present a test function graphically,the number of independent variables cannotexceed two. In one variable cases the homo-topy is identical to the domain of the inde-pendent variable, and examples are hence notrelevant. A test function of two variables isshown in Figure 5.24. Neither the composi-tion nor the thermodynamic data entered intothe physical model are required to understandthe plot, and are, for the sake of complete-ness, given in Table 5.6. The trajectory inFigure 5.24 runs from the trivial minimumthrough an apparently plane region before theglobal minimum is located. From the �gure, it is hard to see that the initial state is a localminimum and that an inde�nite region isolates the global and the trivial solution. Details onthe curvature of the energy surface are revealed by plotting the smallest eigenvalue of the Hes-sian along the trajectory, see Figure 5.25. At the trivial solution, t = 0 in the �gure, it is seenthat the eigenvalue is positive. The direction of the integration is chosen such that the globalminimum occurs at positive t. Figure 5.25 clearly shows that there is an inde�nite region at0:2 6 t 6 0:6 since the eigenvalue is negative. A plot of the homotopy parameter � is alsoincluded in the �gure. It can be seen that the homotopy parameter and the eigenvalue intersect

Page 78: Computation of phase equilibria in uid mixtures

60 Chapter 5: Computational resultsat the minimum of �, hence _� and �� � have equal signs at t > 0. Furthermore, it can be seenfrom the �gure that the global minimum of the test function is characterized by � = 0.Presentation of the characteristic features along the trajectory in Figure 5.25 is indeedpossible for test functions of any number of variables. To investigate the capabilities of theproposed trajectory method, plots similar to Figure 5.25 are also presented in Figure 5.26 for a3 component system. To set up a case where the stability test function has several local minima,the composition at a four-phase equilibrium point was used as the trial composition. If thetrajectory method is capable of locating all the minimum points, the test function should hencetouch the abscissa four times. An example of this is shown in Figure 5.26. The thermodynamicdata and the equilibrium compositions are given in Table 5.5 and Table 5.7, respectively.

Eigenvalue �/100 J mol�2Homotopy parameter �/100 J mol�2Test function f/Jt=mol 10.50-0.5-1-1.5

1050-5-10 (a)�� f

t=mol 0.60.40.20-0.2-0.4

420-2-4 (b)Figure 5.26: Characteristic features along a trajectory. The object function of thecontinuation method is the stability test function of a ternary mixture characterized bySRK EOS, the model parameters are given in Table 5.5. Part b is an enlarged portionof the region near the initial point of the trajectory.In Figure 5.26, phase 1 in Table 5.7 is usedEigenvalue �/100 J mol�2Homotopy parameter �/100 J mol�2Test function f/J

t=mol 10.80.60.40.20-0.2

1050-5-10Figure 5.27: Characteristic features along a tra-jectory.

as the trial composition. In analogy with theprevious example, the sign of � � � can beexploited in the computation of _�. For t < 0,it is seen that ��� and _� have opposite signs.Initiation of the stability searches withthe compositions of phase 2 and 3 in Table 5.7give results similar to those shown in Fig-ure 5.26. These compositions correspond tothe two rightmost minima of f in Figure 5.26.The trajectories do, however, not coincidecompletely since the gradient solution dependson the initial point. When the stability searchis initiated with the composition of phase 4,the composition at the leftmost minima inFigure 5.26, it is revealed that the trajectory method is not guaranteed to locate all minima.Computed f , � and � along this trajectory are shown in Figure 5.27. As can be deduced fromFigure 5.27, the trajectory approaches the boundary of the domain without locating the fourth

Page 79: Computation of phase equilibria in uid mixtures

Chapter 5: Computational results 61minimum. However, since the algorithm can be restarted at all stationary points of the objectfunction, the versatility of the proposed trajectory method depends only on its ability to locatethe nearest stationary point. In the search for stationary points, see page 34, the trajectory isfollowed until an optimum of � is detected, and the next stationary point is located by root�nding.Table 5.6: Composition and chemical potentials of the single phase C1{C10 system atT � = 293:15 K. The pressure P � = 10 bar and the chemical potentials �� are computedat volume V = 0:000108999 m3 using PR EOS. m-factors are computed according tom = 0:37464 + 1:54226! � 0:26992!2 [40]. The binary interaction coe�cient betweenC1 and C10 is 0.042.n �� TC PC !mol Jmol-1 K barC1 0.652679 11530:8 190.4 46.0 0.0109C10 0.347321 �15791:3 617.7 21.2 0.4902Table 5.7: Computed compositions of equilibrium phases in the CH4{H2S{C6H14 systemat temperature 202 K. Computed equilibrium pressure is 53.6106133 bar.Volume/liter Mole numbersCH4 H2S C6H14Phase 1 0.0517574837 0.6652260177 0.2875510399 0.0472229423Phase 2 0.1325652333 0.9579132602 0.0419179944 0.0001687453Phase 3 0.0667286624 0.8841576332 0.1092143667 0.0066280000Phase 4 0.0388958080 0.1663844802 0.8239363125 0.0096792073

Page 80: Computation of phase equilibria in uid mixtures
Page 81: Computation of phase equilibria in uid mixtures

Chapter 6DiscussionEquilibrium computationsThe general equilibrium problem formulated in the theory part of this work is solved by aNewton-Lagrange optimization scheme. The algebraic manipulation of the Newton-Lagrangescheme shown in Appendix D.4 is not strictly required in order to compute the Newton di-rection. When computing the Newton step it is not clear whether one should solve one largesystem of equations, Equation (D.22), or alternatively, perform full matrix inversions of a set ofsmaller matrices and subsequently solve the linear system shown in Equation (D.29). The twoalternatives are mathematical equivalents, but the numerical behavior of the two methods isnot necessarily the same. It is pointed out by Haug-Warberg [21] and Smith et al. [53] that thecoe�cient matrix in Equation (D.29) may become numerically singular due to round-o� e�ectsin the constraint matrix A. Such problems can, however, be avoided if the Newton direction iscomputed from the sparse system. Another argument for calculating the Newton step from thesparse Newton-Lagrange scheme is computation time. A series of matrix inversions and matrixmultiplications will be needed to build the coe�cient matrix in Equation (D.22). There willinevitably be some overhead in these operations, and for thermodynamic systems with relativelyfew chemical components, computing the Newton step from the sparse system will be the leasttime consuming.In the proposed algorithm, the Newton direction is computed by the partitioning tech-nique since also the signature of each Hessian can be obtained when individual inversions areperformed. A constraint matrix with orthogonal rows is used in the partitioning of the sparseNewton-Lagrange coe�cient matrix. The algorithm has not been tested thoroughly on reactingsystems, and it remains unclear whether the orthogonalization of the rows in the constraintmatrix really eliminates the numerical problems described in [21] and [53]. However, both thesealternatives for computing the Newton step require not more than say a dozen lines of sourcecode, and is easily incorporated in the algorithm.One peculiarity with the present algorithm is the choice of active variables in the itera-tion scheme. The common approach in EOS based isothermal ash calculations [32, 38, 61] isto keep the pressure constant in the computation. In the proposed algorithm, the volume ofeach phase are active variables, and the number of unknowns are therefore slightly increasedcompared to classic algorithms. However, the test runs of the algorithm did not indicate anydrawback by also solving the pressure equation iteratively. The algorithm hence works satis-factory on the problem type solved by existing algorithms. Furthermore, due to the generalformulation of the equilibrium problem, the developed algorithm can handle a variety of di�er-ent constraint speci�cations, and convergence of second order is obtained independent of theconstraint speci�cation. 63

Page 82: Computation of phase equilibria in uid mixtures

64 Chapter 6: DiscussionIn the test runs, Chapter 5, the algorithm failed in two di�erent ways. In some tests anerroneous number of phases are calculated, in other computations the algorithm diverged. Themost evident example where the algorithm predicts an incorrect number of phases is the equi-librium computations in Section 5.4.2. The results presented in Figure 5.17 should have (atleast) two more computed points in the two-phase region. The failure is not due to any con-vergence problems. The Newton method successfully computed the pressure of the metastableone-phase system and the correct trial composition was located in the stability search. Ac-cording to the stability criterion, the thermodynamic system is metastable if the tangent planedistance is negative. In the stability search, this criterion is implemented as �� < �� for aspeci�ed small number �. Furthermore, in the stability search the iteration is terminated whenthe two-norm of the Newton step is less than a speci�ed threshold. A wrong rejection of a trialphase in the algorithm shows that these criteria are not su�cient for reliable computations inthe near critical region. This strongly indicates that an elaborate numerical analysis is requiredto resolve the stability problem. Especially, the convergence test in the stability search shouldnot rely entirely on the norm of the Newton step, but also on some second order properties ofthe stability test function. The numerical uncertainty in the computed Lagrange multipliersshould also be considered. Once a reliable criterion is established, the algorithm can easily becorrected.Cycling of the algorithm was experienced in the three-phase region of the ternary mixture,see Section 5.5.2. This is a more severe problem. The cycling occurs due to a poor strategy forstarting a new Newton iteration after converging to an assembly with intrinsic unstable phases.In the present version of the algorithm, intrinsic unstable phases are removed by a QP procedureafter the �rst-order conditions for equilibrium are met. This scheme works eminently in mostsituations, but in order to prevent cycling, a completely new strategy must be worked out.One vital part of the algorithm is yet unresolved. The equilibrium computations are per-formed using one common Newton-Lagrange method for all constraint speci�cations, but itseems di�cult to �nd a reliable initialization scheme of the same generality. The proposed ini-tialization scheme utilizes quadratic programming and adjusts only the size of the phases. Thissimple approach cannot be expected to yield good initial estimates in equilibrium computationsof more complex systems.Although the test runs revealed some weak points in the algorithm, some interesting resultswere obtained. There is no accepted benchmark suite for measuring the performance of equi-librium computation algorithms, and it is di�cult to judge whether the examples are adequate.However, repeated success in computing four-phase equilibria, see Section 5.5.2, does not hap-pen by accident. It is also notable that the algorithm handles alternate constraint speci�cationswithout reducing the rate of convergence. Furthermore, the algorithm does not require anyinformation about model speci�c parameters and new phase models can easily be implemented.Construction of phase diagramsThe presented algorithm for phase diagram construction is a spin-o� from the object orientedmodeling of thermodynamic surfaces and should not be regarded as more than a prototype ofwhat can be achieved with a properly designed data structure. The solution scheme utilized inthe phase diagram construction is of a simple nature, and the numerical problems encounteredin the test examples are far from unexpected. In the examples, divergence were encounteredat some critical points. It is, however, remarkable that the algorithm seems una�ected byordinary two-phase critical points. The problems arise in slightly more complex situations likenear critical azeotrope, Section 5.4.1, two-phase critical point on three-phase boundary and

Page 83: Computation of phase equilibria in uid mixtures

Chapter 6: Discussion 65tricritical point, Section 5.5.1.The performance of the algorithm can hopefully be improved by a more sophisticatedintegration scheme. One straightforward modi�cation of the present predictor corrector schemeis adaptive step-size control. It is also possible to improve the predictor by extrapolation, eitheras proposed in [30] or by established techniques for ODE integration.The algorithm also failed to locate an invariant point in the construction of the phasediagram for a system exhibiting four-phase equilibrium. Invariant points are located by ordi-nary root �nding techniques. Newton's method with step length adjustment is utilized in thealgorithm, and the failure in the computation is probably due to the merit function. Otherweighting matrices than those in Equation (4.14) are possible, but how to �nd a suitable meritfunction is yet an unresolved problem.To construct a phase diagram, the algorithm blindly follows the path where the �rst-orderconditions of thermodynamic equilibrium are ful�lled. A possible re�nement of the algorithm isto include stability tests in order to avoid metastable branches of the diagram. It is, however,unlikely that a general purpose algorithm for construction of phase diagrams will work withoutany manual interaction with the user.The generality seems to be both the strength and the weak part of the proposed algorithm.By making the algorithm so general that no information on the problem type is accessible tothe kernel the problem can be poorly scaled and there is no obvious best way to perform thecorrector step. On the other hand, the general nature of the algorithm enables construction ofentirely di�erent phase diagrams as PT , Tx and Px projections. Furthermore, the designed datatype for modeling thermodynamic functions was found to be an excellent tool for computingphase properties. As a curiosity, the second-order derivatives needed to verify the conditions ofcritical points, see [35] and the footnote on page 53, is one of the output capabilities.Stability computationThe trajectory method utilized in the phase stability analysis was found to be very reliable. Itsuccessfully located all minima of the phase stability functions in all the test cases. However,the method is quite time consuming due to the many expensive calculations of Hessians andeigenvectors of Hessians. It is also notable that the trajectory method can be particularly timeconsuming when applied to relatively simple problems where the minima of the test functionare separated by a large inde�nite region. The continuation method will in such cases traversea long path before the minimum is reached whereas an iterative method will, when provided asu�cient good initial estimate, locate the minimum in few iterations. The proposed trajectorymethod is hence not appropriate as a general purpose algorithm for stability computations.Due to the success in the computations, the trajectory method may be appropriate in thestability testing of systems with complex phase behavior. However, it is not proved that anytrajectory method is guaranteed to locate all the minima of a test function. Thus, if mathe-matical certainty for global optimization is desired, the trajectory method is not an alternativeto i.e. interval analysis [23].

Page 84: Computation of phase equilibria in uid mixtures
Page 85: Computation of phase equilibria in uid mixtures

References[1] Ahmed T.H.: Comparative Study of Eight Equations of State for Predicting HydrocarbonVolumetric Phase Behavior,Soc. Petrol. Eng. Res. Eng. 2, 1988.[2] Aris R.: Vectors, Tensors and the Basic Equations of Fluid Mechanics,Prentice-Hall, Englewood Cli�s, 1962.[3] Aylward G.H, Findlay T.J.V.: SI Chemical Data (second edition)John Wiley & Sons, Sidney, 1974.[4] Baker L.E., Pierce A.C., Luks K.D.: Gibbs Energy Analysis of Phase Equilibria,Soc. Petrol. Eng. J., 22, 1982.[5] Berck P., Syds�ter K.: Matematisk formelsamling for �konomer,Universitetesforlaget, Oslo, 1992.[6] Branin F.H.: Widely Convergent Method for Finding Solutions of Simultaneous NonlinearEquations,IBM J. Res. Develop., 9, 1972.[7] Brinkley S.R.: Calculation of the Equilibrium Composition of Systems of many Con-stituents,Journal of Chemical Physics, 14, 1947.[8] Callen H.B.: Thermodynamics and an Introduction to Thermostatistics,Wiley, New York, 1982.[9] Connoly J.A.D., Kerrick D.M.: An Algorithm and Computer Program for Calculating PhaseDiagrams,CALPHAD 11(1), 1987.[10] Coplien J.O.: Advanced C++ Programming Styles and Idioms,Addison-Wesley Publishing Company, Reading, 1992.[11] Dahlquist G., Bj�orck, �A.: Numerical Methods,Prentice-Hall, Englewood Cli�s, 1974.[12] Diandreth J.R., Paulaitis M.E.: Multiphase Behavior in Ternary Fluid Mixtures: A CaseStudy of the Isopropanol-Water-CO2 System at Elevated Pressures,Chem. Eng. Sci., 44(5), 1989.[13] Dixon L.C.W., Szeg�o G.P.: Towards Global Optimisation,North-Holland Publishing Company, Amsterdam, 1975.67

Page 86: Computation of phase equilibria in uid mixtures

68 References[14] Dixon L.C.W., Szeg�o G.P.: Towards Global Optimisation 2,North-Holland Publishing Company, Amsterdam, 1978.[15] Fletcher R.: Practical Methods of Optimization (second edition),John Wiley & Sons, Chichester, 1990.[16] Gibbs J.W.: The Collected Works of J. Willard Gibbs, Volume 1,Longmans, New York, 1928.[17] Goldstein A.A., Price J.F.: On Descent from Local Minima,Math. Computation, 25, 1971.[18] Grabowski M.S., Daubert Y.W.: A Modi�ed Soave Equation of State for Phase EquilibriumCalculations,Ind. Eng. Chem. Process Des. Dev., 17(4), 1978.[19] Gri�ths R.B., Wheeler J.C.: Critical Points in Multicomponent Systems,Phys. Rev. A, 2(3), 1970.[20] Guddat J., Guerra Vasquez F., Jongen H.Th.: Parametric Optimization: Singularities,Pathfollowing and Jumps,B.G. Teubner, Stuttgart, 1990.[21] Haug-Warberg, T.: Computation of Thermodynamic Equilibria,Doktor ingeni�ravhandling 1988:42, Institutt for Fysikalsk Kjemi, Norges TekniskeH�gskole, Trondheim, 1988.[22] Haug-Warberg, T.: Private communication.[23] Hua J.Z., Brennecke J.F., Stadtherr M.A.: Reliable Computation of Phase Stability usingInterval Analysis: Cubic Equation of State Models,Computers Chem. Engng., 22(9), 1998.[24] Karpov K.I., Chudnenko K.V., Kulik D.A.: Modeling Chemical Mass Transfer in Geo-chemical Processes: Thermodynamic Relations, Conditions of Equilibria, and NumericalAlgorithms,American Journal of Science, 10, 1997.[25] Knuth D.E.: The TEXbook,Addison-Wesley, Reading, 1984.[26] Kohse B.F., Heidemann R.A.: Tricritical Lines and Multiphase Equilibria in QuaternaryMixtures,Fluid Phase Equilibria, 75, 1992.[27] Lootsma F.A.: Numerical Methods for Non-Linear Optimization,Academic Press, London, 1972.[28] Luenberger D. G.: Linear and Nonlinear Programming (second edition),Addison-Wesley, Reading, 1984.[29] Meyers S.: More E�ective C++,Addison-Wesley Publishing Company, Reading, 1996.

Page 87: Computation of phase equilibria in uid mixtures

References 69[30] Michelsen M.L.: Calculation of Phase Envelopes and Critical Points for MulticomponentMixtures,Fluid Phase Equilibria, 4, 1980.[31] Michelsen M.L.: The Isothermal Problem. Part I. Stability Analysis,Fluid Phase Equilibria, 9, 1982.[32] Michelsen M.L.: The Isothermal Flash Problem, Part II. Phase-Split Calculation,Fluid Phase Equilibria, 9, 1982.[33] Michelsen M.L.: Some Aspects of Multiphase Calculations,Fluid Phase Equilibria, 30, 1986.[34] Michelsen M.L.: Multiphase Isenthalpic and Isentropic Flash Algorithms,Fluid Phase Equilibria, 33, 1987.[35] Mistura L.: Critical Phases in Multicomponent Fluid Mixtures,J. Phys. A: Math. Gen., 9(12), 1976.[36] Modell M., Reid R.C.: Thermodynamics and its Applications,Prentice-Hall, Englewood Cli�s, 1974.[37] Nemhauser G.L., Rinnooy Kan A.H.G., Todd M.J.: Handbooks in Operations Research andManagement Science, Volume 1,Elsevier Science Publishers, Amsterdam, 1989.[38] Nghiem L.X., Li Y.-K.: Computation of Multiphase Equilibrium Phenomena with an Equa-tion of State, Fluid Phase Equilibria, 17, 1984.[39] Nulton J.D., Salamon P.: Geometry of the Ideal Gas,Physical Review A, 31(4), 1985.[40] Peng D.-Y., Robinson D.B.: A new Two-Constant Equation of State,Ind. Eng. Chem. Eng. Fundam., 15(1), 1976.[41] Prausnitz J.M.: Molecular Thermodynamics of Fluid-Phase Equilibria,Prentice-Hall, Englewood Cli�s, 1969.[42] Press W.H., Teukolsky S.A, Vetterling W.T., Flannery B.P.: Numerical Recipes in C: TheArt of Scienti�c Computing,Cambridge University Press, New York, 1992.[43] Rall L.B.: Automatic Di�erentiation: Techniques and Applications,in Lecture Notes in Computer Science No. 120, Springer-Verlag, Berlin, 1981.[44] Rall L.B.: The Arithmetic of Di�erentiation,Mathematics Magazine, 59, 1986.[45] Ravindran A., Lee H.K.: Computer Experiments in Quadratic Programming Algorithms,European J. of Operational Research, 8, 1981.[46] Reid R.C., Prausnitz J.M., Poling B.E.: The Properties of Gases and Liquids (fourth edi-tion),McGraw-Hill, New York, 1987.

Page 88: Computation of phase equilibria in uid mixtures

70 References[47] Ricci J.E.: The Phase Rule and Heterogeneous Equilibrium,D. Van Nostrad Company, New Jersey, 1951.[48] Robinson D.B., Peng D.-Y.: The Characterization of the Heptanes and Heavier Fractionsfor the GPA Peng-Robinson Programs,Gas Processors Association, Research Report, RR-28, 1978.[49] Rowlinson J.S, Swinton F.L.: Liquids and Liquid Mixtures (third edition),Butterworth Scienti�c, London, 1982.[50] Scott R.L.: Multicritical Phenomena in Fluid Mixtures,in Proceedings of the Eighth Symposium on Thermophysical Properties Volume 1, ASMF,1982.[51] Seider W.D., Brengel D.D.: Nonlinear Analysis in Process Design,AIChE Journal, 37 (1), 1991.[52] Smith W.R., Missen R.W.: Calculating Complex Chemical Equilibria by an ImprovedReaction-Adjustment Method,The Canadian Journal of Chemical Engineering, 46(8), 1968.[53] Smith W.R., Missen R.W.: Chemical Reaction Equilibrium Analysis,Wiley, New York, 1980.[54] Soave G.: Equilibrium Constants from a Modi�ed Redlich-Kwong Equation of State,Chem. Eng. Sci., 27, 1972.[55] Strang G.: Linear Algebra and its Applications (second edition),Academic Press, New York, 1982.[56] Stroustrup, B.: The C++ Programming Language,Addison-Wesley, Reading, 1986.[57] Stroustrup, B.: The C++ Programming Language (second edition),Addison-Wesley, Reading, 1991.[58] Stroustrup, B.: The C++ Programming Language (third edition),Addison-Wesley, Reading, 1997.[59] Stull D.R., Prophet H.: JANAF Thermochemical Tables (second edition),United States Department of Commerce, National Bureau of Standards, Washington, 1971.[60] Sun A.C, Seider W.D.: Homotopy-Continuation Method for Stability Analysis in the GlobalMinimization of the Gibbs Free Energy,Fluid Phase Equilibria, 109, 1995.[61] Trangenstein J.A.: Customized Minimization Techniques for Phase Equilibrium Computa-tion in Reservoir Simulation,Chem. Eng. Sci., 42(12), 1987.[62] Traub J.F.: Iterative Methods for the Solution of Equations,Prentice-Hall, Englewood Cli�s, 1964.[63] White W.B., Johnson S.M., Dantzig G.B.: Chemical Equilibrium in Complex Mixtures,Journal of Chemical Physics, 28, 1958.

Page 89: Computation of phase equilibria in uid mixtures

Appendix AModels of thermodynamic propertiesA.1 Pure component chemical potentialEmpirical data on properties of pure components are often represented as heat capacity func-tions. The molar heat capacity is related to molar enthalpy, h, bycP def= @h@T where h = h(T; P; n1; : : : )In a one component system, molar enthalpy is trivially related to chemical potential byh = �+ Ts = �� T @�@T , and, by derivation, cP = �T @2�@T 2 . Hence, the functional relation betweenheat capacity and chemical potential may be found by integration of@2�@T 2 = �cP (T )TWith the boundary conditions @�@T ��T=T � = �s�, �(T �) = ��, one �nds@�@T = �s� � TZT � cP (�)� d�� = �� � (T � T �)s� � TZT � tZT � cP (�)� d� dtIn the integral above, the limits of integration may be interchanged:8<: T � 6 � 6 t^T � 6 t 6 T 9=;, T � 6 � 6 t 6 T , 8<: � 6 t 6 T^T � 6 � 6 T 9=;Hence TZT � tZT � cP (�)� d� dt = TZT � TZ� cP (�)� dt d� = TZT � (T � �)cP (�)� d�= T TZT � cP (�)� d� � TZT � cP (�) d�71

Page 90: Computation of phase equilibria in uid mixtures

72 Appendix A: Models of thermodynamic propertiesand the �nal expression for the chemical potential is� = �� � (T � T �)s� � T TZT � cP (�)� d� + TZT � cP (�) d�(A.1)A.2 Ideal gasThe phase model ideal gas is characterized by the two features:� The mixture obeys the ideal gas law PV = NRT .� The components form an ideal mixture.The functional form of the model is so simple that it allows explicit formulation of three di�erentenergy surfaces. These are, respectively, Gibbs energy, Helmholtz energy and Grand canonicalpotential. Concerning the implementation of the model, the Helmholtz surface is considered themost attractive: By implementing the thermodynamic model as a Helmholtz surface equilibriumcomputations at speci�ed T; V;n can be performed without any transformations. Furthermore,computations at speci�ed T; P;n will utilize a shifted surface which is merely a linear transformof the Helmholtz potential function. In the alternative implementations of the ideal gas phasemodel, G = G(T; P;n) will require the nonlinear inverse Legendre transformation when thepressure is not speci�ed in the constraint. The Grand canonical potential = (T; V;�) is theleast appealing candidate since the inverse Legendre transform must be performed when theconstraint speci�cations di�er from T; V;�.Helmholtz energy can, however, not be represented more compact than the homogeneousfunction A(T; V;n) = V @A@V +Pi ni @A@ni . The derivatives are,@A@V � (�P ) = �NRTV@A@ni � �i = ��i (T; P �) +RT ln niRTP �V(A.2)where P � is the reference pressure and ��i (T; P �) is the pure component chemical potential atthe system temperature and the reference pressure. The simple nature of the ideal gas modelcan also be exploited in the phase stability test. To inspect whether the ideal gas model isstable or not compared to a state characterized by T �;�P �;��, one should note that the teststability function � = ( T �T � )S+ (�P +P � )V+Pi( �i � ��i )niis reduced to � = (�P+P �)V at T = T � and � = ��. The phase stability criterion is, therefore,equivalent to �P + P � > 0 where the pressure is found from Equation (A.2) as:�P = �P �Xi exp ��i � ��i (T; P �)RT

Page 91: Computation of phase equilibria in uid mixtures

Appendix A: Models of thermodynamic properties 73A.3 Cubic equation of stateA variety of equations of state (EOS) have been proposed for the representation of uid phasebehavior. The most popular equations are those derived from the van der Waals' classical equa-tion, i.e. Soave-Redlich-Kwong EOS [54] and Peng-Robinson EOS [40]. Recent modi�cationsof these models are reviewed by Ahmed [1]. By suitable choices of parameters [21], both theSoave-Redlich-Kwong EOS and the Peng-Robinson EOS can be represented by the same genericequation. A representation somewhat di�erent from those appearing in the literature is that inEquation (A.3), the parameters d1, d2, a and b will be explained later:�P = �NRTV � b � ab � 1V + d1 b � 1V � d2 b� (A.3)Cubic EOS are inherently explicit in T; V;n which make them easy to implement as Helmholtzsurfaces. From the knowledge of �P = @A@V , Equation (A.3) can be integrated to �nd Helmholtzenergy. However, due to the logarithmic terms in the integral, Helmholtz energy will diverge atin�nite volume. The ideal gas Helmholtz energy, Aig, also approach in�nity in the zero pressurelimit, and L'Hopital's rule applies:limV!1 AAig = limV!1 �P�NRT=V = 1Hence, ideal gas can be introduced as a reference state, and the Helmholtz energy is found asA = Aig + VZ1 ��P + NRTV � dV= �NRT +Xi ni���i (T; P �) +RT ln niRTP �V � +NRT ln VV � b � ab ln V + d1 bV � d2 b (A.4)A.3.1 Model speci�c parametersIn the original papers [40, 54], the parameters in Peng-Robinson and Soave-Redlich-Kwong EOSwere basically the pure component critical pressure PC , the critical temperature TC and theacentric factor1 !, as well as binary interaction coe�cients kij between the components i and j.Recent versions of these EOS also take into account temperature-dependent binary interactioncoe�cients, i.e. by inclusion of the term T kT ij. To compute thermodynamic properties in ane�cient way, it is advisable to de�ne a and b in Equation (A.3) in terms of a few derivedparameters. In vector/matrix notation, the following parameters can be de�ned:Parameter Type i'th elementb vector bRTCi=PCi�0 square, diagonal matrix mi + 1�T square, diagonal matrix �mi=pTCiD square, diagonal matrix TCi=pPCiThe matrix D has been introduced in order to de�ne the two last constants that are required:�0 = �2 a R2d1+d2D(K � 1)D�T = �2 a R2d1+d2D KT D1The acentric factor of a component is, see i.e. [41], de�ned by ! = � log10�P s0:7=PC� � 1 where P s0:7 is thesaturation pressure at temperature T = 0:7TC.

Page 92: Computation of phase equilibria in uid mixtures

74 Appendix A: Models of thermodynamic propertiesIn the formula for �0, the binary interaction coe�cients between components i and j is elementij of K. Similarly, the matrixKT is made up of the coe�cients kT ij. The square matrix 1 haselements equal to 1 in each position. Various other symbols that occur in the equations aboveare summarized in Table A.1. Finally, the temperature and mole number dependency of theenergy parameter a and hard sphere volume b in Equations (A.3) and (A.4) can be stated asfollows: � = �0 +pT �T a = 12nT� (�0 + T �T )�n(A.5) b = nTb(A.6)Table A.1: Parameters turning the generalized cubic equation of state into the Peng-Robinson(PR) or Soave-Redlich-Kwong (SRK) phase model. The parameters �+, �� in PR EOS a andb are found by choosing the appropriate sign in �� = (16p2 � 13)1=3 � 95 . The m-factors arecorrelated to acentric factor ! by polynomials, literature references to di�erent correlations areincluded in the table.PR SRKd1 p2 + 1 = 2:414 213 562 373 : : : 1d2 p2� 1 = 0:414 213 562 373 : : : 0ab 15512( �2+ + �2�� 78175 ) = 0:457 235 528 921 : : :332 ( �+ � ��� 5915 ) = 0:077 796 073 904 : : : 19(21=3 � 1)�1 = 0:427 480 233 540 : : :13(21=3 � 1) = 0:086 640 349 965 : : :m 0:37464+1:54226!�0:26992!2 [40]0:3796 +1:485 !�0:1644 !2+0:01667!3 [48] 0:480 +1:574 !�0:176 !2 [54]0:48508+1:55171!�0:15613!2 [18]

Page 93: Computation of phase equilibria in uid mixtures

Appendix BMiscellaneous mathematical formulaeMiscellaneous formulae and theorems are grouped together in this section. Most of the materialsummarized below is show elsewhere [5, 28]. In addition, some more or less trivial relationswhich are applied in previous sections in this thesis, are explained in a somewhat more detailedmanner.B.1 Partial derivatives and matrix notationIn the search for a notation for derivatives of multi-variable functions, the intention is, as far aspossible, to use the conventions of linear algebra. As a consequence, vectors are unless otherwisestated, implicitly de�ned to be column vectors.De�nitionsAs a basis for the notation used in this thesis, the di�erential operator @x is de�ned as:@x = 26664 @@x1@@x2...@@xn37775The operators subscript is indicating the di�erentiated function's variables. Regarded as acolumn vector, @x can be premultiplied with vectorial functions in IR1�m where m is arbitrary:@x : IR1�m ! IRn�mAs stated above, it is tried to adapt traditional matrix notation, and an operator that can onlybe applied to row vectors is not appropriate. The gradient operator rx is now de�ned with thefollowing property when applied to a vector h 2 IRm:rxh = (@xhT)T = 2666664 @h1@x1 @h1@x2 � � � @h1@xn@h2@x1 @h2@x2 � � � @h2@xn... ... . . . ...@hm@x1 @hm@x2 � � � @hm@xn

3777775 (B.1)By these de�nitions, a variety of di�erentiation rules of calculus of functions in one variablecan be cast into the notation of multi-variable functions merely by replacing d=dx by rx. Toestablish such rules, a single element of the gradient is considered.75

Page 94: Computation of phase equilibria in uid mixtures

76 Appendix B: Miscellaneous mathematical formulaeThe chain rule, z = z(x(y))When x is an implicit function of y, the problem is to �nd the gradient ryz expressed by rxzand ryx. The chain rule applied to an element in the gradient reveals(ryz)ij = @zi@yj= Xk @zi@xk @xk@yj= Xk (rxz)ik (ryx)kj= (rxzryx)ij+ryz = rxzryxA special case of the di�erentiation rule above is when z = y. Since ryy � I where I denotesthe identity matrix 2666664 1 0 0 : : : 00 1 0 : : : 00 0 1 : : : 0... ... ... . . . ...0 0 0 : : : 13777775the chain rule in this case yields rxyryx = I and, when dim(x) = dim(y):rxy = (ryx)-1(B.2)Equation (B.2) is now applied to two di�erent coordinate sets with a common subset, x =� rT tT �T and y = � sT tT �T . In a partitioned matrix notation, Equation (B.2) is24 rrs rtsO I 35 = 24 rsr rtrO I 35�1=8<: 24 rsr OO I 3524 I (rsr)-1rtrO I 35 9=;�1

= 24 I �(rsr)-1rtrO I 3524 (rsr)-1 OO I 35= 24 (rsr)-1 �(rsr)-1rtrO I 35Corresponding sub-matrices on the left and right-hand side are of course equal, and the followingtwo relations for the functional dependencies r = r(s; t), s = s(r; t) are obtained:rrs = (rsr)-1(B.3) rts = � (rsr)-1rtr= � rrs rtr(B.4)

Page 95: Computation of phase equilibria in uid mixtures

Appendix B: Miscellaneous mathematical formulae 77The product rule, x = x(z);y = y(z)(rzxTy)i = @@zi Xj xjyj= Xj xj @yj@zi +Xj yj @xj@zi= Xj (x)j (rzy)ji +Xj (y)j (rzx)ji= (xTrzy + yTrzx)i+rzxTy = xTrzy + yTrzx (B.5)The product rule, � = �(y);x = x(y)(ry(x�))ij = @xi@yj� + xi @�@yj= (�ryx+ xry�)ij+ry(x�) = �ryx+ xry� (B.6)B.2 Taylor's TheoremIf a function f has continuous partial derivatives in a region containing the line segment [x1;x2],then there is a � 2 [0; 1] such thatf(x2) = f(x1) +rf(�x1 + (1� �)x2)(x2 � x1) (B.7)Furthermore, if f also has continuous partial derivatives of second order, there exists a � 2 [0; 1]such thatf(x2) = f(x1) +rf(x1)(x2 � x1) + 12(x2 � x1)TF (�x1 + (1� �)(x2 � x1)) (B.8)where F denotes the Hessian of f .B.3 Sherman-Morrison formulaA general inversion identity often referred to as Sherman-Morrison formula [28] reads(A+ cdT)-1 = A-1 � A-1cdTA-11 + dTA-1c (B.9)A similar identity also exists for inversion of the more general matrix A + CDT. The actualformula is easily derived. As a starting point, consider the two productsA-1 (A+CDT) = I +A-1CDTDTA-1 (A+CDT) = (I +DTA-1C)DT

Page 96: Computation of phase equilibria in uid mixtures

78 Appendix B: Miscellaneous mathematical formulaeA combination of these identities now shows(A-1 �A-1C(I +DTA-1C)-1DTA-1) (A+CDT) = Iand these two factors must be inverses of each other. Hence, the Woodbury formula [42] is(A+CDT)-1 = A-1 �A-1C(I +DTA-1C)-1DTA-1(B.10)B.4 Matrix identitiesFor a generally partitioned symmetric matrix, the following factorizations exist:" A CTC B # = " I OCA-1 I #" A OO B �CA-1CT #" I A-1CTO I #(B.11) = " A OC I #" A-1 OO B �CA-1CT #" A CTO I #(B.12) = " I CTB-1O I #" A�CTB-1C OO B #" I OB-1C I #(B.13) = " I CTO B #" A�CTB-1C OO B-1 #" I OC B #(B.14)B.5 Homogeneous functionsB.5.1 Functions of arbitrary degree of homogeneityA function f : IRn ! IR is said to be homogeneous of degree m iff(�x) = �mf(x)(B.15)where � is an arbitrary scalar. Euler's theorem on homogeneous functions is established bydi�erentiating both sides of Equation (B.15) with respect to �. Taylor-expansion of the left-hand side of Equation (B.15) yields,f�(�+��)x� = f��(1 + ��� )x�= �mf(x+ ��� x)= �m n f(x) + ��� nXi=1 xi @f@xi +O���2� o= �mf(x) + �m�1�� nXi=1 xi @f@xi +O���2�= f(�x) + �m�1�� nXi=1 xi @f@xi +O���2�

Page 97: Computation of phase equilibria in uid mixtures

Appendix B: Miscellaneous mathematical formulae 79and, after a simple rearrangement, one �ndsf((� +��)x)� f(�x)�� = �m�1 nXi=1 xi @f@xi +O(��)lim��!0 f((� +��)x)� f(�x)�� = �m�1 nXi=1 xi @f@xi (B.16)Di�erentiation of the right-hand side is straightforward, the result beingm�m�1f(x). Combinedwith Equation (B.16) one has dd�ff(�x) � �mf(x)g = �m�1fPni=1 xi @f@xi � mf(x)g = 0 for allvalues of the parameter �. Hence, Euler's theorem on homogeneous functions of degree m reads:nXi=1 xi @f@xi = mf(x) (B.17)Useful formulae are obtained by repeated partial di�erentiation of Euler's theorem. A �rst orderderivative of Equation (B.17) is@@xk nXi=1 xi @f@xi = nXi=1 ��ik @f@xi + xi @2f@xi@xk�= @f@xk + nXi=1 xi @2f@xi@xk= m @f@xkBy collecting identical terms on the right-hand side, the equation above takes the form,nXi=1 xi @@xi � @f@xk� = (m� 1) @f@xkand, when this result is compared to Equation (B.17), it is seen that @f=@xk also is a ho-mogeneous function, the degree of homogeneity now being m � 1. Further di�erentiations ofEquation (B.17) reduces the degree of homogeneity by one. Explicit expressions for the deriva-tives are summarized in Table B.1 below.B.5.2 First-order homogeneous functionsHomogeneous functions of �rst-order are of special importance to thermodynamics. Althoughthe properties of such functions can be derived from Table B.1 by setting m = 1, a somewhatmore detailed discussion is required to derive a di�erential equation of fundamental importance.A special symbol is now introduced for the partial derivatives of the function:gi def= @f@xiSince the function is considered to be homogeneous of order one, the identity (see Table B.1)nXi=1 xi @2f@xi@xj = 0

Page 98: Computation of phase equilibria in uid mixtures

80 Appendix B: Miscellaneous mathematical formulaeTable B.1: Formulae characterizing homogeneous functions.f(�x) = �mf(x) General property of m'th degreehomogeneous functions.nXi=1 xi @f@xi = mf(x) Euler's theorem on homogeneousfunctions of degree m.nXi=1 xi @@xi @f@xk = (m� 1) @f@xknXi=1 xi @@xi @2f@xk@xl = (m� 2) @2f@[email protected]=1 xi @@xi @mf@xk@xl � � � = 0 General property of (m + 1)'thorder derivatives of m'th degreehomogeneous functions.is valid for all indices j. The di�erential of gi is found by the chain rule:dgi = nXj=1 @gi@xj dxj= nXj=1 @2f@xi@xj dxjThe sum of all xi dgi is hence nXi=1 xi dgi = nXi=1 xi nXj=1 @2f@xi@xj dxj= nXj=1 nXi=1 xi @2f@xi@xj dxj� 0(B.18)Equation (B.18), showing that at most n� 1 di�erentials of a �rst-order homogeneous functionare linearly independent, is in the thermodynamic-related literature known as the Gibbs-Duhemequation. By letting the function f be internal energy, the corresponding Gibbs-Duhem equationreads S dT + V d(�P ) +Xi ni d�i = 0(B.19)The various symbols in Equation (B.19) are explained in Table 1. This result was, of course,known by Gibbs, see [16, page 88]. However, it is not explicitly stated by Gibbs that energyfunctions are �rst-order homogeneous functions. According to Gibbs, the counterpart to Equa-tion (B.18) is derived from the di�erential d� = t d��p dv+�1 dm1+�2 dm2 � � �+�n dmn whichis integrated to � = t� � pv + �1m1 + �2m2 � � � + �nmn and afterwards \di�erentiated in themost general manner". This is, however, a strange argument since di�erentiation cannot resultin anything other than the already known di�erential.

Page 99: Computation of phase equilibria in uid mixtures

Appendix CTransforms of thermodynamicfunctionsVarious transforms of (thermodynamic) functions are discussed in this section. Of theses, theLegendre transform is thoroughly described in the literature, see i.e. Modell et al. [36]. Thetheory of the Legendre transformation has also been presented in vector/matrix notation, seeHaug-Warberg [21], where also explicit formulae for the second order derivatives of Legendretransformed functions are given. A survey of the Legendre transform has, however, also beenincluded in Appendix C.1. The notation in Appendix C.1 is heavily in uenced by [21]. Thereare mainly two reasons for this duplication of known material:The results presented in this work are computed by an algorithm where the Legendretransform is implemented, and much of the formulae and details in Appendix C.1 are needed inthe implementation. Secondly, the inverse Legendre transform is outlined in Appendix C.2 andthe inverse Legendre transform has been implemented. Without the knowledge of the Legendretransform this would have been impossible.Functions that are de�ned implicitly are considered in Appendix C.3. By the results ofAppendix C.3, thermodynamic computations involving Massieu functions are made possible.C.1 Legendre transformationsThe Legendre transformation is a mathematical operation of particular importance in thermo-dynamics. By this technique, di�erentiation of energy functions of alternate variable sets canbe found in a very systematic way. The applications of this transformation are shown elsewherein this thesis, and only the mathematical foundation of Legendre transform is discussed here.Calculation of the derivatives of transformed functions are given special attention.C.1.1 De�nition of the Legendre transformationA general function u = u(x) is now considered. Let x be partitioned into two sets of independentvariables; x = � rT tT �T. The Legendre transform of u with respect to r is then de�ned by:v = v(y) = u�rru r; y= � sT tT �Ts = (rru)T (C.1)In Equation (C.1), the gradient operator applied to u is, see Equation (B.1) on page 75,rru = � @u=@r1 @u=@r2 � � � �. 81

Page 100: Computation of phase equilibria in uid mixtures

82 Appendix C: Transforms of thermodynamic functionsC.1.2 The �rst-order derivatives of a Legendre transformed functionNo complicated operations are needed to di�erentiate the function v de�ned in Equation (C.1),but some de�nitions must be introduced. First, let the Hessian of u be:rx(rxu)T = � Urr UrtUtr Utt �Next, since rru = sT where s is a subset of y, all nontrivial sub-matrices of rxy are alsosub-matrices of rx(rxu)T: rxy = � rrs rtsrrt rtt � = � Urr UrtO I �(C.2)Furthermore, Equation (B.2) shows that ryx now can be found by inversion:ryx = (rxy)-1 = � (Urr)-1 � (Urr)-1UrtO I �(C.3)Applying the product rule for scalar products, Equation (B.5), to the function v yields:rxv = rxu�rx(rru r)= � rru rtu ��rru � I O �� rT � Urr Urt �= � �rTUrr rru� rTUrt �Finally, the derivatives of the Legendre-transformed function with respect to the natural coor-dinates s and t can be found by the chain rule.ryv = rxv (rxy)-1= � �rTUrr rru� rTUrt � � (Urr)-1 �(Urr)-1UrtO I �= � �rT rtu �(C.4)Hitherto, a general function has been considered. However, homogeneous thermodynamic func-tions are of special interest, and it can be shown that a transform of a homogeneous function isa new homogeneous function. If u is �rst-order homogeneous in its entire variable set, the for-mulae shown on page 80 implies u =Pi xi @u=@xi =rru r+rtu t. With this identity insertedinto Equation (C.1), one gets v = rtu t =Pi ti @v=@ti since rtu = rtv. This equation ful�llsthe conditions of a �rst-order homogeneous function, see Equation (B.17), but the function v isseen to be homogeneous in the coordinates t only.C.1.3 Second order derivatives of Legendre-transformed functionAmongst others, Hessians are needed in second order optimization schemes. To determine theHessian of a Legendre transform in terms of the derivatives of the untransformed function, thegeneral formula for a Hessian is not suitable. A less thornful path is to apply the chain rule onright-hand side of Equation (C.4):ry(ryv)T = rx (ryv)Tryx= (ryx)T (rxy)Trx (ryv)Tryx(C.5)

Page 101: Computation of phase equilibria in uid mixtures

Appendix C: Transforms of thermodynamic functions 83In Equation (C.5), (ryx)T (rxy)T = I. The product of the two central matrices is,(rxy)Trx (ryv)T = � Urr OUtr I � � �I OUtr Utt � = � �Urr OO Utt �and the �nal expression for the Hessian is now obtained asry(ryv)T = � (Urr)-1 O�Utr (Urr)-1 I � � �Urr OO Utt � �(Urr)-1�(Urr)-1UrtO I �= � I O�Utr I � ��(Urr)-1 OO Utt � � I �UrtO I � (C.6)Written out in detail, the formula for the Hessian of a Legendre transformed function reads:� Vss VstVts Vtt � = � �(Urr)-1 (Urr)-1UrtUtr (Urr)-1 Utt �Utr (Urr)-1Urt � (C.7)From the sub-matrices of Equation (C.7), it is seen that:(Urr)-1 = �Vss� (Urr)-1Urt = �VstThe left-hand side of the equations above are also found as sub-matrices in Equation (C.3). Analternative formulation of Equation (C.3) is thereforeryx = � � Vss VstO �I � (C.8)C.2 The inverse Legendre transformationLet the functions u and v be as de�ned in the previous sections, and note especially thatv = u�rru rs = (rru)Trsv = �rTrru = sTThese relations, when inserted into the Legendre transform of v with respect to s, yield,v �rsv s = (u�rru r)� (�rTrruT) = u (C.9)and it is seen that u is also a Legendre transform of v. The derivatives of the untransformedfunction can hence be calculated from the derivatives of the transformed function merely byinterchanging u and v and their corresponding arguments in Equation (C.4):rxu = � �sT rtv � (C.10)A similar relation can be obtained for the Hessian of v. By comparing corresponding sub-matrices of Equation (C.7), expressions for the second order derivatives of u are easily obtainedas: � Urr UrtUtr Utt � = � �(Vss)-1 �(Vss)-1 Vst�Vts (Vss)-1 Vtt � Vts (Vss)-1 Vst �= � I OVts I � ��(Vss)-1 OO Vtt � � I VstO I � (C.11)

Page 102: Computation of phase equilibria in uid mixtures

84 Appendix C: Transforms of thermodynamic functionsC.3 Implicit functionsA technique for obtaining derivatives of a Legendre transformed function in terms of the gradi-ents of the untransformed function was discussed in Appendix C.1. It is also useful to be ableto calculate the derivatives of a function that is known only implicitly, and a special case ofsuch functional dependency is now considered.Let u be an explicit function of x where x = � r tT �T. In addition, it is assumed thatboth the gradient and the Hessian of u are known. The problem is now to �nd the gradient andthe Hessian of r when r is considered an implicit function of z = � u tT �T. In order to applythe chain rule on r, one needs to establish the two gradients rxr and rzx. The �rst of theseis trivial: rxr = � rrr rtr � = � 1 0T �The gradient rzx can be evaluated from,rxz = � rru rturrt rtt � = � ur rtu0 I �where ur is a short hand notation for @u@r . Inversion now reveals thatrzx = � u-1r �u-1rrtu0 I �(C.12)The gradient of r can now be calculated:rzr =rxrrzx = � u-1r �u-1rrtu �(C.13)Some tricks of the trade are involved in order to �nd the Hessian of r. From Equation (C.13)one can see that the gradient of (rzr)Tur is:rx ((rzr)Tur) = � 0 0T�Utr �Utt �where the short hand notation introduced on page 82 is applied. On the other hand, thedi�erentiation rule (B.6) on page 77, states that:rz ((rzr)Tur) = urrz(rzr)T + (rzr)TrzurRearrangement and the use of the chain rule results in:urrz (rzr)T = rz ((rzr)Tur)�(rzr)Trzur= �rx ((rzr)Tur)�(rzr)Trxur rzx=(rzx)T(rxz)T �rx ((rzr)Tur)�(rzr)Trxur rzx(C.14)The central product of Equation (C.14) can be given a surprisingly compact interpretation.First, since(rxz)Trx ((rzr)Tur) = � ur 0T(rtu)T I � � 0 0T�Utr �Utt � = � 0 0T�Utr �Utt �and, in addition, (rxz)T(rzr)T = � ur 0T(rtu)T I � � u-1r�(rtu)Tu-1r � = � 10 �

Page 103: Computation of phase equilibria in uid mixtures

Appendix C: Transforms of thermodynamic functions 85the actual product is reduced to(rxz)T frx ((rzr)Tur)� (rzr)Trxurg= � 0 0T�Utr �Utt �� � 10 � � Urr Urt �= � � Urr UrtUtr Utt �This result inserted into Equation (C.14) then shows thaturrz (rzr)T = �(rzx)Trx((rxu)T)rzxThe Hessian of r can thus be written� Ruu RutRtu Rtt � = � 1ur � u-1r 0T�u-1r (rtu)T I � � Urr UrtUtr Utt � � u-1r �u-1rrtu0 I � (C.15)

Page 104: Computation of phase equilibria in uid mixtures
Page 105: Computation of phase equilibria in uid mixtures

Appendix DConstrained optimizationIn this section, some theorems central to constrained optimization are summarized. This pre-sentation follows closely the notation of Luenberger [28]. The theorems are applied to centralproblems in thermodynamics and the conditions for thermodynamic equilibrium and thermody-namic stability are derived. Furthermore, the Newton-Lagrange iteration scheme is presentedin Appendix D.4, and this scheme applied on a sum of �rst-order homogeneous functions isdiscussed in detail. The main result in the section is an alternative system of equations forcomputing the Newton-step. Similar equations are given by Haug-Warberg [21] and Whiteet al. [63] who considered minimization of Gibbs energy.The linearized system of equations for a set of points ful�lling the conditions for an optimumof a sum of �rst-order homogeneous functions are shown in Appendix D.5. In thermodynamics,this set of points corresponds to the lines of a phase diagram.D.1 Constrained minimization conditionsTo specify the conditions for a point to be a local constrained minimum, the following problemis considered: minimizex f(x) subject to h1(x) = 0h2(x) = 0...hm(x) = 0 (D.1)In Equation (D.1) above, the constraints can alternatively be written in matrix notation ash(x) = 0.First-order necessary conditions, equality constraints: Let x� be a local ex-tremum point of f subject to the constraints h(x) = 0. Assume further that thegradient vectors rh1(x�), rh2(x�), : : : , rhm(x�) are linearly independent. Thenthere is a � such that rf(x�) + �Trh(x�) = 0T (D.2)The Lagrange multipliers are introduced in Equation (D.2). Another useful de�nition is theLagrangian associated with the minimization problem in Equation (D.1):l(x;�) = f(x) + �Th(x) (D.3)87

Page 106: Computation of phase equilibria in uid mixtures

88 Appendix D: Constrained optimizationBy the use of the Lagrangian, the �rst-order necessary conditions can be expressed in a compactform rxl(x;�) = 0Tr�l(x;�) = 0TSecond-order su�ciency conditions:Suppose that the �rst-order necessary conditions are ful�lled. Suppose also that thematrix L(x�) = r2f(x�) +Pmi=1 �ir2hi(x�) is positive semide�nite on the tangentspace M = fy : rh(x�)y = 0g, that is, for y 2 M there holds yTL(x�)y > 0. Thenx� is a local minimum of f subject to h(x) = 0.There also exists theorems for inequality constraints, i.e. the Kuhn-Tucker conditions1. The�rst-order necessary conditions for an inequality constrained problem are the following.Let x� be a minimum point for the problemminimizex f(x) subject to h(x) = 0g(x) 6 0(D.4) where the gradient vectorsrhi(x�) andrgj(x�) are linearly independent for all equal-ity constraints i and active constraints j. Then there are vectors � and � such thatrf(x�) + �Trh(x�) + �Trg(x�) = 0T�Tg(x�) = 0� > 0(D.5)D.2 Descent properties of the Newton directionIt is shown in [28] that the Newton direction � �xT ��T �T is a descent direction for the meritfunction m(�) = 12 jjrxl(x+ � �x;�+ � ��)jj2 + 12 jjh(x+ � �x)jj2where l is the Lagrangian in Equation (D.3). It is also straightforward to show that a meritfunction de�ned in terms of weighted inner products shares the same property. Let the meritfunction be de�ned bym(�) = 12rxl(x+ � �x;�+ � ��)W TxWxrxl(x+ � �x;�+ � ��)T+ 12h(x+ � �x)T W T�W� h(x+ � �x)= 12 � rxl(x+ � �x;�+ � ��)Th(x+ � �x) �T � W TxWx OO W T�W� � � rxl(x+ � �x;�+ � ��)Th(x+ � �x) �(D.6)whereWx andW� are arbitrary weighting matrices. Di�erentiation of the merit function de�nedin Equation (D.6) yieldsdmd� �����=0 = � (rxl)Th �T � W TxWx OO W T�W� � � L rxhTrxh O � � �x�� �(D.7) 1This notation is not unique in the literature. Conditions equivalent to Equation (D.5) is i.e. called a Karush-Kuhn-Tucker system by Guddat et al. [20].

Page 107: Computation of phase equilibria in uid mixtures

Appendix D: Constrained optimization 89where L(x) = r2f(x) +Pmi=1 �ir2hi(x). Furthermore, since the Newton step is found bysolving the Newton-Lagrange scheme� L rxhTrxh O � � �x�� � = � � (rxl)Th � ;Equation (D.7) is equivalent todmd� �����=0 = � � (rxl)Th �T � W TxWx OO W T�W� � � (rxl)Th � = �2m( 0 ) (D.8)Equation (D.8) shows that the Newton direction is always a descent direction for the merit func-tion Equation (D.6). It is also noteworthy that Equation (D.8) is valid even if L is inde�nite.D.3 Optimum of a sum of �rst-order homogeneous func-tionsThe majority of problems related to the computation of thermodynamic equilibria can be for-mulated as optimization problems, and the intention is to present a generic problem descriptionwell suited for such computations. However, since generality imposes some abstractions, theequations cannot be presented in a notation where the relevance to thermodynamics is easilyrecognized.D.3.1 First-order conditionsThe optimization problem considered readsminimizex1; ::: ;xn nXi=1 fi(xi) subject to A( nXi=1 P Ti xi � b) = 0x1 = 0 or x1 > 0x2 = 0 or x2 > 0...xn = 0 or xn > 0 (D.9)where all the functions fi are �rst-order homogeneous functions of xi. The constant matrix Aand the constant vector b are problem speci�c, but it is a prerequisite that A has a full rank.In the linear equality constraint, the P -matrices have orthonormal rows with elements equal toeither 1 or 0.The nature of the problem considered is such that an inequality constraint being activeimplies that all the elements of the corresponding variable xi are zero. These non-negativityconstraints are now reformulated. Without loss of generality, an active inequality may be writtenxi = yizi; zi > 0Furthermore, when I is the set of indices i for which zi = 0, the minimization Problem (D.9) isequivalent to minimizex1; ::: ;xn Xi 62I fi(xi) +Xi2I zifi(yi)subject to A(Xi 62I P Ti xi +Xi2I P Ti ziyi � b) = 0�zi 6 0 for i 2 I (D.10)

Page 108: Computation of phase equilibria in uid mixtures

90 Appendix D: Constrained optimizationThe optimization problem above is a Kuhn-Tucker problem, and by the �rst-order conditions,see Equation (D.5), one has the following conditions on a minimum point fx�i : i 62 Ig,rfi(x�i ) + �TAP Ti = 0T 8 i 62 Ifi(y�i ) + �TAP Ti y�i��i = 0 8 i 2 I�i > 0 8 i 2 I(D.11)The active inequality constraints must hence ful�ll�i = fi(y�i ) + �TAP Ti = y�Ti (rfi(y�i )T + P iAT�) > 0(D.12)D.3.2 First-order conditions of a system of thermodynamic functionsThe theory outlined in Appendix D.3.1 applies to �rst-order homogeneous functions, and i.e. tosee the relevance of Equation (D.12) in thermodynamics, one merely has to replace the symbolsused in the mathematical reasoning by notation used in thermodynamics.The equations governing phase equilibria of a thermodynamic system can be found by rec-ognizing a function fi as the internal energy U of the homogeneous phase i. The correspondingcoordinates of phase i, xi, will, by the symbols shown in Table 1, be [ Si Vi nTi ]T. A situa-tion corresponding to a thermodynamic, non-reacting system is characterized by A = I andP i = I for all phases i. By denoting the Lagrange multipliers �T = �[ T � �P � ��1 ��2 : : : ]T,Equation (D.11) states that all phases i present in the equilibrium assembly must ful�ll@Ui@Si = Ti = T �@Ui@Vi = �Pi = �P �@Ui@nij = �ij = ��j for all components j.Equation (D.12) applies to homogeneous functions that have coordinates equal zero at optimum.The thermodynamic analogy to such a situation is a possible phase that is not present atequilibrium. Hence, the stability criterion in thermodynamics is equivalent to Equation (D.12),and by considering the internal energy of a phase as shown above, the stability criterion can bewritten as Si ( Ti � T � )+ Vi (�Pi + P � )+ Xj nij( �ij � ��j )> 0(D.13)In the equation above, the inner product in Equation (D.12) has been replaced by summation.The phase stability criterion was originally formulated by Gibbs [16, page 106] asThis condition, which for brevity's sake we will call the condition of stability, may be writtenin the form �00 � t0�00 + p0v00 � �10m100: : :� �n0mn00 > 0By the homogeneity property of the internal energy, �00 in Gibbs' notation, it is easy to verifythat the stability criterion due to Gibbs is equivalent to Equation (D.13). Gibbs also introduceda function � de�ned as � = �� t0� + p0v � �10m1 : : : � �n0mn

Page 109: Computation of phase equilibria in uid mixtures

Appendix D: Constrained optimization 91It may be seen that � is equal to left-hand side of Equation (D.13). Inspired of Gibbs' notation,the stability test function2 � is de�ned by�(S; V; n1; n2; : : : j T �;�P �; ��1 ; ��2 ; : : : ) = S ( T � T � )+ V (�P + P � )+ Pjnj( �j � ��j ) (D.14)D.3.3 Optimization of Legendre transformed functionsSince the Legendre transform does not a�ect the gradient with respect to the untransformedvariable set, it is evident that the following holds true:If the solution of the optimization problemminimizeri;ti nXi=1 ui(ri; ti) subject to nXi=1 ri = r�nXi=1 ti = t� (D.15)is r�1 : : : r�n; t�1 : : : t�n where rriui evaluated at the point � r�i T t�i T �T is identical to s� for allindices i, then the vectors t�1 : : : t�n are a solution ofminimizeti nXi=1 vi(s�; ti) subject to nXi=1 ti = t� (D.16)In Problem (D.16), it is assumed that vi is the Legendre transform of ui with respect to ri asdescribed in Appendix C.1. Concerning the constraints in the untransformed variables t1 : : : tn,they are identical in the two optimization problems, and the �rst-order condition of a minimumof Problem (D.16) is hence trivially ful�lled. The second order conditions for a minimum ofProblem (D.15) are ful�lled by assumption, hence the Hessian of each function ui is positive(semi)de�nite. To see that the Hessian of each of the functions vi is also positive (semi)de�nite,the partitioned Hessian of ui is factored by the matrix relation shown in Equation (B.11). Whenthe index i is left out, one �nds that the two matrices� Urr UrtUtr Utt � and � Urr OO Utt �Utr (Urr)-1Urt �are congruent. Hence, by Sylvester's law of inertia, see [55] and page 23, Utt �Utr (Urr)-1Urtcannot have any negative eigenvalues. Hence, since Vtt = Utt �Utr (Urr)-1Urt, the Hessian ofvi is positive (semi)de�nite.

2The symbol \�" is preferred since capital letters are used to denote thermodynamic functions.

Page 110: Computation of phase equilibria in uid mixtures

92 Appendix D: Constrained optimizationD.3.4 Optimization of implicit functionsSimilar to the results in Appendix D.3.3, there exist relations between the optima of sums whenthe functions are de�ned implicitly. Especially, it can be veri�ed that the following holds true:If the solution of the optimization problemminimizeri; ti nXi=1 ui(ri; ti) subject to nXi=1 ri = r�nXi=1 ti = t�(D.17)is r�1 : : : r�n; t�1 : : : t�n and u� = nXi=1 ui(r�i ; t�i ), then u1(r�1; t�1) : : : un(r�n; t�n); t�1 : : : t�n is a solution ofoptimizeui; ti nXi=1 ri(ui; ti) subject to nXi=1 ui = u�nXi=1 ti = t�(D.18)The �rst-order conditions for a minimum of Problem (D.17) can be written@ui@ri + � = 0; rtiui + �T = 0T(D.19)where � and � are Lagrange multipliers. Furthermore, by the �rst-order derivatives of implicitfunctions, Equation (C.13), one has@ri@ui = �@ui@ri �-1; rtiri = ��@ui@ri �-1rtiuiand ful�lled �rst-order conditions of Problem (D.17) yield@ri@ui + � = 0; rtiri + �T = 0T(D.20)by choosing Lagrange multipliers according to � = 1� and � = 1��. Equation (D.20) is the�rst-order conditions for optimum of Problem (D.18).Hitherto, it is not indicated whether Problem (D.18) is a minimization problem or a max-imization problem. The actual type of optimum is found by inspecting the second-order con-ditions. First, since r�1 : : : r�n; t�1 : : : t�n is a solution of a minimization problem, it is known thatthe Hessian of ui is positive (semi)de�nite. Furthermore, from Equation (C.15) it is known thatthe signatures of the Hessians are related by�(Ri) = �(�(@ui@ri )-1Ui)where Ri and Ui are the Hessians of ui and ri, respectively. Thus, when @ui@ri < 0, Ri will be pos-itive (semi)de�nite and u1(r�1; t�1) : : : un(r�n; t�n); t�1 : : : t�n is a minimum point of Problem (D.18).Analogously, the solution of the �rst-order conditions is a maximum point if @ui@ri > 0.

Page 111: Computation of phase equilibria in uid mixtures

Appendix D: Constrained optimization 93D.4 The Newton-Lagrange scheme for a sum of �rst-order homogeneous functionsTo solve the �rst-order equations of Problem (D.9), all the inequality constraints are assumedto be inactive. The Lagrangian corresponding to Problem (D.9) then readsl(x1;x2; : : : ;xn;�) = nXi=1 fi(xi) + �TA( nXi=1 P Ti xi � b) (D.21)The gradient and Hessian of each function isrxifj = �ijgTi andrxigj = �ijH i respectively, andthe Newton-Lagrange scheme [28] is2666666666666664H1 O � � � O P 1ATO H2 � � � O P 2AT... ... . . . ... ...O O � � � Hn P nATAP T1 AP T2 � � � AP Tn O

37777777777777752666666666666664�x1�x2...�xn��

3777777777777775 = �2666666666666664

g1 + P 1AT�g2 + P 2AT�...gn + P nAT�A( nXi=1 P Ti xi � b)3777777777777775 (D.22)

Since fi is homogeneous in xi all the sub-matricesH i are singular, and the system of linearizedequations must be solved with at least partial pivoting. However, one can take advantage of thissingularity and transform the left-hand side of Equation (D.22) into a smaller, dense matrix.First, due to the homogeneity, gTi xi = fi andH ixi = 0. A post-multiplication of the �rst n rowsin Equation (D.22) by xTi hence implies that xTi P i�� = �xTi (gi + P i�). By the de�nitions�+ �� = � �, egi = gi + P i and efi = xTi egi, this is equivalent toxTi P iAT� = efi (D.23)Under the assumption3 efi(xi) 6= 0 8 i, fH i is de�ned as a rank-one update of the singular matrixH i: fH i =H i + efi -1 egiegTi (D.24)It is assumed that H i is of corank one, and, by the Interlocking Eigenvalue Lemma [28], theinverse of fH i exists. Furthermore, due to the singularity H ixi = 0, Equation (D.24) becomes,fH ixi = egisince egTi xi = efi by de�nition. Solving with respect to xi, one obtains the identityfH -1i egi = xi (D.25)All sub-matrices H i are now eliminated from the system (D.22). Insertion of fH i from Equa-tion (D.24) and multiplication of one of the �rst n rows with the inverse matrix fH -1i reveals�xi � efi -1xi egTi �xi �fH -1i P iAT� = �xi (D.26)3The optimization problem considered is subject to linear constraints, and the iteration scheme is not a�ectedby the initial estimate of the Lagrange multipliers. The vector can hence be chosen such that efi 6= 0.

Page 112: Computation of phase equilibria in uid mixtures

94 Appendix D: Constrained optimizationHere the factors in efi -1xi egTi �xi are the vector xi and the unknown scalar efi -1egTi �xi. Afterintroducing the de�nition �i = efi -1egTi �xi, Equation (D.26) can be written�xi = xi�i � xi +fH -1i P iAT�(D.27)To establish a system of equations for determination of �i and �� in Equation (D.27), the lastline in Equation (D.22) is written asA nXi=1 P Ti �xi = �A( nXi=1 P Ti xi � b)(D.28)Hence, by inserting �xi from Equation (D.27), Equation (D.28) is reduced to the identityA nXi=1 P TifH -1i P iAT� +A nXi=1 P Ti xi�i = AbIn addition, n equations can be written in accordance with Equation (D.23):xT1P 1AT� = ef1xT2P 2AT� = ef2...xTnP nAT� = efnTo make sure that the linear system has the same number of equations and unknowns, the lasttwo expressions are written in vector notation:2666666666666664A nXi=1 P Ti fH -1i P iAT AP T1x1 AP T2x2 � � � AP TnxnxT1P 1AT 0 0 � � � 0xT2P 2AT 0 0 � � � 0... ... ... ...xTnP nAT 0 0 � � � 0

37777777777777752666666666666664��1�2...�n3777777777777775 =

2666666666666664Abef1ef2...efn

3777777777777775(D.29)The update of the variables of the object function are shown in Equation (D.27).D.5 Pathfollowing of curves of local minimizersThe Kuhn-Tucker conditions of the optimum of a system of �rst-order homogeneous functionsare shown in Equation (D.11). A point (x1;x2; : : : ;�) satisfying both these conditions and theconstraint speci�cations of the Kuhn-Tucker problem is unique. The intention of this section isto outline the conditions for a family of points that satis�es:(i) the �rst-order Kuhn-Tucker conditions(ii) only a subset of the constraints.

Page 113: Computation of phase equilibria in uid mixtures

Appendix D: Constrained optimization 95The characteristics of the set of points considered is that m inequality constraints are active andthe set should span a curve only. Hence, by the last criterion, m+ 1 of the equality constraintsof the corresponding minimization problem cannot be ful�lled. These types of problems aredescribed by Guddat et al. [20] where also algorithms for �nding the solution set are described.In order to present a mathematical description of the requirements, the free variables ofthe problem are, for the moment, denoted y1;y2; : : : . Furthermore, let n be the number ofnonzero y-vectors in the solution set and let the reduced constraint speci�cation beB(n+mXi=1 P Ti yi � b) = 0 where B = �A (D.30)where gTi =rxifi. In the matrix product above, the matrix � merely erases m+1 of the linearconstraints in the Kuhn-Tucker problem. The �rst-order conditions aregi + P iAT� = 0 8 i = 1 : : : n+m (D.31)An active inequality constrain is most conveniently formulated by a substitution of the freevariables. By the de�nitions4 yi = �izi; zTi ei = ci (D.32)where the constants ei and ci are a vector and a scalar, respectively, Equation (D.30) can bewritten B( nXi=1 P Ti yi � b) = 0eTn+1 zn+1 � cn+1 = 0eTn+2 zn+2 � cn+2 = 0...eTn+mzn+m � cn+m = 0 (D.33)In Equation (D.33), the active inequality constraints are invoked by assigning �n+1 = �n+2 =� � � = �n+m = 0. The Equations (D.31) and (D.33) together form a nonlinear system of equationswith one more unknown than equations. This is evident since, by letting � in Equation (D.30)be equal to the identity matrix, Equations (D.33) and (D.31) will de�ne a system with nodegrees of freedom. Hence, when � has corank m + 1 and with m additional equations fromsystem (D.33), the entire system has one degree of freedom.One way to locate subsequent points solving the equations above is outlined in Appendix E.2.To apply this method, the gradients of the equations must be established in order to �nd thetangent of the curve (Euler predictor) and to locate points on the curve exactly (Newton'smethod used as corrector). It is, however, possible to rearrange the equations in the same wayas described in Appendix D.4. First, by introducing the common symbol x for the variablesy1 : : :yn; zn+1 : : :zn+m, the Newton scheme for solving Equations (D.31) and (D.33) can be4In a variable substitution y = �z an additional constraint, i.e. zTe = c is indeed required. Without thisconstraint, the variables y1; y2 : : : yn would have been replaced by z1; z2 : : : zn; �, and an extra degree of freedomwill be introduced.

Page 114: Computation of phase equilibria in uid mixtures

96 Appendix D: Constrained optimizationwritten:2666666666666666666666666666666666664

H1 O � � � O O � � � O P 1ATO H2 � � � O O � � � O P 2AT... ... . . . ... ... ... ...O O � � � Hn O � � � O P nATO O � � � O Hn+1 � � � O P n+1AT... ... ... ... . . . ... ...O O � � � O O � � � Hn+m P n+mATBP T1 BP T2 � � � BP Tn O � � � O O0T 0T � � � 0T eTn+1 � � � 0T 0T... ... ... ... . . . ... ...0T 0T � � � 0T 0T � � � eTn+m 0T

3777777777777777777777777777777777775

2666666666666666666666664

�x1�x2...�xn�xn+1...�xn+m��

3777777777777777777777775= �

2666666666666666666666666666666666664

g1 + P 1AT�g2 + P 2AT�...gn + P nAT�gn+1 + P n+1AT�...gn+m + P n+mAT�B� nXi=1P Ti xi � b�eTn+1xn+1 � cn+1...eTn+mxn+m � cn+m

3777777777777777777777777777777777775(D.34)

Furthermore, as in Appendix D.4, the substitutions�+ �� = � �; egi = gi + P i ;efi = xTi egi and fH i =H i + efi -1 egiegTienable Equation (D.34) to be partitioned into a smaller system of equations. By matrix inver-sion, �xi is obtained from Equation (D.27) as�xi = xi�i � xi +fH -1i P iAT�where �i = efi -1egTi �xi. The unknowns � and �i are obtained by solving the partitioned systemwhich reads,2666666666666666666666666664

B nXi=1 P TifH -1i P iAT BP T1x1 � � � BP Tnxn 0 � � � 0eTn+1fH -1n+1P n+1AT 0 � � � 0 eTn+1xn+1 � � � 0... ... ... ... . . . ...eTn+mfH -1n+mP n+mAT 0 � � � 0 0 � � � eTn+mxn+mxT1P 1AT 0 � � � 0 0 � � � 0xT2P 2AT 0 � � � 0 0 � � � 0... ... ... ... ...xTn+mP n+mAT 0 � � � 0 0 � � � 0

3777777777777777777777777775

26666666666666666666664

��1...�n�n+1...�n+m

37777777777777777777775=266666666666666666666666664

Bbcn+1...cn+mef1ef2...efn+m

377777777777777777777777775(D.35)

Page 115: Computation of phase equilibria in uid mixtures

Appendix D: Constrained optimization 97The general solution of Equation (D.35) consists of a particular and the homogeneous solution:� = �p + � �h�1 = �1p + � �1h�2 = �2p + � �2h...Corresponding solutions in terms of the variables in Equations (D.31) and (D.33) are obtainedfrom Equation (D.27) and the de�nition of �:�xi = xi (�ip + ��ih � 1) +fH -1i ��p + ��h�= xi(�ip � 1)+fH -1i P iAT�p+�fxi �ih +fH -1i P iAT�hg (D.36)�� = � �� �= � �� ��p + � �h�= � �� �p + � (��h) (D.37)In Equations (D.36) and (D.37) the particular solution is the part of the formulae being in-dependent of the arbitrary scalar �. Furthermore, from Equation (D.37), it is seen that it isalways possible to choose the initial Lagrange multiplier � such that the particular solution��p = ����p is equal the zero-vector. To within an arbitrary scale factor, the homogeneoussolution ��h is unique.As shown in Appendix E.2, the homogeneous solution �x1h; �x2h : : : is codirectional withthe tangent of the curve, and the Euler predictor is obtained straightforward as xi(t + �t) =xi(t) +�t �xih. It is, however, not possible to obtain a unique corrector step. In Appendix E.2a corrector step is derived by requiring that the correction is orthogonal to the tangent. In theproblem considered, this orthogonality can be written0 = n+mXi=1 (�xi; �xih)Wxi + (��; ��h)W�

Page 116: Computation of phase equilibria in uid mixtures
Page 117: Computation of phase equilibria in uid mixtures

Appendix ENumerical algorithmsE.1 Newton's methodA widely applied algorithm for numerical solution of systems of nonlinear equations is Newton'smethod. In practical optimization, the method is also widely used since the �rst-order su�cientconditions in general are a nonlinear system which must be solved iteratively. Textbook formsof Newton's method are �x = � f(x)f 0(x) and �x = �(rxy)-1y(x) for the solution of the equationsf(x) = 0 and y(x) = 0, respectively. These formulae de�nes second order iteration sequences,independent of the problem being a transcendent equation or a system of nonlinear equations.Iteration formulae of higher order convergence do also exist, perhaps the most well known isthe extended Newton formula �x = � f(x)f 0(x) � 12 f(x)2f 00(x)f 0(x)3 . However, as pointed out by Traub [62],Newton-like methods of arbitrary order can be found by inverse interpolation, even for systemsof equations, and the purpose of this section is to present iteration formulae with order ofconvergence up to four.E.1.1 Taylor expansion of inverse functionsThe derivation of the formulae are somewhat tedious, and in order to not introduce too manyindices initially, an implicitly de�ned function u is considered �rst. Partial derivatives of thefunction u(y(x)) are obtained by the chain rule. By applying the summation convention [2],derivatives to order three may be written as:@u@xi = @u@yl @yl@xi@2u@xi@xj = @2u@yk@yl @yl@xi @ym@xj + @u@yl @2yl@xi@xj@3u@xi@xj@xk = @3u@yl@ym@yn @yl@xi @ym@xj @yn@xk+ @2u@yl@ym � @2ym@xi@xj @yl@xk + @2ym@xi@xk @yl@xj + @2ym@xj@xk @yl@xi�+ @u@yl @3yl@xi@xj@xk 99

Page 118: Computation of phase equilibria in uid mixtures

100 Appendix E: Numerical algorithmsNow, since @yi@xk @xk@yj = �ij, explicit formulae for derivatives of u with respect to y can be estab-lished:@u@xi @xi@y� = @u@y�@2u@xi@xj @xi@y� @xj@y� = @2u@y�@y� + @u@yl @2yl@xi@xj @xi@y� @xj@y�@3u@xi@xj@xk @xi@y� @xj@y� @xk@y = @3u@y�@y�@y + @2u@y @ym @2ym@xi@xj @xi@y� @xj@y�+ @2u@y�@ym @2ym@xi@xk @xi@y� @xk@y + @2u@y�@ym @2ym@xj@xk @xj@y� @xk@y + @u@yl @3yl@xi@xj@xk @xi@y� @xj@y� @xk@y

In the case u = xp, some higher order terms vanish.0 = @2xp@y�@y� + @xp@yl @2yl@xi@xj @xi@y� @xj@y�0 = @3xp@y�@y�@y + @2xp@y @ym @2ym@xi@xj @xi@y� @xj@y�+ @2xp@y�@ym @2ym@xi@xk @xi@y� @xk@y + @2xp@y�@ym @2ym@xj@xk @xj@y� @xk@y +@xp@yl @3yl@xi@xj@xk @xi@y� @xj@y� @xk@y

Page 119: Computation of phase equilibria in uid mixtures

Appendix E: Numerical algorithms 101Explicit formulae for higher order derivatives with respect to y can now be written:@2xp@y�@y� = �@xp@yl @2yl@xi@xj @xi@y� @xj@y�@3xp@y�@y�@y = � @2xp@y @ym @2ym@xi@xj @xi@y� @xj@y�� @2xp@y�@ym @2ym@xi@xk @xi@y� @xk@y � @2xp@y�@ym @2ym@xj@xk @xj@y� @xk@y �@xp@yl @3yl@xi@xj@xk @xi@y� @xj@y� @xk@y = @xp@yl @2yl@xn@xo @xn@ym� @xo@y @2ym@xi@xj @xi@y� @xj@y�+@xo@y� @2ym@xi@xk @xi@y� @xk@y +@xo@y� @2ym@xj@xk @xj@y� @xk@y ��@xp@yl @3yl@xi@xj@xk @xi@y� @xj@y� @xk@y

Substitution of these expressions into a Taylor series now revealsxp(y + a) = xp(y) + @xp@y�a� + 12 @2xp@y�@y� a�a� + 16 @3xp@y�@y�@y a�a�a + � � �= xp(y) + @xp@y�a� � 12 @xp@yl @2yl@xi@xj @xi@y� @xj@y� a�a�+16 @xp@yl �3 @2yl@xn@xo @xn@ym @xo@y @2ym@xi@xj @xi@y� @xj@y�� @3yl@xi@xj@xk @xi@y� @xj@y� @xk@y � a�a�a + � � �

This expansion can be cast into a vectorial form by some trivial de�nitions. Let element i; j ofH be @yi@xj and compute @xi@yj as element i; j of H -1. Furthermore, common factors in the Taylor

Page 120: Computation of phase equilibria in uid mixtures

102 Appendix E: Numerical algorithmsseries can be replaced by the de�nitions:xp(y + a) = xp(y) + @xp@y�a�| {z }qp �12 @xp@yl @2yl@xi@xj @xi@y�a�| {z }qi @xj@y� a�| {z }qj+16 @xp@yl 8>>><>>>:3 @2yl@xn@xo @xn@ym @xo@y a | {z }qo @2ym@xi@xj @xi@y�a�| {z }qi @xj@y� a�| {z }qj� @3yl@xi@xj@xk @xi@y�a�| {z }qi @xj@y� a�| {z }qj @xk@y a | {z }qk9>>>=>>>;+ � � �= xp(y) + @xp@y�a� � 12 @xp@yl @2yl@xi@xj qiqj| {z }bl+16 @xp@yl �3 @2yl@xn@xo @xn@ym qo @2ym@xi@xj qiqj| {z }bm� @3yl@xi@xj@xk qiqjqk�+ � � �= xp(y) + @xp@y�a� � 12 @xp@yl bl+16 @xp@yl �3 @2yl@xn@xo qo @xn@ym bm| {z }rn � @3yl@xi@xj@xk qiqjqk�+ � � �= xp(y) + @xp@y�a� � 12 @xp@yl bl+16 @xp@yl 8>>><>>>:3 qo @2yl@xn@xo rn| {z }cl � @3yl@xi@xj@xk qiqjqk| {z }dl

9>>>=>>>;+ � � �= xp(y) + @xp@yl �al � 12bl + 12cl � 16dl�+ � � �The Taylor series in vector notation �nally takes the form,x(y + a) = x(y) +H -1�a� 12b+ 12c� 16d�+ � � �(E.1)

Page 121: Computation of phase equilibria in uid mixtures

Appendix E: Numerical algorithms 103where the components are: q = H -1a (E.2)bl = @2yl@xi@xj qiqj (E.3)r = H -1b (E.4)cl = @2yl@xi@xj qirj (E.5)dl = @3yl@xi@xj@xk qiqjqk (E.6)E.1.2 Newton iteration formulaeWith a Taylor expansion of the inverse function established, it is straightforward to �nd anupdate in a solution sequence. Since the inverse function exists by assumption, the vectorx solving y(x) = 0 is simply x(0). Accordingly, insertion of a = �y into Equations (E.1)and (E.2) gives the expansion around the solution point y = 0:x(0) = x(y)�H -1�y + 12b� 12c+ 16d�+ � � � (E.7)The truncation after one term is seen to be the Newton formula �x = �(rxy)-1y(x). In thescalar case, y = f(x), b = f 00(x) (f(x)=f 0(x))2 and the extended Newton formula may hence befound from Equation (E.7) by considering two terms only. With all terms taken into account,Equation (E.7) is a forth order Newton iteration formula.E.2 Pathfollowing using Euler predictor and Newton'smethod as correctorThe continuation methods described by Branin [6] and Guddat et al. [20] are based on the samenumerical scheme for computation of the trajectory. The method can, in short, be summarizedas the computation of the solution set of a system of nonlinear equations with one degree offreedom.Let a curve in IRn�1 be de�ned by F (X) = 0 (E.8)where F : IRn ! IRn�1. The parameterized curve in Equation (E.8) may alternatively bede�ned by the di�erential equation, rXF (X) _X = 0 (E.9)which states that the tangent of the curve is in the null-space of the gradient of F . A Taylorexpansion of F indicates that this tangent can be computed simultaneously with the correctorstep. First, by Taylor expansion, one hasF (X + �X) = F (X) +rXF (X) �X + � � �and iterative substitutions X X + �X where �X is the solution of0 = F (X) +rXF (X) �X (E.10)

Page 122: Computation of phase equilibria in uid mixtures

104 Appendix E: Numerical algorithmswill, provided the initial estimate is within the convergence radius, give a point on the curvede�ned by Equation (E.8). SincerXF (X) 2 IR(n�1)�n, the general solution of Equation (E.10)can be written1, �X = �Xp + � �Xh(E.11)where �Xp and �Xh are a particular and the homogeneous solutions, respectively. The homoge-neous part of Equation (E.10) is identical to Equation (E.9) and �Xh is, therefore, codirectionalto _X. Hence, the Euler predictor is X +�t �Xh and any component of �X along �Xh cannotserve as a corrector. To compute the corrector step, �X is, therefore, chosen to be orthogonalto �Xh. By this criterion, a weighted inner product2 of �X and �Xh is, see Equation (E.11),0 = (�Xh; �Xp)W + � (�Xh; �Xh)Wand the corrector step becomes:�X = �Xp � (�Xh; �Xp)W(�Xh; �Xh)W �Xh(E.12)E.3 Canonical formsIn connection with the computation of chemical equilibria of reacting systems, it may be of inter-est to transform the constraint matrix into a form which is equivalent to a linear programmingtableau in its canonical form. By the nomenclature applied in linear programming, a systemis said to be in canonical form if the columns of the basic variables form an identity matrix.The transformation to the canonical form can be done in a number of ways, here singular valuedecomposition is utilized. To outline the method, some de�nitions are required. First, let theindices of basic variables be contained in the integer array p and let P have elements accordingto (P )ij = �i;p(i). A linear transformation R putting A to the desired canonical form musthence satisfy RAP T = � IO �By the singular value decomposition, see Strang [55],AP T = udvTwhere u and v are orthogonal and d have the diagonal structured = � bO � where b = 26664 d1 0 � � � 00 d2 � � � 0... ... . . . ...0 0 � � � dn

37775 and n = rank(A)1Equation (E.10) is equivalent to the linear system [A b]x = c. When the columns of A are linearlyindependent, the solution of this equation is x = hA-1c0 i + � hA-1b�1 i = hA-10T 01 inhc0i+ � h b�1io. One possibleway to compute the homogeneous and a particular solution of the system is to LU-decompose hA0T 01 i and applyits inverse to the right-hand sides h c0i and h b�1i.2A weighted inner product, see [55], is de�ned as (x;y)W = (Wx)T(Wy).

Page 123: Computation of phase equilibria in uid mixtures

Appendix E: Numerical algorithms 105By the matrices in the singular value decomposition, the following square matrices are de�ned:V =� v OO I �D=� b OO I �U= uBy insertion, it can be veri�ed that,V D-1UTAP T = � IO �and the linear transformation providing the canonical form becomes:R = V D-1UTE.4 Automatic di�erentiationIn thermodynamic computations, the only nontrivial mathematical technique involved is di�er-entiation. The analytical formulae for the derivatives needed in the computations, i.e. chemicalpotentials etc., are somewhat complicated and tedious to derive, and in the design phase ofnumerical algorithms, a method for customized computation of derivatives is a surprisinglypowerful tool. A method for automatic di�erentiation of a scalar function in one variable isdiscussed by Rall [43, 44]. In the same papers, Rall also outlines an extension of the method tocompute higher order derivatives. However, his method is easily extended to functions of severalvariables as well, and the di�erentiation arithmetic is completely described by Equations (E.13)to (E.19) below.The basic elements for automatic di�erentiation are triplets de�ned byU = fu; ux; uxxgwhere u = u(x1; x2 : : : xn). uTx and uxx are, respectively, the gradient and the Hessian of u. Theelementary rules for binary operators acting on such triplets may be summarized asAddition U + V = fu+ v; ux + vx; uxx + vxxg (E.13)Subtraction U � V = fu� v; ux � vx; uxx � vxxg (E.14)Multiplication U � V = fuv; uxv + vxu; uxvTx + vxuTx + uxxv + vxxug (E.15)Straightforward deduction of the rule for division is, of course, also possible, but this formulawill become unnecessarily complicated. A better approach is to apply Equation (E.15) on theproduct U = (U=V ) �V to �nd the gradient and the Hessian of the quotient. The multiplicationrule gives fu; ux; uxxg = fvuv ; vxuv + (uv )xv; vx(uv )Tx + (uv )xvTx + vxxuv + (uv )xxvgBy allowing (uv )x to appear in the expression for the Hessian, the rule hence readsDivision U=V = fuv ; 1v (ux � vxuv ); 1v (uxx � vx(uv )Tx � (uv )xvTx � vxxuv )g (E.16)

Page 124: Computation of phase equilibria in uid mixtures

106 Appendix E: Numerical algorithmsWith additional rules for di�erentiating scalars and primary variables, the chain rule completesthe arithmetic of automatic derivation.Chain rule F (U) = ff(u); uxf 0(u); uxxf 0(u) + uxf 00(u)uTxg(E.17) Scalar C = fc; 0; Og(E.18) Variable Xi = fxi; ei; Og(E.19)In Equation (E.19) ei is the i'th unit vector.

Page 125: Computation of phase equilibria in uid mixtures

Appendix FDesign of a data type representingthermodynamic surfacesThe description of thermodynamic surfaces is necessary in both equilibrium and phase boundarycomputations. One way to implement a data type representing such surfaces is shortly describedin this section. Due the general nature of these surfaces, the data type will inevitably be rathercomplex and most of its functionality cannot be explained in a short summary.A computer language excellently suited for programming of complicated data types is theC++ programming language created by Stroustrup [56, 57, 58]. The presented implementationis based on the \functor idiom" due to Coplien [10].F.1 FunctionalityA class whose objects represent generalized surfaces, must have two kinds of functionality.First, as a prerequisite for inclusion of surfaces in equilibrium computations, the extensivecoordinates of the surface must coincide with the constraint speci�cation of the problem. A basicthermodynamic surface has coordinates equal to the natural coordinates of the thermodynamicmodel and the functionality of the class should allow transforms of any basic surface to ful�llthe requirements of a general constraint. The following member functions of class surface ishence required:surface surface:: legendre_transform( const string_list &coordinates ) const;surface surface:: inverse_legendre_transform( const string_list &coordinates ) const;surface surface:: permutation( const string &coordinate ) const;surface surface:: shift( const string_list &coordinates ) const;The purpose of these functions is to construct objects runtime with the desired coordinates. Itis, however, quite di�cult to represent a general set of coordinates by any existing low-level datatype. To overcome this problem, a class whose objects store characteristics of thermodynamicfunctions and corresponding coordinates is introduced. The name of the class, class tdf,resembles the acronym \ThermoDynamic Function". Shortly summarized, the main part of thefunctionality of this class is string manipulation. However, one important attribute enablingconstruction of general surfaces is the member function is_transform_of:class tdf{ // ...public:enum type { NONE, PERMUTATION, LEGENDRE_TRANSFORM };107

Page 126: Computation of phase equilibria in uid mixtures

108 Appendix F: Design of a data type representing thermodynamic surfaces// ...inline const string_list & coordinates() const;// ...inline type is_transform_of( tdf *base, string_list *trnsfrmd_crds ) const;};By this member function, one has information on the sequence of transformations on a thermo-dynamic function and a thermodynamic surface with desired coordinates can be constructed.This is illustrated in Figure F.1 where the source code of a function transforming surfaces isshown. The other kind of functionality is imposed by the di�erent algorithms and numericalmethods that manipulate generalized surfaces. In a Newton-Lagrange iteration scheme a surfacemust provide derivatives up to second order and there must exist an e�cient way to return thecomputed Newton-direction of the surface. The following member functions were found to besu�cient to perform equilibrium computation and phase boundary tracking:inline vector surface:: x ( ) const;inline vector surface:: g ( ) const;inline square_matrix surface:: H ( ) const;inline int surface:: set_dx ( const vector &dx );inline double surface:: max_step ( ) const;inline vector surface:: x ( double step_length ) const;inline vector surface:: g ( double step_length ) const;inline int surface:: update ( double step_length );The �rst of these member functions, x();, returns the extensive coordinates of the surface inthe current state. In contrast to optimization problems that are formulated explicitly in theunknowns, the variables are here returned by a function. This is a consequence of transforma-tions that may have been performed. Only a few basic surfaces are explicit functions of theextensive coordinates, and extensive coordinates must, in the general situation, be computed.The functions g() and H() return the gradient vector and the Hessian matrix, respectively.Hence, by referencing x(), g() and H(), one has enough information to compute updates ofthe variables according to the Newton-Lagrange scheme. Information from the Newton-scheme,the computed Newton-direction, is passed to the surface by set_dx. Function max_step() re-turns, in fractions of assigned Newton-step, maximum step-length which is possible to perform.Things that lay restrictions on maximum step lengths are typically violation of non-negativityof mole numbers or temperature in the underlaying thermodynamic model1. The two functionsx( double step_length ) const; and g( double step_length ) const; are analogousto those returning the coordinates and the gradient. However, returned vectors are evaluated ata point step_length, in fractions of assigned Newton-step, along the Newton direction. Thesefunctions are typically referenced by line-search algorithms. The state of a surface is changed byreferencing update ( double step_length );. If a line search is not performed, the surfaceis updated by the statement update( 1.0 );.1A more appealing strategy is to not check for feasibility of the coordinates and, in case some violation occurs,recover the computation by the exception handling mechanism of C++. This has indeed been tried, what wasexperienced can be summarized by quoting Meyers [29]: \There is much the C++ community does not knowabout writing programs using exceptions, including, for the most part, how to do it correctly. There is as yet2no agreement on a body of techniques that, when applied routinely, leads to software that behaves predictablyand reliably when exceptions are thrown."21996.

Page 127: Computation of phase equilibria in uid mixtures

Appendix F: Design of a data type representing thermodynamic surfaces 109int create_system_element( const tdf *u, permutation_matrix *P, surface *f ){ tdf base; string_list t;switch ( u->is_transform_of( &base, &t ) ){ case tdf::PERMUTATION:create_system_element( &base, P, f );*f = f->permutation( t[0] ); return 1;case tdf::LEGENDRE_TRANSFORM:create_system_element( &base, P, f );// In case of constraints in intensive coordinates,// generate a shifted surface.if ( intersection( t, f->coordinates() ).size() > 0 )*f = f->shift(t);return 1;case tdf::NONE:*P = u->coordinates()[ f->coordinates() ];return (int)*P;}}Figure F.1: Function, referenced recursively, transforming surface *f to functional form suit-able for a ash-problem characterized by tdf *u. The function create system element is ref-erenced in order to transform a basic thermodynamic surface to match the optimization problemdescribed in Equation (D.9): With permutation matrix P; tdf u; and a basic thermodynamicsurface f; the statement create system element( &u, &P, &f ); insures that f and P con-form to the optimization problem optimizeP fi(xi); A (PP Ti xi � b) = 0. The permutationmatrix is constructed by a generalized \index of" operator that may be an attribute of any listobject, i.e. for string list a("a b c"), b("c b"); the subscripting a[b]; returns �00 01 10�.

Page 128: Computation of phase equilibria in uid mixtures

110 Appendix F: Design of a data type representing thermodynamic surfaces// Forward declaration of data types...class surface{public:class representation{ // Some integral data type counting references, see [10] or [29].friend class surface; // Allow envelope class to manage memory.virtual vector x() const = 0; // Return vector of extensive coordinates.virtual vector g() const = 0; // Return corresponding derivatives.// More virtual functions... .virtual representation *clone() const; // Return pointer to alloced memory// where a clone is placed.protected:representation(); // Initialize the reference counting mechanism.};private: representation *p;surface( representation *pp ) : p(pp) { }public:vector x() const { return p->x(); }vector g() const { return p->g(); }// Reference all virtual functions of "class representation" in the same manner.const string_list &coordinates() const;// An example of mapping is "inverse Legendre transform", see Appendix C.1.// Implement it as static function and allow the transformation to// be accessed through member function.static surface inverse_legendre_transform( const surface &, const string_list & );inline surface inverse_legendre_transform( const string_list &coordinates ) const{ return inverse_legendre_transform( *this, coordinates );}// More transforms ...inline surface ( const surface & ); // Apply reference counting.inline surface & operator = ( const surface & ); // Apply reference counting.inline ~surface(); // Free memory if reference count is zero.};Figure F.2: Declaration of data type modeling a thermodynamic surface. Only a small part ofthe functionality is shown.

Page 129: Computation of phase equilibria in uid mixtures

Appendix F: Design of a data type representing thermodynamic surfaces 111F.2 ImplementationIt is far out of scope to give a full documentation of the implementation of any of the memberfunctions of class surface. Instead, the implementation of one transformation is describedshortly. The inverse Legendre transformation is chosen as working example. An abbreviatedlisting of class surface is shown in Figure F.2, page 110. One member only is present inthe class, a pointer to the nested class representation where pure virtual functions aredeclared. The virtual functions are overloaded in the derived class. To model the inverseLegendre transform, a suitable class may look likestruct inverse_legendre_transform : public surface::representation{ vector x() const { return my_x; }vector g() const { return my_g; }// Overload all virtual functions.surface v; // Untransformed surface.const permutation_matrix P; // Indices of transformed coordinates.const permutation_matrix Pn; // Indices of untransformed coordinates,// the nullspace of P.vector my_x; // Save coordinates,vector my_g; // gradientsquare_matrix my_H; // and Hessian.// More members ...inverse_legendre_transform( const surface &untransformed, const string_list &c ):v ( untransformed ),P ( v.coordinates()[c] ),Pn ( P.nullspace() ),my_x ( P.col_dim() ),my_g ( P.col_dim() ),my_H ( P.col_dim() ) { }};Static member function of class surface returning inverse Legendre-transformed surface is inessence a call of the constructor of struct inverse_legendre_transform:surface surface::inverse_legendre_transform( const surface &u,const string_list &c ){ return new ::inverse_legendre_transform( u, c );}One safe way to compute the members of struct inverse_legendre_transform is to do allcalculations at the very point where the state of the surface is altered. The only memberfunction actually changing the coordinates of the surface is update. A possible implementationof update is shown below. The actual implementation should be written in low-level C avoidingsubscripting.int inverse_legendre_transform::update( double step_length ){ if ( !v.update( step_length ) ) return 0;

Page 130: Computation of phase equilibria in uid mixtures

112 Appendix F: Design of a data type representing thermodynamic surfacesconst vector y ( v.x() ); // Coordinates of v are y = � rru tT �T,// see Equation (C.1) page 81.const vector grad_v ( v.g() ); // Gradient of v is � �rT rtu �T.for ( int i=0; i<P.row_dim(); ++i ) {my_x[ P[i] ] = - grad_v[ P[i] ]; my_g[ P[i] ] = y[ P[i] ]; }for ( int i=0; i<Pn.row_dim(); ++i ) {my_x[ Pn[i] ] = y[ Pn[i] ]; my_g[ Pn[i] ] = grad_v[ Pn[i] ]; }const square_matrix Vyy( v.H() );const square_matrix m_VssI ( - inverse( P*Vyy*P .transposed() ) );const matrix Vst ( P*Vyy*Pn.transposed() );const matrix m_VssI_Vst ( m_VssI*Vst );const matrix m_Vts_VssI_Vst ( Vst.transposed()*m_VssI_Vst );// Compute Hessian according to Equation (C.11).for ( int i=0,j; i<P.row_dim(); ++i )for ( j=i; j<P.row_dim(); ++j )my_H[ P[i] ][ P[j] ] = my_H[ P[j] ][ P[i] ] = m_VssI[ i ][ j ];for ( int i=0,j; i<P.row_dim(); ++i )for ( j=0; j<Pn.row_dim(); ++j )my_H[ P[i] ][ Pn[j] ] = my_H[ Pn[j] ][ P[i] ] = m_VssI_Vst[ i ][ j ];for ( int i=0,j; i<Pn.row_dim(); ++i )for ( j=i; j<Pn.row_dim(); ++j )my_H[ Pn[i] ][ Pn[j] ] = my_H[ Pn[j] ][ Pn[i] ]= Vyy[ Pn[i] ][ Pn[j] ] + m_Vts_VssI_Vst[ i ][ j ];return 1;}The last example of a member function is set_dx where the Newton-direction is mapped tothe coordinates of underlaying surface. The implementation is straightforward since requiredderivatives reside in the rows of my_Hess.int inverse_legendre_transform::set_dx( const vector &dx ){ // Map Newton direction. �y =rxy�x, rxy is shown in Equation (C.2).vector dy( dx );for ( int i=0; i<P.row_dim(); ++i )dy[P[i]] = inner_product( my_H.row( P[i] ), dx );return v.set_dx( dy );}

Page 131: Computation of phase equilibria in uid mixtures
Page 132: Computation of phase equilibria in uid mixtures
Page 133: Computation of phase equilibria in uid mixtures

IndexAcentric factor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73Automatic di�erentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105Chain rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76Corank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93Critical point, conditions of . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53Cubic equation of state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73Davidenko path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Di�erential operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75Euler's theorem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5, 78Extended Newton formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99Formula matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Gibbs-Duhem equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80Gibbs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5, 14, 80, 90, xiiGradient operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75Hessian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77, 82Homogeneous functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78Ideal gas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72Implicit functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84Kuhn-Tucker conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88L'Hopital's rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73Lagrange function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87Lagrange multipliers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87Legendre transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Massieu function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7, 84Merit function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22, 88Newton's method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99Newton-Lagrange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89, 93Phase stability test function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91Product rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77Sherman-Morrison formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77Signature of a symmetric matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Sylvester's law of inertia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Taylor's Theorem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77Weighted inner product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104Woodbury formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78115

Page 134: Computation of phase equilibria in uid mixtures