Comsol Process Modelling and Simulation With Finite Element Methods1

386

Click here to load reader

Transcript of Comsol Process Modelling and Simulation With Finite Element Methods1

  • Process Modelling andSimulation with

    Finite Element MethodsWilliam B. J. Zimmerman

    World Scientific

  • Process Modelling andSimulation with

    Finite Element Methods

  • SERIES ON STABILITY, VIBRATION AND CONTROL OF SYSTEMS

    Founder and Editor:Co-Editors:

    Ardeshir GuranM. Cloud & W. B. Zimmerman

    About the SeriesRapid developments in system dynamics and control, areas related to many othertopics in applied mathematics, call for comprehensive presentations of currenttopics. This series contains textbooks, monographs, treatises, conference proceed-ings and a collection of thematically organized research or pedagogical articlesaddressing dynamical systems and control.

    The material is ideal for a general scientific and engineering readership, and isalso mathematically precise enough to be a useful reference for research specialistsin mechanics and contrOl, nonlinear dynamics, and in applied mathematics andphysics.

    Selected Volumes in Series AVol. 3 Vibration Analysis of Plates by the Superposition Method

    Author: Daniel J. GormanVol. 4 Asymptotic Methods in Buckling Theory of Elastic Shells

    Authors: P. E. Tovstik and A. L. SmirinovVol. 5 Generalized Poinl Models in Structural Mechanics

    Author: I. V. AndranovVol. 6 Mathematical Problems of Control Theory: An Introduction

    Author: G. A. LeonovVol. 7 Analytical and NlIIT1erical Methods for Wave Propagation in

    Fluid MadiaAuthor: K. Murawski

    Vol. 8 Wave Processes in Solids with MicrostructureAuthor: V. I. Erofeyev

    Vol. 9 Amplification of Nonlinear Strain Waves in SolidsAuthor: A. V. Porubov

    Vol. 10 Spatial Control of Vibration: Theory and ExperimentsAuthors: S. 0. Raza Moheimani, D. Halim, and A. J. Fleming

    Vol. 11 Selected Topics in Vibrational MechanicsEditor: I. Blekhman

    Vol. 12 The Calculus of Variations and Functional Analysis; With Optimal Controland Applications in MechanicsAuthors: L. P. Lebedev and M. J. Cloud

    Vol. 13 Multiparameter Slability Theory with Mechanical ApplicationsAuthors: A. P. Seyranian and A. A. Mailybaev

    Vol. 14 Stability at Stationary Sets in Control Systems with DiscontinuousNonlinearitiesAuthors: V. A. Yakubovich, G. A. Loonov and A. Kh. Gelig

  • SERIES ON STABILITY, VIBRATION AND CONmOL Of SYSTEMS

    series A

    Foundef & Editor: Ardeshir Guran

    Volume 15

    M. Cloud & W. B. Zimmerman

    Process Modelling andSimulation with

    Finite Element Methods

    William B. J. ZimmermanUniversity of Sheffield. UK

    World ScientificNEW JERSEY' LONDON SINGAPORE' BEIJING' SHANGHAI HONG I:OHG TAIPEI' CttENNAI

  • f'ubli5hed byWorld Scientific Publishing Co. Pte. LId.5 Toh Tuck Lillk, Singapore 596224USA office: 21 Warren Street, Suite 401-402, Hackensack, NJ 07601UK office; 51 Shelton Street, Covent Garden, wndOfl WC2H 9HE

    British Library Catliloguing-in-Publication DataA. catalogue record for this book is available fTOrn the British Library.

    I'IWCESS :\10DELUNG ANn SIMULATION wun FINn'!': ELEMENT METHODSCopyright e 2004 by World Scientific Publishing Co. l>te. Ud.All rights reserved. This book. or[XlfiS Ihereof, may nOI be reproduced in any fomr ar hy any means,elulrQflic or meclwnicul, ilJcI"din~ l}horQ{'opyin~, recordin/: or an)' ;'1(OrmaliOlI5Iomge and relrie"al.s)'.slem nOw knOK'n Or /(} be illvenled, wilham wrillen pl'Tmi5sionfrol/llhe Publisher.

    For pholocopying of material in this volume, please pay a copying fee througb the CopyrightClearance Center, 11K: .. 222 RO$Cwood Drive, Danvers,l\lA Ol923, USA.ln Ihis case permission Inphotocopy is not required from lhe publisher.

    ISBN 981-238-793-5

    Printed ill Singapole by WOI1d ScillntiflC Printers (S) Pte tid

  • ABOUT THE AUTHOR

    Dr William D.J. Zimmerman is a Reader in Chemical and Process Engineering.His research inlcresls arc in nuid dynamics and reaction engineering. He haspreviously created modules entitled Chemical Engineering Problem Solving withMathematica, Modclling and Simulation in Chemical Processes, NumericalAnalysis in Chemical Engineering, and FORTRAN progranuning. He has beenmodelling with finite elemcnl methods sincc 1986. He has aUlhored ovcr sixtyscientific and scholarly works. He is a gradualc of Princeton and StanfordUniversities in Chemical Engineering. past Direclor of the M Sc inEnvironmental and Encrgy Engineering, originator of the M Sc in Process AuidDynamics, and a winner in US and UK national competitions of four presligiousfellowships:

    2000-5 EPSRC Advanced Research Fellow1994-99 Royal Academy of Engineering, Zencea Young Academic Fellow.1991-93 NATO postdocloral fellow in sciencc and engineering.1988-91 National Scicnce Foundalion Research Fellow

  • FOREWORD

    I would especially like to thank the Engineering and Physical Sciences ResearchCouncil of the United Kingdom for the award of an Advanccd ResearchFellowship on the topic of "models of helical mixing and reaction; a ncwapproach to chemical reaction engineering." Without the flexibility of thefellowship, [ doubt I would have felt adventuresome enough 10 afford Ihe time 10run so far - developing an intensive training module and writing a textbook on atopic thai is relatively new to me and was not envisaged whcn I wrote theoriginal research stralegy for Ihe fellowship in 1998. It has lurned out to beintegral to my plans for turbulence modeling, although this is not reflected inthe book.

    Johan Sundqvist and Ed Fonles of COMSOL have been most supponive ofmy two projects, lending considerable resources to helping me (0 iron outdifficulties in modeling, contributing to the intensive modules, and providingcritiques of the draft chapters. I would have thought the crew at COMSOLwould have tired with the endless c-mails from my research group. With mostpackages I use, r have no intention of being "cutting edge," so the FAQs on theweb site usually already have my queries - asked and answered. It is both noveland refreshing to have identified (and sometimes solved or worked around) newbugs or puzzles. To Ed and Johan, a wholeheaned thanks for welcoming me tothe FEMLAB developers community.

    Many thanks 10 the team of collaborators and chaptcr co-authors who haveencouraged Ihis effon. Huddhi, Alex, Kiran, Jordan, Peter, Georgc and Juliahave always had a kind word

  • CONTENTS

    About the Author

    I

  • , Process Modelling Utld Simulation wirh Finite Elfme.rt MelhQ(/s

    2.1 A Boundary Conditions2.1.5 Basic Elements

    2.2 SummaryReferences

    8589

    105105

    3 Multiphysics 107w. 8. J. Zimmenllan3.1 Introduction 1073.2 Buoyant ConveClion. 1083.3 Unsteady Response of a Nonlinear Tubular Reactor 1233.4 Heterogeneous Reaction in a Porous Catalyst Pellet 1293.5 Discussion 135References 136

    4 Extended j\.lultiphysics IJ7\V. /1. 1. Zimmerman, I'. O. Mclledlov-Petrossyan alldG. A. Khomenko4.1 Introduction 1374.2 Heterogeneous Reaction in a Fixed Bed with Premixed Feed 1404.3 Primacy of the Buffer Tank 1524.4 Linking the 2-D Buffer Tank to the l-D Heterogeneous Reactor 1624.5 Biorcactor Kinetics 1674.6 Discussion 170References 171

    5 Simulation and Nonlinear Dynamics 173W. B. 1. Zimmerman5,1 Introduction 1735.2 Rayleigh-Benard Convection 178

    5.2.1 Heating from Above 1805.2.2 Heating from Below 1845.2.3 Agreemcm wilh Thin Layer Theory 190

    5.3 Viscous Fingering Instabilities 1925.3.l Strcamfunction-Vorticity Model with Periodic BCs 202

    5.4 Summary 210References 212

    6 Geometric ContinuationW. B. J. Zimmennan and A. F. Routh6.1 Introduction6.2 Stationary Gcometric Continuation: Pressure Drop in a

    Channel with an Orifice Plate

    21S

    215

    217

  • Comems xi

    6.3 Transient Geometric Continuation: Film Drying 2276.4 Summary 2416.5 End Note: Solver Parameters for Problems with Pointwise

    Weak Terms 242References 243

    7 Coupling Variables Revisited: Inverse Problems, LincIntegrals, Integral Equations, and Integro-DifferentialEquationsW. 8. J. Zimmerman7.1 Introduction7.2 SummaryRcferences

    245

    245290290

    8 Modeling of Multi-Phase Flow Using the Level Sct Method 293K. 8. Deshplwde and IV. 8. J. Zimmerman8.1 Introduction 2938.2 Governing Equations of the Levcl Set Method 2958.3 Curvature Analysis!: Methodology 2978,4 Results and Discussion 297

    8,4.1 Coalescence of Two AxisymmelTic Drops 2988.4.2 Coalescence of Acoustically Suspended Drops 3048.4.3 Coalcsccnce Between Two Drops Approaching Each

    Other 3078.4,4 Multi-Body Coalescencc 309

    8.5 Summary 310Acknowledgements 310References 31 U

    9 Electrokinetic Flow 313W. B. J. Zimmerman and J. M. Macinnes9.1 lnuoduction9.2 Weak Boundary Constraints: Revisiting ECf9.3 Electrokinetic Row

    9.3.\ Background9.3.2 Problem Sct Up9.3.3 FEMLAB Implcmentation9.3.4 Links 10 Physical Boundarics

    9,4 SummaryAcknowledgementsReferences

    313314319319320321327349349349

  • '"Proceu Modelling and Simulation with "'inile ElertU!nf Me/hods

    351Appendix: A MATLABIFEMLAB Primer ror Vector CalculusW. B. J. Zimmerman and 1. M. Rees

    A.I Review of Vectors 351A.l.1 Representation of Vectors 351A.l.2 Scalar Products, Matrix Multiplication, Unit Vectors,

    and Vector Products 352A.2 Arrays: Simple ArTays. Cell Arrays, and Structures 356A.3 Scalar and Vector Fields: MATLAB Function

    Representations 362A.4 Differentiation in Multivariablc Calculus 365

    AA.I The Gradient of a Scalar Field 365AA.2 Derivatives of Vector Fields 369

    A.S End NOle: Plalform Dependence of Meshes 374

    Index 377

  • INTRODUCTION TO FEMLAB

    W.IU ZIMMERMANDepartment ofChemical and Process Engineering. University of Sheffield,

    Newca.ule Slreel, Sheffield S I lJD United Kingdom

    E-mail: [email protected]

    FEMLAR is a relatively recent develQpment in the MATLAB sphere. l'erhaps a goodfraction of the readers of lhis book were alltacled by the title and Ihe dust jacketdescription, so they might have lillie exposure 10 FEMLAB previously. To them, r wouldheartily recommend auending a FEMUR seminar on their recurring academicroadshows. The e"'lll:riencc of seeing FEMLAB in aclioll is more illustrative lhan theprinted word and screen captures shown here. This Introduction provides an overview ofwhy I wrote the book and developed an intensive training module for FEMLARmodeling of chemical engineering applications _ the unique features of FEMLAB IhalIhe reader will want 10 assess for her own modeling objectives. The FEMLAB User'sGuide (available for download from t~ C0.\1S0L web site) does a beUer job offamiliari7.ing the reader with "What is FEMLABr' than the brief introduction in thischaptcI to lhe FEMLAB graphical user interface (GUI). The poilU of tl!c introduction toR.JMLAB here is todeseribc how completely deternlinoo mcxJcls are set up in FEMLAB.after which Ihe lTIethodology can be used in SUbsequent chaptcrs without ambiguity.Nevertheless. I hope that this chapter whets your appetite for the cornucopia of mcxJelingtools. along with an intellectual framework for using FEMLAB for modeling, that isdescribed in this book.

    0.1 Overview of the Book

    Chapters 1-4 were laken as the text for the firSI intensive module "ChemicalEngineering Modelling with FEMLAB." These chaplers represent a personalodyssey with FEMLAB. It was not originally my intention to write a book aboutFEMLAB. For a long term project that I am still undertaking, I need a POEengine that is readily customi7..ablc to additional terms and heterogeneousdomains. Once 1 decided that FEMLAB could fill the bill. I needed to becomean expert on it. One nefarious way of doing that is to declare a course on it, ropegraduate students and other interested external parties into anending. and thenstudy like mad to produce a coherent set of lectures and computer laboratories. Ialready had several templates for this, having taught undergraduate andpostgraduate modules on numerical analysis, modeling, and simulation. So Iadapted the storyline of those modules with FEMLAB models. Chapter One isthe product of this adaptation. Chapter Two is an obvious outgrowth of my prioruse of the POE toolbox of MATLAB and a necessary explanation of finiteelement methods. Chapters 3-7 were far more deliberate attempts to exploillhe

  • 2 Process Modelling and Sim"lm;Qn with Finile Element MellrQds

    powerful features of FEMLAB by systematically exploring models thai illuSiratcthe feature of the theme of each chapler. I searched through my own repertoireof POE modeling and sought out contributions from colleagues Ihal wouldillustrate the features. Chapters 8 and 9 are of a different type. These chaplerswould legitimately fit into the FEMLAB Model Library as case studies ofmodeling with FEMLAB, rather than organized along a particular programmingtheme. Nonetheless, the case slUdies highlight non-standard aspects ofFEMLAB/MATLAB modeling, analysis, and postprocessing that are strikinglyoriginal.

    Target audience

    The book is aimed at graduate Chemical Engineers who usc modelling tools andas a general introduction to FEMLAB for scientists and engineers.

    ,

    Gec>.... t ..y only+ Physics .ades+ PDE ltllCl"s+ Wk _usy...."t..y~_~~,~.:. c..rtesian coordinatesEl'

    Figure 0.1 lhe pre-built application modes are arranged in a tree struclure on the Model Navigalor.Here is thc Incompressible Navicr-Stokes mode under Ihe Chemical Engineering Module. TheModel Navigator specifies Ihat this mode is 2-D, lias lhree dependenl variables, and uses a mixedlype of element Lagrange p2 for the velocilies u and v, Lagrange pI for lite pressure. Using mixedorder discrc1ir.alion schernc.~ is quil" cOlrunon in finite element methods for numerical 51abilily oflhc Navicr-Slokes 501\"cl".5. The SIMPLE scheme (I] pioneered Ihe approach. The Model Navigatorallows the user to specify pre-built applicalion modes or to customire a generic PDE mode(coefficient, general. weak) 10 build up their own modcL

  • Attitude

    ImroduClion 10 FEM1.AB 3

    The attitude of this book is to demonsttate particular features of FEMLAB thatmake computational modelling easy to implement, and then emphasize thosefeatures that are advantages to modelling with FEMLAB. This will be illustratedwith reference to Chemical Engineering Modelling. which has a special hislOryand well known applications. The features, however, are generally applicable inthe sciences and engineering.

    Bias

    The book is slanted toward applications in fluid dynamics, transport phenomena,and heterogeneous reaction, which reflect some of the research interests of theauthor that routinely involve mathematical modelling by POEs and solution bynumerical methods.

    Modeling versus simulation

    This book is aboul modelling and programming. The first four chapters, Ihe coreof the taught module, focus completely on modeling. The remaining chaptersarc slanted towards the usc of FEMLAB for simulation. The distinction is thatsimulation has some stochastic and evolutionary clements. Simulations mayhave a PDE compute engine as an integral component, bUI generally involvemuch more "user defined programming." This book organizes case studies ofmodeling along the lines of a cookbook - here are some models that areimportant in chemical engineering applications that arc computable inMATLABfFEMLAB. What is lacking from this presentation style, however, arethe philosophical and methodological aspects of modeling. This book is "HowTo", but not sufficiently "Why" and "How good?" arc the models. There arctwo major classes of modeling activity - (I) rigorous physicochemical modeling,which takcs the best understanding of physics and attempt to compute bynumerical mcthods the exact value up to the limits of finite precisionrepresentation of numbers; (2) approximate modeling, which intends toapproximate the true, rigorous dynamics with simpler relationships in order toestimate sizes of efft:cts and features of the outcome. rather than exact, detailedaccuracy. In this book, no attempt is made 10 systematically treat how topropose the equations and boundary conditions of modeling - decisions aboutmodeling objectives and acceptable approximations are presumed to havealready becn taken rationally. Yet, in most modeling conundrums and troubleshooting, whether or not the model itself is sensible is a key question, and whatlevel of approximation and inaccuracy are acceptable, are part and parcel of themodeling activity. Numerics and sciemific/engineering judgement about whatshould be modelled and how should not be separated.

  • 4 Process Modelling and Simulation with Fillite Elem"m Methods

    _ Cheaioal_En'cY_ e

  • fntrodllc/;on 10 PEMLAH 5

    Figure 0.3 FEMLAlJ's poslproooising screen, Hm: lhe solution for the last cxccuted run of theturbulent sUltic mixer model is shown. mMLAB's GUI provides pull down mcnus and toolbars 10initiate all building bloch of model construction .. specifying analyzed geomelries, meshing,speo::ifying POE equations and boundary conditions, analyling and POSI processing the solutionsfound, Note that lhe staluS bar al the bollom shows the posilioo of the cursor on the Yisuali7..ationwindow. The informalion window just above it echoes messages to lhe scTt:cn from theFEMLAR/MATI.AB commands executed in FEMLAB's MATLAR worlcspace, The "Loading datafrom static_miller,mat" message was the responsc to our requcst 10 lo.ad the model library entry forthe turbulenl slatic mixer,

    As we will learn in Chapters Four and Seven, extended multiphysics is verysimilar to the linkages provided by process simulation tools common forintegrated flowsheets of process plant such as HYSYS and Aspen, or which canbe developed in MATLAB's Simlliink environment. FEMLAB fully couples thisfunctionality to a POE engine that rivals CFD packages such as FLUENT andCFX or other commercial POE engines such as ANSYS, but with competitiveadvantages listed above.

    Modelling strategies in FEMLAB

    This book is about how I think about modelling and simulation. Perhaps mythoughts will serve as a guide to help you with the modelling problem that drewyou to FEMLAB, After posing myself the modelling problems in this book, Icame up with a short list of guidelines for how to approach modelling withFEMLAB:

  • 6 Process Modelling andSimuJUI;on wifh Fi"i/(' Elemt'nJ Mnhods

    4Ui .af ~ G '- OPS 0.1 G.15 nl'" "

    Figure O.41lle Options Menu pennits definition of many useful feature: constants, i!rids for drnwingand visuali1.J.lion, and c~pressions USl-U in entering the model equations arc the lHOSl common uses,

    I. Don't fe-invent the wheel. Read the Model Library and User's GuidcIWebpages.

    2. Formulatc a mathematical model. Compare with pre-buill application modes.3. Can it all be done in {he FEMLAB GUl. or is the PDE engine only a

    subromine?

    FEMLAB as an integrated modelling environment

    FEMLAB can be viewed two ways-

    1. As an interactive, integrated GUI for setting up, solving, and post-processinga mathematical modcl- a PACKAGE.

    2. As a set of MATLAB subroutines for setting up, solving, and post-processinga mathematical model - a PROGRAMMING LANGUAGE.

    This book intends to show how to implement models built both ways In anefficient way. The FEMLAB GUI is so straightforward in setting up problemsand trying "what iC' scenarios that it must be the first port of call in "having ago." The great utility of a PACKAGE is that the barriers to entry arc small. sothe payoff is wonh the investment of learning aU the features of the tool.

  • /mroduCliufl 10 FEMUlfJ

    _.. , of.1IIItJ ".k,

    7

    Figure 0.5 J

  • Process Mode/lin!? IJnd Simulation with Finite EI/'mllf Methods

    - The Multiphysics Menu allows switching between "active" modes for thespecifications menus and permits additions and deletions of "applicationmodes"

    The aUI makes the siages of computational mooelling accessible in a muchshorter lime than traditional methods. Furthermore, the level of complexity inmodelling is greater than any other PACKAGE. This has its adV3n1agcs, as wellas its own drawbacks.

    FEMLAB as a programming language

    I have learned a seemingly ceaseless stream of programming languages -BASIC, Assembler (a5m for 8088 & Cray Assembly Language), FORTRAN.PASCAL, LISP, APL, C. Mathematica, CH, MATLAB.

    Programming is hard. The languages are full of commands and syntax withintricate details thaI need to be mastered before complicated problems can betackled.

    t-igure 0.6 Draw Mode is sclccloo from the Draw Menu

  • lrllrodl
  • lO Proass Modtd/ing and SiJ1llllaliQfl wilh Finir~ llW~nI M~llwds

    ,

    ,

    "

    ,

    ,

    Figore 0.8 Poinl mode shows alllhe poinlll (vertices and spccirlCally identified poinl$) distinguishedin the geometry model by circles. The red circle is scleCloo here.

    The book provides a wealth of examples of user defined programming" withMATLAB m-file scripts aod m-file functions calling FEMLAB subprograms. Inevery case. however, I adapted models developed in the FEMLAR QUI and readout as model m-files. I have yella write a MATLAB program around FEMLABcommands/functions 'from scratch." TIle J-"EMLAB Reference Manual providesa complete description of all the commands. so I have tried to gel functionalityout of the MATLAB programming thai is IlOI achievable lhrough the Gut alone.Perha?S this is a good jul1ClUrc to point OUI lhal each FEMLAB GUI session hasits 0.....'" MATLAH workspace, ~parale from the one that launched it. So it isperfectly legitimate to write your own MATLAB m-fiIe script and read it into theFEMLAB GUI. The MATLAB workspace will execute all the MATLABcommands, even those thai ace nOI possible 10 do through the CUI alone, and theGUI responds by showing the intermedime steps - drawing the geometry,meshing, solving, and postprocessing. If yOll are writing your own user-definedm-fiIe script for FEMLABfMATLAB, playing it back in the GUI shows you howfar it gets before the program bugs (well, maybe you don't put them in yourcodes. but mine arc usually infested to start) crash it. In this respect, MATLARis a '"macro" language for FEMLAR.

  • ,Introduction IQ FE::MLAB II

    figure 0.9 Point seltiogs dialogue box, Hcre point 13 which is highlighted corresponds hi the redcircled venex in figure 0.8. The k-t model has an cxtr

  • 12 Process Modelling and Simulation with Finite Elemenr Methods

    menus and dialogue boxes with their content, limiting the number of models thatcan be effectively discussed.

    0.2.1 k-e model of a turbulent slatic mixer

    Figure 0.1 shows the Model Navigator, which pennils selection among pre-determined application modes, seuing up user-specified "multiphysics"combinations of application modes, access to the models listed here by the user,and access to the Model Library, which houses many manycars of solved andexplored models contributed by the FEMLAB user community and by theCOMSOL development team. In Ihis subsection, we will walk through Ihe"turbulent Slatic mixer," which is modelled as a complicated 2-D geometry withthe popular k-E model of turbulence 12]. This model can be found by selectingthe Model Library tab in Figure 0.1, which brings up the Model Library dialoguepage, whose menu tree is traversed in Figure 0.2. We arrive at the turbulentstatic mixer model with illustration and short blurb description. Selecting theOK button brings up the FEMLAB GUI with the geometry, model equations andboundary conditions completely specified. Figure 0.3 shows the postprocessingscreen thallhe model was stored wilh in the file "static_mixer.mat." MAT filesare Ihe binary formal for efficient disk storage of MATLAB variables. Thosecreated by FEMLAB have the complcte state of the FEMLAB environmentSaved. The postprocessing screen shows a color density plot of surface velocityof the last solution execUlcd. Let's find out what situation that was, in terms ofmodel equations and parameters.

    The model is specified in a series of dialogue boxes. Traversing Ihc pulldown menus from left 10 right will show Ihe pertinent specifications. Now pulldown Ihe Options menu, with the Add/Edit Constants choice highlighled asshown. The Options menu allows specification of a local database of constants.coupling variables, expressions, and differentiation rules, as well as specifyingthe display scalcs. Here, we only need to view the constants. Figure 0.5 showsthe Add/Edit Constants dialogue box. We can see thaI rhof::1 and nuf::l0'~ arespecified. Note Ihat Ihese arc pure numbers, i.e. no units are specified. It is upto Ihe user to employ a consistenl SCI of units for his models, or 10 specify themodel in dimensionless form with dimensionless control parameters. This is notnecessarily a trivial task.

    The next pull down menu over is the Draw menu. Here we will only switchto Draw mode. which then takes over the display. Figure 0.7 shows the greycomposite geomctry cal that was constructed when the model was originallycreated. Note that the Draw loolbar has replaced the postprocessing toolbar onthe left. We could use these tools to enter new geometric primitives. cal is asimply connected single domain, but we are not limited to either a single domainor to simply connected domains. FEMLAB accepts these graphic primitives,along with Boolean set theory operators (union and intersection) to construct

  • /mroduc/iol1/o FEMLAB 13

    analyzed geometries. Although the geometry specification can be donegraphically in Draw mode, it can also be done through MATLAB functions, apower that is exploited in Chapter six on geometrical continuation.

    Since we do not need to alter the geometry, we can move on to Point mode,shown in Figure 0.8. Here all the vertices required in specifying the analyzedgeometry are shown as circles. You can add additional poims within Pointmode that you might need either for specifying Ihe FEM model or forpostprocessing. The FEM permits specification of a system of equations in weakform, which for a POE system is equivalent to a conservation law in integralfonn. Weak terms that have no POE equivalent may be added. like pointsources and conslr3ints. It may only be thaI postprocessing information i.~required at a particular point, so entering the poim in Point mode will permitselection of a mesh to find the required solution more accurately.

    Figure 0.9 shows the Point Settings dialogue box. The k- model usespointwise contributions to the viscosity coefficient in weak (amI. These are allset at the vertices. Shown in Figure 0.9 is the contribution on vertex 13 (redcirele in Draw mode). The upper left comer shows the specific expression"hard-wired" into the k-e turbulence application mode for point viscositycontributions to the weak form. Here there are two coefficients that can beentered, TIp and ~ and they have been preset to typical model values to the k-emodel.

    Figure 0.10 moves us along to the Boundary mode, selected from theBoundary pull down menu as shown. All boundary segments are shown in thedisplay, as well as the boundary sense. The boundary sense is the direction ofincreasing arc length of that particular boundary segment. FEMLAB does nottry to coordinate boundary sense in adjacent boundary segments, as is dear fromseveral reversals seen in the display here. If the user wants to specify a boundarycondition that varies along a boundary, it can he done either with theindependent variables defined when the model was created by the ModelNavig:'ltOf, say x and y for a Iypical 2-D geometry. or wiTh the arc length sdefined locally along the boundary, with positive sense matching the arrowshown here.

    Figure 0.11 shows the Boundary Settings dialogue box. This applicationmode permits setting conditions on the mean field andlor on the turbulencequantities k (turbulellt kinetic energy) or E (dissiplation rate). Since boundary 1is an inflow boundary (or outflow, with opposite signs), the u,v,k, and e lermsare all specified. but not independently. Again, the upper left comer shows theequation being satisfied on boundary 1.

    Figure 0.12 shows us how to select Subdomain mode. Here there is exactlyone subdomain (highlighted in the display). Subdomain mode is where the POEsystem is usually specified. For simple POEs, it is the equation(s) that isspecified in subdomain mode. In pre-built application modes, however, Ihe form

  • 14 l'rv;;ess Modelling (lnd 511111'/1
  • IlI/roductiQn to FEMl.AB"

    you are llot already a FEMLAB user. I would recommend requesting ademonstration license for both FEMLAB and MATLAB. Mathworks [31 andCOMSOL 141 will provide one month trial licenses for bOlh products free ofcharge, with the software downloadable or available from CD-ROM shipped toyou by request. The Users' Guide for FEMLAB is very good, and you mightwant to read it after this Introduction and before Chapter One. I read all thedocumentation that comes with FEMLAB cover to cover before designing anddelivering my first intensive module on chemical engineering modeling withFEMLAB 15j and highly recommend it. Nevertheless, I felt there was somethingmissing in the FEMLAB references, even though the Model Library andChemical Engineering Module references have a wealth of fascinating casestudies. I think it is the perspective of an expert user that is missing, but forgivemy hubris in thinking it is my perspective!

    By now, you must be thinking that this book is a thinly veiled sales pitch forFEMLAB/MATLAB. I would be dishonest if I did not make my preference formodeling with FEMLAB/MATLi\B clear at the outset of this book. There aremany packages for modeling available on the market, but FEMLAB is the first Ihave seen for general purpose modeling that is equation based in gener3ting thePDE engine. Equations are the language of mathematical modeling andmalhematical physics, and FEMLAB aims (0 speak the language of its targetuser community. So this book represents my personal odyssey in learning howto adapt FEMLAB to modeling of chemical engineering processes, especiallybut not exclusively PDE based. In the next section, I give

  • 16 Procns Model/ing and SimuJatioll with Finite Element Me/hods

    We can lay those at the user's door morally, but since FEMLAB is not "idiot-proof', we arc frec to specify "badly conditioned or inconsistent"' models.(Politely, wrong.) FEMLAB may never generate an error message al all. Withjust about every novice user who has sought my advice. r have shown themwhere they have specified an inconsistent boundary condition like 0= I inGeneral PDE mode. Yct, in many cases, FEMLAB generates output that is notsuperficially wrong, but certainly not satisfactory in the case of modeling,conceptual. or syntactical errors. At this point, the "tough love" approach is allIhat can be advised - there is no substitute for experience. This bookencapsulates many of my experiences. 'haven't tried to sugar-coat my chaptersso that all models are magically perfect. Think of this as a cookbook that showsboth good recipes and bad ones, but each labeled and the latter coming with ahealth warning. For instance. in Chapter Seven, I tried four attempts at modelingthe population balance equations before the last came good. $0 you will learnfrom my mistakes that lawn up to as well as from my triumphs. For better orworse, every modeling attempt 1 made during the six months of writing this bookhas been included. I will pat myself on the back for persistence. because in theend Ihey all worked. but at many points I had my doubts and frustration!>. 1 ampleased not to have cherry picked the models. Of course I have not shown everysingle computation nor "what iF' line that ( pursued in each modeL

    0.3 Chapter Synopsis

    Chapter One treats the basics of numerical analysis with FEMLAB. No doubtmany of the example models are artificial in that if you were handed themodeling problems in Chapter One, FEMLAB would not be the obvious choiceof computational platform. The topics of rool finding, numerical integration bymarching, numerical integration of ordinary diffcremia! equations. ami linearsystem analysis arc universal to numerical analysis. They form the basis of myprevious lecture courses in FORTRAN programming and chemical engineeringproblem solving with Mathematica. For pedagological purposes, Chapter Oneprovides a finn basis for understanding what FEMLAB does. The commonapplications in chemical engineering that arc treated as examples, flashdistillation, tubular reactor design, diffusive-reactive systems, and healconduction in solids. arc understandable to the non-chemical engineer as well.Perhaps the single most important modeling feature introduced here, however, isthe ll

  • Imrodm;I;Q" 10 Fl;.7.1LAB 17

    Figure O.tO Boundary mode clarifies the boundary identifications and permits boundary data entryfor the FEM model.

    Chapter Two might be thought the normal point of departure for a textbook onfinite element methods (FEM). ln my opinion, FEMLAB is not so much a toolabout FEM, bur a modeling tool rhat happens lO use FEM in jt$ automatcdmethodology. The key actions of FEMLAB that reduce the drudgery ofmodeling are (I) the translation of systems of equations in symbolic form to analgorithm that can be computed numerically, (2) the provision of a wide array ofnumerical solver, analysis, and post-processing tools at either the "touch of ahutton" or (3) through a powerful "~ripting language" can be programmed inMATLAB as subroutines (function calls) and automated. So much of modelingof partial differential equations in the past has been devoted to the computerimplementation of algorithms that the modeler did not get the chance (0 properlyconsider modeling alternatives. Who would consider a different modelingscheme if it meant spending three graduate student years building the toolsbefore the scheme could be tested? FEMLAB is a paradigm shift for modelers-it frees them to ask those "what iP' questions without the price of coding a newcomputer program. Nonetheless, FEMLAB uses FEM as the powerhouse of itsPOE engine. Chapter Two gives an overview of how FEM is implemented inFEMLAB. For experienced FEM users, the takeaway message is that FEMLABtranslates POEs specified symbolically into the assembly of the FEM augmented

  • "Process ModelUllg (md Simulatioll willi Finite Element Me/hods

    Figure 0.11 Boundary settings pcmlit cntry of boundary data for each. boundary wilh a range of pre-built boundary conditions for the application mode. Here, not only is lhe inflow mean u,v_vclocityspecified fOf boundary 1. hut the turbulence intensity k and energy dissipation rate as well.

    stiffne.~s matrix - the Jacobian. the load vector, and auxiliary equations forL.1grangc multipliers representing boundary conditions and auxiliary conditions.Chapter Two illustrates these points about partial differential equations and thefinite clement method thorough treatment of canonical types of linear, secondorder PDEs: elliptic, parabolic. and hyperbolic and gives an overview of FEM,with particular emphasis on the treatment of boundary and auxiliary conditionsby the method of Lagrange mullipliers.

    Chapter Three is about multiphysics modeling. What is it? How docsFEMLAB do it so well? There are applications: lnermoconvection. non-isothermal I.:hemical reactors, heterogeneous reaction in a porous pellet.Furthermore, the workhorse methodology for nonlinear solving, parametriccontinuation, is explained. I won't steal the thunder of Chapter Three here byexplaining multiphysics modeling in detail. Suffice to say that multiphysicsmodeling means the ability to treat many POE equations simultaneously, and theprovision of pre- built POE equations that can be mixed and matched in thespecification of a model so that the symbolic translation to a FEM assembly istransparent to the user.

    Chapter Four is about extended multiphysics: the central role of couplingvariables and the use of Lagrange multipliers. Example applications are: aheterogeneous reactor; reactor-separator-recycle; buffer tank modelling; and animmobilized cell bioreactor model.

  • 'tllrodltctiVlJ 10 Ft:MLAB 19

    itCl"

    ". u

    IUS 0.1

    .,-.,. ,.

    '. -.... "-" _..... ",.

    .,

    ."

    mll!iil!r.=- "----"=.. " ,.

    Figure 0.12 In the turbulent static mi~er model. there is only one 5ubdomain. exactly equivalent tothe single composite geometry ObjCCI specified in draw mode.

    Chapter five starlS the advanced concepts in modeling - nonlinear dynamicsand simulation. Chapter six deals with geometric continuation, and Chapterseven lrealS integral equations and inverse problems. All three chapters arclargely drawn from my own research portfolio, but there arc also newlydeveloped treatments or extended studies from previous works. Rather thansystematically exploring the fcatures of FEMLAB as in chapters 1-4, chapters 5-7 pose the question "Can FEMLAB be hem 10 solve the problcms that interestme in stability theory (five), complex geometries and modulating domains (six)or inverse problems (seven), where I know the questions and desired forms ofthe answers, but can FEMLAB provide the solution tools'! These chapters willhave their own audiences for the direct questions they treat, but should providemany users with fertile proving grounds and a baskctful of "tricks of thc trade."GeHing information into and out of the FEMLAB GUI is onc of the weaknessesof the package. Many of my tricks arc how 10 use the MATLAB interfaces to dointricate (/0.

    Chapters eight through ten are purely about applications and arc only co-authored by mc. To a large degree, chapters 5-7 are about my applications andtheir generalizations, used to demonstrate FEMLAB functionality. Chatpers 8-10 are thc applications of colleagues for which we thought FEMLAB and theconcepts of chapters (-4 should be exploitable. My co-authors of these chaptershave other agendas and that is evident in the narrative voice adopted in thesechapters.

  • 20 Proce$$ Modellinfl. and Simulation with f"inile Element MelhooJ

    Figure 0.13 The subdornain settings dialogue box permits data entry fOf the PDE coefficientsdefined in the equation line above the select labs. Heno. the coefficient tab is selected for domain I.the same domain as shown in Figure 0.12. The constants roof and nuf defined ;n the ""ddlEdilCOllstams dialogue box under tile OptiOllS Menu are entered here. as are formula for the artifidaldiffushm and streamline diffusion coefficients. NOle lhat lhe production term P is not specificallydefined. so reference needs 10 be made 10 lhe documentation.

    Chapter eight i!> about the level set melhod for modeling two phase flows thatarc dominated by interfacial dynamics and transport. The subject matter wasmastered and modelled in record time for one of my doctoral students. Thesimulations are a reflection of the need for researchers !O be able to runnumerical experiments in complex systems dynamics to augment understandingof laboratory experiments. Such "in silico" experiments are more flexible thanlaboratory experiments. provide a much greater wealth of detailed knowledge,but at the expense of modeling errors of all varieties.

    Chapter nine focuses on electrokinetic flow modeling in microfluidicapplications. A substantial fraction of FEMLAB users arc numbered in themicmtluidics community, especially wirh biotech end-uscs. Rather early on, wetargeted FEMLAB as a potentially useful modeling tool for microtluidic reactornetworks for the "chemical-factory-on-a-chip" community. The extendedffiultiphysics capabilities of FEMLAB for designing such factories are anexplosive growth area which should benefit the community. Microfluidics 2003[6J was sponsored by COMSOL for just this reason.

  • InrmduCI;OIlIO FEMLA8 21

    J-lgure 0.14 Mesll mode sllows llie existing mesh and pcnnils specification of mesh parnmews fortile elliptic mesll gcner:ltor routine.

    The appendix, a MATLABIFEMLAB primer for veclor calculus, is acompromise between Ihe recurrent suggeslion of siudents laking the module formore MATLAB instruction and my desire for the students to grasp vectorcalculus more intuitively. I am actually a late convefl to MATLAB, withapologies to Cleve Moler, its creator. I was one of the graduate students giftedwith the bela test edition of MATLAB 1.0 while he was developing it. At thetime. computational power was expensive and there was a bias againstinterpreted environments for scientific computing. To programmers, the samematrix U1i1ities were available as libr

  • 22 Pro
  • Chapter I

    FEMLAB AND THE BASICS OF NUMERICAL ANALYSIS

    W.BJ. ZIMMERMANDepartment ofChemical find Process Engilreering, University ofSheffield.

    Newcastle Street, Sheffield 51 JiD United Kingdom

    E-mail: [email protected]

    III this chapter. several key elcment~ of TlUlTK:rical analysis arc profiled in n~MLAB wilhO-D and l-D models. These elemems arc root finding. numerical intcgmtion bymarching. numerical illlegmtion of ordinary differential equations, and linear systemanalysis. These methods underly nearly all problem solving techniquC$ by numericalanalysis for chemical engineering applications. The use of these methods in I'EMLAB isillustrated with reference to some COlnlDon applicaliOlls in chemical engineering: nashdistillalion, tubular reactor design, diffusivc_rcaelive systems. and heal condudiol1 insolids.

    1.1 Introduction

    This chapter is rather busy, as it must accomplish several different goals.Primarily, it is intended to introduce key features of how FEMLAB works.Secondarily, it is to illustrate how these key features can be used to analysesimple enough chemical engineering problems thaI O-D and l-D spatial orspatial-temporal systems can describe them. The chapter is also intended towhet your interest to investigate modeling and simulation with FEMLAB bypreseming at least a glimpse of the power of the FEMLAB and MATLAB toolswhell applied to chemical engineering analysis.

    Because FEMLAB is not intended to be a general tool for problem solving,some of these goals are achieved ill a roundabout fashion. The author haspreviously taught courses in chemical engineering problem solving by numericalanalysis using FORTRAN, Mat/zemalicaH.l, and MATLABT"', and used all theexamples implemented here with those tools. Furthermore, the most extensivecompilations of chemical engineering problem solving by numerical analysishave been done in POLYMATH Ill. which only seems to be u!>ed by thechemical engineering community through the CACHE program,

    The upshot is that for the examples in this chapter, FEMLAB is probablynot the package of first choice for the analysis. From the author's experienceeither MATLAB or Mar/zematica is preferable, with less overhead in selling upthe calculations, Nevertheless, even though FEMLAB was not necessarilyenvisaged 10 solve such problems, lhat ils numerical analysis tools are general

    23

  • Process Modelling and Simula:ion ...irh Fin;u Elemenl Me/hods

    enough to do so is important information that will benefit the reader in Interchapters, where very clearly FEMLAB is the first choice package for the analysis- 2-0 and 3-D spatial-temporal systems with multiphysics.

    1.2 Method I: Root f"inding

    Typically. courses in numerical analysis So into great detail in Ihc description ofthe algorithm classes used for root finding. From experience, there are only twoalgorithms that are really useful - the bisection method and Newton's method.Instead of prcscnling all the methods, here we will consider why root finding isone of the most useful numerical analysis tools. Finding roots in linear systemsis fairly casy. Nonlinear systems are the challenge, and nearly all interestingdynamics stem from nonlinear systems. The interest in root finding in nonlinearsystems results from its utility in describing inverse functions. Why? Becausewith most nonlinear functions, the "forward direction". y=-f(u), is well described,but the inverse function of U=fl(y) may be analytically indescribable, multi-valued (non-unique), or even non-existent. But if it exists, then the numericaldescriplion of an inverse function is identical to a Toot finding problem - find usuch Ihat F(u)=O is equivalent to F(14)=f(U)-y=O. Since the goal of most analysisis to find a solution of a set of constraints on a system, this is equivalent toinvening the set of constraints. FEMLAB has a core function for solvingnonlinear systems, !amnlin, and in this section its use to solve O-D root findingproblems will be illustrated.

    famnlin uses Newton's method which with only one variable u uses the firstderivative F'(u) which is used iteratively to drive toward the root. The methodtakes a local estimate of the slope of the function and projects 10 the root Theslope can be computed either analytically (Newton-Raphson Method) orIlulllcril,;ally (lhe: SCl,;aUl mcthod). If the: :slupe call bc computcd t:ithcr way, yuucan usc Taylor's theorem to project to the root. The basic idea is to usc a Taylorexpansion aboU! the current guess uo:

    / (u) = / (uo)+(u -uo)/'(uo)+'"which can be re-arranged to estimate the root as

    u =u _ /(uo)o I'(l/o)

    (1.1)

    (1.2)

    This methodology is readily extendable to a multiple dimension solution space,i.e. u is a vector of unknowns, and division by t(uoJ represents multiplication bythe inverse of the Jacobian of f. The next subsection ilIustrales root finding inFEMLAB.

  • FEMU,B und rhe Basics of Numerical Analysis

    1.2. [ Rool finding: A simple application of the FEMLAB nonlinear solvL'l""

    As implied in the previous section, rool finding is a "0-0" ;activity, at least interms of the spatial-temporal dependence of the SOlution vector of unknowns, U,which can be a multi-dimensional vector. FEMLAB does not have a "0-0"application mode, so we must improvise in I-D. This has the undesirable fealUrethat we will unnecessarily solve the problem redundantly at several points inspace. Given the small size of the problem, the efficiency of FEMLAB coding,and the speed of modem microprocessors, this causes no guilt whatsoever!

    Start up MATLAB and type FEMLAB in the command window. After severalsplash screens, you should be facing the Model Navigator window.

    Model Navigator Select 1-0 dimension Select PDE modes - Coefficient fonn Element: Lagrange-linear More OK

    This application mode gives us one dependent variable u, but in a I-D spacewith coordinate x. Now we are in a position to set up our domain. Pull down theDraw menu and select Specify Geometry.

    Draw Mode Name: interval Start: 0 Stop: I Apply OK

    Now for the boundary conditions. Since we wish to emulate 0-0 (no spatialvariation) then Neumann boundary conditions (no slope at either boundary) areappropriate. Pull down the Boundary menu and select Boundary Settings.

    Boundary Mode I Boundary Settings Select domains I alld 2 (hold down ctrl key) Select Neumann boundary conditions Apply OK

    Subdomain mode specifies the equation to be satisfied in each subdomain. Pulldown the Subdomain menu and select Subdomain settings. Notice the

  • 26 1'rcK:f!SS Modelling nnd Simularion with Finile Element Me/hods

    equation in the upper left given in vector notation. In 1-0, this equation can besimplified to

    au a(au ) aud.--- c-+auy +au+{3-=!at ax ax ax (1.3)

    Clearly, ay and 6 arc redundant with the simplification 10 I-D. Since we wanl tofind TOOls in 0-0, however, :lllthe coefficients on thc LHS of (1.3) can be set tozero. Let's solve for the roots of the polynomial equation u3 + i - 4u + 2 = O.

    Subdomain Mode I Subdomain Settings Select domains J Sct c=O; a:::4; (=u"3+u"2+2; da=O Apply Select the init tab; set u(lO)=-2 ApplY 10K

    By rearranging the jXllyllornial, we can readily see thai 0=4 and f = lil + u2+ 2.One lasl slep - discretizing thc domain with clements. Since we do nol wish

    to replicate our effort, we will mesh the interval with exactly one element, theclosest we can get to O-D! Pull down the Mesh menu and selecl the Parametersoption.

    Mesh Mode Set Max clemem Si7,.C, general = 1 Select Rerncsh OK

    The report window now declarcs "Initialized mesh consists of 2 nodes andclements."

    Now 10 find the root nearest to the initial guess of -2. If you are wonderingwhy a=4 was set, rather than all of the dependence put into f, it is so that thefinite clement discretization of the RHS of (1.3) docs not result in a singularstiffness matrix. Now pull down the Solve menu and select the Parametersoption. This pops up the Solver Parameters dialog window.

    Solver Parameters General tab: select stationary nonlinear

    solver type. Jacobian: select Numeric option Solve Cancel

  • FEMLAB and the Basics atNumerical Analysis 27

    Note in proof: I got into the habit of using the coefficient mode tlnd numcrieJacobian as it mirrors my style of FEM coding - the eocfficiem mode does notinclude all tne potemial nonlinearity in the coefficient.. in assembling tnestiffness matrix, but by computing thc Jacobian numerically, it is all included inthe iterative scheme, For small problems, you will see no performancedegradation. On larger problems, it is \\iser to use the PDE general mode andthe exact Jacobian option, which assembles the full nonlinear contributions to thcJacobian analytically. If I had to write this chapter again, all the coefficientmodes would disappear.

    During the Solve step, the report window shows a runout of several columnsper iteration; particularly important is the error estimate ErrEst, which foriteration 4 is about 10-7 which is smaller in magnitude than the defaulttolerance set at 10.6. in the Nonlinear lab of the Solver Parameters dialogbox. Click anywhere on the grid and the report window will "Value of u(u) at0.456: -2.73205." The analytically determined root nearest to this is -1-J3,showing the numerical solution in good agreement. According to the structure ofthe quadratic formula of algebra. clearly another root is -1+J3. and byinspection, Lhe third root is I. Returning to the subdomain settings, set the initialguess to u(tO)=-0.5 and FEMLAB converges to u=0.732051, again a goodapproximation. u(10)=1.2 as an initial guess converges to u=l.

    This exercise clarifies two features of nonlinear solvers and problems - (i)nonlinear problems can have multiple solutions; (ii) the initial guess is key toconvergence to a particular solution. With Newton's method, if is usually thecase that convergence is to the nearest solution, but overshoots in highlynonlinear problems may override this stereotype. These features persist inhigher dimensional solution spaces and with spatial-temporal dependence.

    The MATLAB model m-file rootlinder.rn contains all the MATLAB sourcecode with FEMLAB extensions to reproduce the current state of the FEMLABGUI. This file is available from the website http://eyrie.shef.ac.uklfemlab. Justpull down the file menu. select Open model m-fiIe, and use the Open file dialogwindow to locate it. You can rapidly place your nonlinear function in theSubdomain settings, specify an initial guess, and use the stationary nonlir.earsolver to converge to a solution. But what if your function does not have a linearcomponent to put on thc LHS of (1.3)'1 For instance, tanh(u) - u2 + 5 = 0results in a singular stiffness matrix when FEMLAB assembles the LHS of (1.3).The suggestion is to sct the coefficient or" the second derivative of u. c=1 in thcSubdomain settings. Coupled with the Neumann boundary conditions, thisartificial diffusion cannot change the fact that the solution must be constant overthe single clement. yet it prevents the stiffness matrix from becoming singular,

    RoO! Fillding ill General ModeThe difficulty with a singular stiffness matrix assembly for tanh(u) - 1/ + 5 = 0 canbe averted by using General Mode, which solves

  • 28 Pnxes Modelling aM Simulation wilh Finite ElerMrlt Methods

    (1.4)

    where /(u,ux) is in principle the same functionality as the coefficient form (1.3),but is treated differently by the Solver routines. In Coefficient Mode. thecoefficients are treated as independent of u unless the numerical Jacobian isused, which brings out some of rhe nonlinear dependency - ileraLion docs therest. The exact Jacobian in General Mode differentiates both rand F withrespect 10 u symbolically in assembling the stiffness matrix. Typically, GeneralMode requires fewer iterations for convergence than Coefficient Mode with thenumerical Jacobian. The usc of the exact Jacobian below docs nOI require anyspecial treatment to avoid a singular stiffness matrix in the treatment of the linearterms as the coefficient mode did. In general. General Mode is more robust atsolving nonlinear problems than Coefficient Mode. It is my opinion thutCoefficienl Mode is a "legacy" feature of FEMLAB - the POE Toolbox ofMATLAB, in many ways a precursor to FEMLAB, uses coefficientrepresentations extensively. Further, the coefficient fonnulation with numericalJacobian is a long standing FEM methodology, so for benchmarking againstother codes, it is a useful formulation.

    Here's the recipe for General Mode - a minor modification of what we justdid.

    Model Navigator 1-0 geom., PDE modes, gcneral form nonlin stat)Gotions Sel Axes/Grid to (0, I JDraw Name: interval; Start 0; Stop 1Boundary Model Set both endpoints (domains) [0 Neumann BCsBoundarv SettingsSubdomain Model Set r = 0; da = 0: F = u"3+u"2-4*u+2Subdomain SeuingsMesh modc Set Max element size, e:encral _ I: RemeshSolve Use default sellin's nonlinear solver, exact Jacobian)Post Process After five iterations. the solution is found. Click on the

    graph to read out u=0.732051. Play with the initialconditions to find the other two roots.

    Although setting up Ihis template (rtfindgen.m) for root finding of simplefunctions of one variable was rather involved, and in fact MATLAB has asimpler procedure for root finding using the built-in function Czero and inlinedeclarations of functions, the FEMLAB GUI still provides many options andflexibility to root finding that may not be available in other standard packages.The next subsection applies our newly constructed nonlinear root finding schemeto a common chemical engineering application. flash distillation, which clarifiesa few more features of the FEMLAB GUI.

  • FEMUoB and Ihe Basics ofMmrerical Analysis

    1.2.2 Root finding: Application to flash distiUation

    29

    Chemical thermodynamics harbors many common applications of root finding,since the constraints of chemical equilibrium and mass conservation arefrequently sufficient, along with constitutive models like equations of state, toprovide the same number of constraints as unknowns in the problem. In thissubsection, we will take flash distillation as an example of simple root findingfor one degree of freedom of the system, whieh is conveniently taken as thephase fraction ~.

    A liquid hydrocarbon mixture undergoes a flash to 3.4 bar and 65OC. Thecomposition of the liquid feed stream and the 'K' value of each component forthe flash condition are given in the table. We want to determine composition ofthe vapour and liquid product streams in a flash distillation process and thefraction of feed leaving the flash as liquid. Table 1.1 gives the initialcomposition of the batch.

    Table 1.1 Charge to the flash unit

    ComponentEthanePropanei-Butanen-Butanei-Pentanen-PentaneHexane

    x,0.00790.12810.08490.26900.05890.13610.3151

    K- at 65C and 3.4 bar16.25.22.61.980.910.720.28

    Rash at 3.4 barand 65C

    A material balance for component i gives the relation

    X, = (I - )y, +X, ( \.5)where Xi is the mole fraction in the feed (liquid), Xi is the mole fraction in theliquid product stream, Yi is the mole fraction in the vapour product, and r is theratio of liquid product to feed molar flow rate. The definition of the equilibriumcoefficient is Ki=Yi /xi Using this 10 cJiminafc Xi from the balance relationresults in a single equation between Yi and Xi:

    y, =' X,

    1-.[1-nSince the Yi must sum to I, we have a nonlinear equation for $:

    . " Xf()= 1-I ' =0,., 1-.(1- :,1

    (1.6)

    (1.7)

  • 30 I'roCiSJ Modelling and Simulation with Fi,lile ElenretJI Me/hods

    where n is the number of components. This function f(~) can be solved for theroot(s) $, which allows back-substitution to find all the mole fractions in theproduct stream. The Ncwton-Raphson method requires the dcrivativcf(fk) atthe current estimate to determine the improved estimate, and FEMLAB willcompute this analytically as an option. It is fairly straightforward to arrive at theNewton-Raphson iterate as

    (1.8)

    Now onto the FEMLAB solution for root finding. As an exercise, we will set upthe solution using the general POE mode. We could just load rootfindcr.rn orrtfindgcn.m and customize it. but of course becoming familiar with FEMLAB'sfeatures is an imporlant goal.

    Start up FEMLAB and await the Model Navigator window. If you alreadyhave a FEMLAB session started. save your workspace as a model MAT-file orthe commands as a model m-file, and the pull down the file menu and selectNew.

    Model Navigator Select I-D dimension Select POE modes - General Element: Lagrange - linear More OK

    This application mode gives us one dependent variablc u and one spacecoordinate ;r;. Ne;r;t. set up the domain. Pull down the Draw menu and selectSpecify Geometry.

    Draw Mode Namc: interval Start: 0 Stop: 1 ApplY I OK

    Now for something ncw. We must enter our data. Pull down the options menuand select Add/Edit constants. The AddlEdit constants dialog box appears.Now enter our fourteen pieces of data:

  • FEMLAB and lire Basics ofNII~ri(alAnalysis

    AddlEdit Constants Name of constant: X I Expression: 0.0079 Apply Name of conslant: KI Expression: 16.2 Continue with the rest of Table 1.1 OK

    Now Onto the Neumann boundary conditions. Pull down the Boundary menuand select Boundary Settings.

    Boundary Mode Select domains I and 2 (hold down ctrl key) Select Neumann bounda!)' conditions Apply 10K

    31

    Next Subdomain mode. Pull down the Subdomain menu and selectSubdomain mode. Before setting the equations, il is useful to define someintennediate variables to make the data ent!)' more concise. Pull down theoptions menu and select Add/Edit expressions. By experience, you should bein Subdomain mode to add expressions for Ihe first time.

    AddlEdit Expressions Variable name: 11 Variable type: subdomain Add Repeat to create t2 through t7 Now select variable tl and click on the

    definition lab. Select level: subdomain I Enter expression: ~X I/(I-u*( I-11K 1)) Apply Now select the variables tab, select t2, and

    then click on the definition lab, and enter thesimilar expression for tl, substitute index 2where appropriate.

    Continue with indices 3 through 7 OK

  • 32 Process Modelling lind Simutmion with Finile Eten/elll Methods

    Now pull down the Subdomain menu and select Subdomain settings. Defaultvalues of d.=!. r=-ux. and F=l arc specified in Ihe data cntry locations.Because we selcct Neumann BCs for spatial dependency. we can lake the defaultsetting for r=-ux without contradiction. As you will see, Ihe solution is"spatially flat" - pseudo-OD.

    Subdomain Mode I Settings Select domains I Set F= 1+t 1+t2+t3+14+15+t6+t7; d.=O Apply Select the init tab; sel u(tO)=O.5 Apply/OK

    Pull down the Mesh menu and select the Parameters option to set up our singleclement.

    Mesh Mode Set Max element size, general - I Select Remesh OK

    The report window now declares "Initialized mesh consisL~ of 2 nodes and Iclements."

    Now pull down the Solve menu and select the Parameters option. This popsup the Solver Parameters dialog window.

    Solver Parameters General tab: select stationary nonlinear

    solver type. Jacobian: retain default Exact option Solve Cancel

    After three iterations, we find that 41=0.458509 solves for the phase fraction atequilibrium. For your own information, resolve with the initial guesses $--0 and$=1. How many rOOIS would you expect to this function? If you wish to avoidall of the data entry, then you could just load the MATLAB model m-file l1ash.mthat came with the distribution.

  • FEMIAH and the Rasics ofNumerical Analysis 3)

    ,

    ,

    ,

    ,

    1.1 Find the root of the equationflu) =ue~ - I =O. This function istranscendenlal, which means that ilhas no analytic solution in therational numbers. If you useCoefficient Mode, put c=1 to aidconvergence. c~,:-~~~,--c~,_--+"7Lc--:--7,

    Exercises:

    Figure l.l u c~p(u)-1.

    ( ) ,5 I1.2 Find the roots of the equation f u ::;; u - 3u +-ll - - ::;; 0 . As this2 2function is a cubic polynomial, there is an analytic solution in the irrational

    I Inumbers, u=), u=l- J2' u=l+ J2'

    1.3 Method 2: Nutneric:.tllntegration by MarchingNumerical integration is the mainstay of numerical analysis. The first duty ofscientific computing before there were digital computers were to fill thehandbooks with tables of special functions, nearly all of which were solutions tospecial classes of ordinary differential equations. And the computationalmethodology? One-dimensional numerical integration.

    There arc two classes of I~D integration: initial value problems (IVP) andboundary value problem.~ (BVP). The laUer will he con.~idercd in the nextsection. The easiest to integrate arc IVPs, as jf all the initial conditions are allspecified at a point, it is straightforward to step along by small incrementsaccording to the local first derivative. Clearly, if the DOE is first order, i.e.

    y I,.~= y I, +i1tf (I) (1.9)

    (1.I 0)

    The second statement in (1.9) is true exactly in the limit of 111 -+ O. It istermed the Euler method and is the most straight-forward way of integrating afirst order ODE. In one dimension, you simply step forward according to thelocal value of the derivative of f at the point (xn,y,J, where n refers to the n-lhdiscreti:r,.ation step of the interval upon which you arc integrating. Thus,

    Y." = Y. +hf(x.,yJ

  • 34 Process Modelling and Simulation with Finite Eleme/ll Methods

    This assumes that the derivative does not change over the step of size h. which isonly actually true for a linear function. For any function with curvature, this is alousy assumption. Consider. for inslance, how far wrong we go with a large stepsize in Figure 1.2. So clearly, one important point in improving on Euler'sMethod is to be able to use big steps, since it requires small steps for goodaccuracy. Euler's method is called "first order" accurate, as the error onlydecreases as the first power of h.

    Figure 1.2 Curvature effects arc losl in lllc Euler method,

    Runge-KUlla methods

    So if we want to usc big step sizes, we need a "higher order method", one thatreduces the error faster as step size decreases. A k-th order method has errorwhich diminishes as Ilk. Given that it is curvature thaI we know we arcneglccting, we can estimate the curvature of the graph y(x) by evaluating theslope f(x) at several intermediate points between xn and xn+l' Second orderaccuracy is obtained by using the initial derivative to estimate a point halfwayacross the interval, then using the midpoint derivative across the full width of theinterval.

    k, = lif(x.. yJk, =hf (x. +~ h,y. + ~k,)Yn+1 = Yn +k2 +O(h 3 )

    (1.11)

    The upshot is that by making two function evaluations, we have saved a wholeorder in accuracy. So, for instance, with a first order method, N calculationsgives us an error O(lIN), but for a sccond ordcr mcthod, 2N calculations gives

    22. .us error O(114N). It would take N calculatIons to do so wcll with a first ordermethod.

    Higher order Runge-Kuna methods

    Can we do better? Clcarly, we can use a three midpoint method to achieve thirdordcr accuracy, a four midpoint method for fourth order accuracy, etc. When

  • PEMLAlJ (lI1d tlte l1(lSics ofNumerical Analysis"

    should we stop? Well, there is more programming work for higher ordcrmethods, so our time is a consideration. But intrinsically, function!> may not bevery smooth in their k-th derivative that we arc estimating. It is possible Ihat inincreasing the "accuracy of the approximation", the round-oIT error of higherderivative terms so estimated becomes appreciable. If that is the case, with eachsuccessive step, the error may grow rapidly. This implies that higher ordermethods arc less stable than lower order methods. The common choice forintegrating ODEs is to use a fourth order Runge-Kulla method. This is fairlycompact to programme. gives good accuracy. and typically has good stabilitycharacter.

    Other methods

    There are two other famous problems in numerical integmtion that needpanicular programming attention:Numerical Instability. Suppose your integration diverges to be very far fromknown test-cases, even with a high order accuracy method. Then it is likely thatyour method is numerically unstable. You can cut down your step size andeventually achieve numerical stability. However, this mcans a longercalculation. If you arc computing a great many such integrations and theslowness really bothers you, Iry a semi-implicit method like predictor-{;orrectorschemes.StitT Systems. Stiff systcms usually have two widely disparate length or timescales on which physical mechanisms occur. Stiff systems may have "numericalinstability" of the explosive sort mentioned above. or they may have non-physical oscillations. Try the book of Gear 12J for a recipe to treat stiff systems.

    1.3.1 Numerical integration: A simple example

    Higher order ODEs are treatable by marching mcthods by reduction of order.Suppose you have an ode:

    d'y dy ()-+q(x)-=r Xdx2 dx

    ( 1.12)

    Unless q(x) and r(x) are constants, then you are out of luck with most textbookanalytic methods for finding a solution. There are special cases of q(x) and r(x)that lead to analytic solutions, but these days you are better off computing thenumerical solution in nearly all cases anyway. Why? Because you need to plotthe graph of the solution y(x) to make sense of it, so you will need to harnesssomc computing horse power for the graphics. How? First let's reduce the orderof the second order system above to two first order systems:

  • 36 Process Modelling and Simu{aliQ1I will, f,nitl! Element Me/hods

    dy =Z(x)dx

    dz = r(x)- q(x)Z(x)dx

    (1.13)

    Each of these ODEs can be numerically integrated by time marching melhods asin (1.10) or (1.11), simultQlleou.\-ly. A simple eXilmple is

    d 2u-+u=odr'

    Reduction of order yields two first order ODEs:

    du,--=-u2dtdu,--=u1dt

    (1.14)

    Taking the initial condition to be Ul=! and u2=O. we can now SCI up a O-D spatialsystem to integrate this coupled set of ODEs.

    Start up FEMLAB and await the Model Navigator window. If you already havea FEMLAB session started, save your workspace as a model MAT-file or thecommands as a model m-file, and the pull down the file menu and select New.

    Model Navigator Select I-D dimension Select PDE modes - Coefficient+timc dependent Select 2 dependent variables Element: Lagrange - linear More OK

    This application mode gives us two dependent variables Ul and U2 and one spacecoordinate x. Next, set up the domain.

    Pull down the Draw menu and select Specify Geometry.

    Draw Mode Name: interval Start: 0 Stop: 1 Apply I OK

  • FEMLAB and the Bcsics ofNumuical Analysis 37

    Now onto the Neumann boundary conditions. Pull down the Boundary menuand seleclBoundary Settings.

    Boundary Mode Select domains I and 2 (hold down ctrl key) Select Neumann boundary conditions Apply I OK

    Now pull down the Subdomain menu and select Subdomain settings. NoticeIhe equation in the upper left given in vector nOlation.

    Subdomain Mode Select domains I Set fl=O; f2=O; (1),= I; a21=-I; CI= I; C2= I ; Apply Select the iniltab; sel UI(IO)=1. Apply 10K

    Pull down the Mesh menu and select Ihe Parameters oplion to set up our singleclewent.

    Mesh Mode Sel Max element sil'.e. general _ I Select Remesh OK

    Now pull down the Solve menu and select the Parameters option. This popsup tne Solver Parameters dialog window.

    Solver Parameters Time-stepping tab: set output times

    linspace(O,2*pi,SO) Jacobian: numeric Solve Cancel

    1 inspace (0, 2*pi, 50) is the MATLAB command to create a vector oflength 50 which uniformly goes from 0 to 2:tr. Click anywhere on the graph andyou learn that ul(t=2:tr)=1.02475. Given that the analytic solution is ul(t=2:tr)=1,this is rather inaccurale (2%). The odel5s solver is a stiff solver with low tomedium accuracy. ode45 has the best accuracy of the suite of solvers, but is fornon-stiff systems. It gives ul(1=6.29)=O.99994, which is pretty good. Greateraccurdcy, however. comes from decreasing the output time interval. Iflhe output

  • 38 Process Modelling and Simulation wirh Finire tJemenl Mellwds

    .0>

    times are set to linspace (0, 2*pi. 500), i.e. tenfold smaller time-step, thanuI(I=2n)=0.999939 with odc15s.

    These two figures (t.3 & 1.4) clarify that FEMLAB can reproduce Ihenumerical integration of thc cosine and sine functions with high fidelity if givena small enough time step. Allhaugh we think of sine and cosine as "analyticfunctions," when tabulated this way, it is clear that thc distinction betweenanalytic functions and those Ihat require numerical integration is specious - theyare no more analytic than Bessel functions, elliptic functions, etc.

    1.3.2 Numerical integration: Tubular reactor design

    In this subsection, a coupled sct of first order nonlinear ODEs are solvedsimultaneously for the design of a tubular reactor undergoing a homogeneouschemical reaction. Typically. {he key element in the design of a tubular reactoris the estimate of the length of the reactor.

    A tubular reactor is used to dehydrate gaseous ethyl alcohol at 2 bar and150"C. The formula for this chemical reaction is

    1 ""' /~, /\ /\\, II

    \ /\\ /

    , I

    '\ //..~.----:----:,c--"::'., ~c:...--:.----:,~-~.c-----:,

    Figure 1.3 Ul(l) over one period.

  • .,

    o.s

    Ft:Ml.AB arrd the Basics ofNumerical Allalysis

    /--"/ \

    os / \, ,, ,, ,

    / \, ,, ,

    , \\ I

    \ /, ,\, /"'-~/

    1 50~---:-----,;---",C---7,---,;---~,,-----:,

    Figure 1.4 u2(t) OVer olle period.

    39

    Some experiments on this reaction have suggested the reaction rate expression at2 bar pressure and 150"C. where CA is the concentration of ethyl alcohol(mol/litrc) and R is the rate of consumption of ethyl alcohol (moUslm3):

    R:= 52.7C~I 0.013+--

    C,

    The reactor is to have a 0.05m diameter and the alcohol inlet flowrate is to be109/so The objective is to determine the reactor length to achieve variousdegrees of alcohol conversion. We wish to determine reactor length for theoutler alcohol mole fractions 0.5, 0.4, 0.3,0.2, and 0.1.

    Chemical Engineering Design Theory

    Assuming small heat of reaction, plug now and ideal gas behaviour, it can beshown thai the reacting now is described by four ordinary differential equationsin terms of the dependent variables CA. Cw (the water concentration), V (thevelocity) and x (the distance along the reactor from the inlet):

  • Process Modelling and SilllufaliQn wilh Pinile ElemRnl Me/hods

    dell =_Jl+CII )dl "l C

    dew =R(l- Cw )dl C

    dV RV-=--

    dl C

    dx =Vdl

    (1.15)

    The last equation states thaI the superficial velocity creates an equivalencebetween distance along the reactor and the residence time t that a fluid elementhas to react These equations are subject to the initial condition of the now atthe inlet (1=0):

    C, (O)=CC.(O)=O

    V(O)=V,x(O)=O

    (1.16)

    Approach

    Clearly from the initial condition and stoichiometry, Cw=Ct; (the concentrationof ethyl alcohol, and the value of C is constant as temperature and pressure areassumed constanl. C can be found from the ideal gas law, with

    C= p.,.(8314 J )'l kmolK

    ( 1.17)

    And the initial flow velocity Vo can be determined from the flowrate given, theinlet density (the molecular weight of ethyl alcohol is 46 kg/kmol), and the tubecross-sectional area. The equations will need to be integrated numerically inspace-time t until the required alcohol mole fractions have been reached. Useeither simple Euler or Runge-Kuua numerical imegrmion.

    You may note that it is possible to solve for CA without recourse to the othervariables, but CW, V, and x depend explicitly on t. But since the requirement is10 find positions x where specific mole fractions occur, it is best 10 solve for allfour variables simultaneously.

  • FEMLAB and lhe Basics ofNumerical Analysis

    Parrial Result",

    A resolved numerical solution gives

    C, =0.1C

    t = 5.65225x = 18.5435

    with a profile for CAlC as in Figure 1.5.

    1

    0.'

    0.6

    0.'

    0.2 ~

    41

    (1.18)

    2 6 10Figure 1.5 Profilc of nonnalizcd alcohol concr:ntnllion vs. space time t.

    FEMLAB Implementation

    We wish to create our pseudo-DO simulation environmenl yet again, this timewith four dependent variables. Start up FEMLAB and await the ModelNavigator window.

    Model Navigator Select 1-0 dimension Select PDE modes - Coefficient+time dependent Select 4 depelldcnI variables Element: Lagrange - linear More OK

    This application mode gives us four dependcnt variables UI Ul UJ 14and one spacccoordinate x. Next. set up the domain.

    Pull down thc Draw menu and select Specify Geometry.

  • 42 Pro
  • FEMLAJJ and Ihe Basics ofNumerical Analysis 43

    Pull down the Mesh menu and select the Parameters option to set up our singleelement.

    Mesh Mode Set Max clement size. general _ I Select Remesh OK

    Now pull down the Solve menu and select the Parameters option. This popsup the Solver Parameters dialog window.

    Solver Parameters Time-stepping lab: set output times 0:0.1: 10. Jacobian: numeric Solve Cancel

    Try plotting point plots of til, U2, Ul and U4 for the whole mnge of times. Howgood is the qualitative agreement with Figure 1.5? Does it agree 11l1mericallywith the fully resolved solution'!

    /;xercises:

    1.3 Find the value of y'(x=/J from the system of equations below. Plot y' for xbetween 0 and 3.

    , , 0y+y+y=y(x=O)= Il(x=O)=O

    1.4 Linear systems of ODEs resull from first order reversible reaction systemsin a continuously stirred tank reactor. For instance, consider theisomerization reactions

    with forward reaction rates k l and kl , respectively. as written; reversereaction rates k2 and ~, as written. First order kinetics leads to thefollowing system of ODEs:

  • 44 Process Modelling und Simulation with Finite Hlement Me/hods

    dC A-- '" - klC II + k2C 13d.

    deB", k,ell

    - k2C

    Il- k

    3C

    Il+ k

    4C

    CdLdCc--= k3C fl - k4CCd.

    It may surprise you, but because the above system is linear, it has a general,analytic solution. Though general, it lends little insight into the dynamics of thesystem. Plot the graph of concentrations versus time for Ihe initial valueproblem. Stan with pure ell=1 with parametric values k l= 1 Hz, k2 =0 Hz, k)=2Hz, k.t=3 Hz and plot the graph versus time of concentrations.

    ].4 Method 3: Numerical Integration of Ordinary Differential Equations

    In the previous seclion, numerical integration was treated by marching methods,commonly referred to as "lime-stepping," allhough in the reactor designapplication, it was clearly spatial integration. In marching methods, theunknowns arc found sequentially. The other common mcthod for integration is toapproximate the ODE and solve simultaneously for the unknown dependentvariables at the grid points. With marching methods, all solutions must be initialvalue problems (IVP). The number of initial conditions must malch the order ofthe ODE system. But for second order and higher systems, a second type ofboundary condition is possible - the boundary value problem (BVP), where in 1-0, there arc conditions at the initial and final points of the domain. Hence, thesearc two point boundary value problems. Marching methods can laboriously treatBVPs by shooting - artificially prescribing an IVP and guessing the initialconditions that satisfy the actual BYP by trial and enOL III higher JimensiollulPOEs, a BVP specifics conditions on the boundaries of the domain.

    One of the major advantages of the finite element method is that it natumllysolves two-point BYPs. As an example, the reaction and diffusion equation in1-0 is

    (1.L 9)

    where It is the concentration of the species, 2; is the diffusivity, L is the length ofthe domain, H(u) is the disappearance rale by reaction, and x is the dimensionlessspatial coordinate. If the unknown function u(x) is approximated by discrete

  • FEMLA8 Clnd rhe 8asics 4 Numuical Analysis 45

    values Uj = u(Xj) at the grid point,> x=Xj=j ill, then with central differences, thesystem of equations becomes

    ( 1.20)

    where Mij is a tridiagonal matrix with the diagonal element -2, and I on thesuper and subdiagonals:

    -2 1 0 0I -2 I 0

    M= 0 1 (1.21)0 0

    and R)=R(uiJ. This system ean be solved by iteration for u", by matrix inversion,where n refers to the n-th guess:

    (1.22)

    and Rj'=R(Ui""). For either IVP or BVP, the appropriate rows of the matrix M in(1.21) can be altered to accommodate the boundary conditions. As wriuen,(1.21) supposes u=O at both x=O and x=l. This is a Dirichlet type boundarycondition, and is the natural boundary condition for finite difference methods -natural because it occurs if no dfon is made to overwrite rows of (1.21) withspecified boundary conditions.

    We will now illustrate the solUlion of (1.19) with FEMLAB on a small 1-0domain with first order rcaction R(uj=k u and representative values for theresulting dimensionless parametcr, the Damkohler number:

    ( 1.23)

    and with boundary conditions u=1 at x=O and no flux at II=}.

  • 46 Process Modelling wrd Shllulmion with finite Element Me/hods

    First launch FEMLAB and enter the Model Navigator:

    Model Navigator Select 1-0 dimension Select PDE modes _ Coefficient Element: Lagrange - linear More OK

    This application mode gives us one dependent variable u, bUI in a I-D spacewith coordinate x. Now we are in a position to SCi up our domain. Pull down theDraw menu and select Specify Geometry.

    Draw Mode Name: interval Start: 0 Stop: I Apply OK

    Now for the boundary conditions. Pull down the Boundary menu and selectBoundary Settings.

    Boundary Mode Select domain I Check Dirichlet and sct h= I; r= I Select domain 2 Select Neumann boundary conditions Apply OK

    hand r are the two handles on Dirichlet Bes in Coefficient Mode. If you want toset uio a given valuc Uo on a boundary, then it is accomplished with setting h=land r= Uo. Now pulJ down the Subdomain mcnu and seleCI Subdomainmode. Selecl Subdomain settings.

    Subdomain Mode Select domains 1 Set c=-I; (=0.833*u Selecllhe init lab: set u(to)=I-x Apply OK

  • FEMUR alld lire Hasics ofNumerical Analysis 41

    Click on the triangle symbol to mesh (15 elements) and the triangle with theembedded upside-down triangle to refine the mesh (30 clements).Now pull down the Solve menu and select the Parameters option. This popsup the Solver Parameters dialog window.

    Solver Parameters Select Slalionary linear Solve Cancel

    You should get a graph with the information as in Figure 1.6. Clearly thedesired boundary conditions are met: u=1 at x=O and the slope vanishes at x=l.BU! did FEMLAB solve the problem we thought we posed?

    Now resolve with the statjonary nonlinear solver. First nOte that FEMLABtakes thirteen iterations (Q converge. Do you notice that the final value hasdropped from 0.86 to 0.69? One might wonder why there is a difference. Thelinear solver only evaluates R(u) once at the initial condition u(tO):::I-x and thusonly needs olle iteration of (1.22). The nonlinear solver evaluatcs R(u) for eachiter3lion at the old estimate for u. Thus, the nonlinear solver might "forgcl" theinitial guess completely after a number of iterations as it homes in on aconverged solution.

    Let's test Ihis explanation. Changing the initial condition should change thestationary linear solution. Return now 10 Subdomain settings and try the initialcondition lI(tO):::/. What final value do you get for lI(x=1)? Now try thestationary nonlinear solver. Do you gct the same solution as with the other initialcondition?

    -..----

    00..... 1

    ..

    "

    .. .. .. .. .."

    .. ..

    .-Figure 1,6 Steady state first order reaction and diffusion with Da=Q.833.

  • "ProcesJ Modelling and Sim.. /alion wi,h Finite Element Me/hods

    This example should illustrate the importance of selecting the right solverfor your equations. If there is any dependence of f on the dependent variables,then the statiomlry nonlinear solver should be used. The linear solver is faster,but it also presumes that the coefficients of the PDE do nOI depend on thedependent variable 1I (clse the problem would be nonlinear). When in doubt, usethe nonlinear solver. After all, (1.19) with R(u)=k u, is a linear problem, butFEMLAB only finds the correct steady state solution with the nonlinear solver!The slow convergence rate is also the consequence of the form of the mooe\ -general mode with the exact Jacobian solver option for the nonlinear solverconverges in two iterations to the correct prolile.

    We argued thaI (1.20) is the finite difference matrix equalion for thisproblem, yet later applied the argument that (t.22) should describe the FEMLABfinite element problem. Because we used Lagrange linear elements, in thisspecial case the finite clement and finite difference matrix operators coincide, upto the boundary conditions. To see this, we will take a foray into the MATLABrepresentation of FEMLAB problems.

    Pull down the File Menu and select Export FEM structure as 'fern'. Thisputs the current solution as a MATLAB data structure in the MATLABworkspace. We can then manipulate it using the buill-in MATLAB functionsand commands, as well as the special function set of FEMLAB.

    In your MATLAB workspace, lry the commands~~x~fem.xmesh.p{l}i~~u",fem.sol.u;

    ~~plot(x,u)

    This should pop up a MATLAB Figure plotting the solution u versus the array ofmesh points. No doubt your plot looks scrambled. This is because FEMLABstores the mesh points and the associated solution variables so as to make thespecification of the rnalrix equations sparse and compact. We can make sense ofthe solution by ordering the mesh points and the solution:

    In your MATLAB workspace, try the commands~~[xx,idx):sort(x) ;~~plot(xx,u(idx))

    This plot should resemble Figure 1.6, with the exception that it represents yourlast FEMLAB solution. In fact, we can only make sense of the solution formatof the fem structure so readily because this is a single dependent variable, one-dimensional problem. Otherwise, multiple variables and dimensions leave amesh and solution structure that only FEMLAB tools/functions can readilydecode.

  • F"MUB cmd Ihe Rasics ofNumerical Analysis 49

    The final MATLAB manipulation we will consider here is interrogation ofthe finite element matrix. The fern structure does not hold the tinite elementstiffness matrix, but ralher contains the information necessary for FEMLABfunctions to construct it. This activity is a vital part of the finite element method,and the FEMLAB function that does it is called assemble. Type in thecommand below:

    [K,L,M,N]=assemble(fem};>:>K!30

    You should now see a MATLAB sparse representation of a matrix, all of theelements of whkh are I, -2, and I, arranged on different diagonals. This is thestiffness matrix of the finite element method, and up to the ordering of theunknowns, is equivalent to (1.21). If you return to Ihe Subdomain Settings,element tab, and select Lagrange quadratic elements, and repeat the solulion.exporting FEM and assemble K as above, you will note that although sparse, thematrix is distinctly different from the Lagmnge linear elements.

    Exercise

    1.5 The coefficicnt form has a pde term (J. u. Repeat the implementation of thereaction-diffusion example, but this time entering a = 0.833 andf=O for thesubdomain settings. Now compare the stationary linear and nonlinear solversolutions. Can you explain why this formulation leads to this resull? Whateffect does this formulation of the problem have on the stiffness matrix K.Can you think of a difficulty that might occur if the Oa is chosen so thai thediagonal element is nearly zero in magnitude, I.e. Oa 6.x2 = 2?

    1.5 Method 4: Linear Systems Analysis

    Central to MATLAB, and hence to FEMLAB, is linear systems analysis. In thissection. we will brieOy review the concepts of linear operator theory - typicallylumped as "matrix equ

  • Process Modelling and Simulation with Finite t."'Iemem Methods

    BrieOy, the standard matrix equations look like this:

    al1x! +a!2x2 +aUx) + + a 1N x N = h)a21 x1 +an x2 + (l23X3 + + (l2NXN =b2a 31 x 1+a32 x 2 +a))x) + +aJNxN =b3 (1.24)

    aMlx! + (lM2X2 + (l,\ox3 +... +aMNxN = b/tlHere there arc N unknowns Xj which are related by M equations. Thecoefficients Qij are known numbers, as are the constant terms on the right handside. bi. In engineering, models arc frequently derived that satisfy such linearsystems of equations. Mass and energy balances, for instance, commonlygenerate such sets of Linear equations.

    Solvability

    When N=M. there are as many constraints as there arc unknowns, so there is agood chance of solving the system for a unique solution sct of Xj's. There can failto be a unique solution if one or more of the equations is a linear combinmion ofthe Olhers (row degeneracy) or if all the equations contain only certaincombinations of the variables (column degeneracy). For square matrices, rowand column degeneracy are equivalcnt. A set of degenerate equations arc teonedsingular. Numerically, however, at least two additionallhings can go wrong:

    While not exactly linear combinations of cach olher. some of the equationsmay be so close to linearly dependent thai within round-off errors on Ihecomputer they are.

    Accumulatcd round-off errors in the solution process can swamp the truesolution. This frequently occurs for large N. Thc procedure docs not fail, butthe computed solution docs not satisfy the original equations all that well.

    Guidelinesfor Linear SystemsThere is no "typical" linear system of equations. but a rough idea is that round-off error becomes appreciable:

    N as large as 20-50 can be solved by normal methods in single precisionwithoUl recourse to specialist correction of the two numerical pathologies.

    N as large as several hundred can be solved by double precision. N as large as several thousand can be solved when the coefficients are sparse

    (i.e, most are zero) by methods that take advantage of sparseness. MATlABhas a special data type for sparse matrices, and a suite of functions that exploitthe sparseness.

  • FEM1AIJ and ,he Basics ofN1m:erical Analysis"

    However, in engineering and physical sciences, there arc problems that by theirvery nalUre are singular or nearly singular. You might find difficulty with N=lO.Singular value decomposition is a technique which can sometimes treat singularproblems by projecting onto non-singular ones.

    Common Tasks in Numerical Linear Algebra

    E4ualion (1.24) l.:all be succinctly written as a lllaLri~ equation (cr. equation1.20).

    Ax=b ( 1.25) Solution for the unknown vcctor x, where A is a square matrix of coefficients,

    and b is a known vector. Solution with more than one b vector with the matrix A held const:ml. Calculation of thc matrix A-!, which is the inverse of a square matrix A. Calculation of the determinant of a square matrix A. IfMN, there is, in general. no solution vector x to (1.24). Thisovcrdetcrmined system happens frequently, and the best compromise solutionthat comes c10sesl to satisfying the equations is sought. Usually, the closenessis "least-squares" difference between the right and left hand sides of (1.24).

    Matrix Compurmions in MATIAB

    Matrix inversion is easily entercd using the inv(matrix) command. Solution ofmatrix equations is represented by the matrix division \ operator as here:

    A= [ 3 -1 0; -1 6 -2; 0 -2 101;B=[li 5; 261; X=A\BX =

    1,00002.00003.0000

    DelerminaflUDeterminants arc used in stability theory and in