Modelica-based modelling and simulation to support ... · building simulation programs are...

19
Modelica-based modelling and simulation to support research and development in building energy and control systems Michael Wetter* Lawrence Berkeley National Laboratory, Energy and Environmental Technologies Division, Building Technologies Program, Berkeley, CA, USA (Received 1 December 2008; final version received 12 February 2009) Traditional building simulation programs possess attributes that make them difficult to use for the design and analysis of building energy and control systems and for the support of model-based research and development of systems that may not already be implemented in these programs. This article presents characteristic features of such applications, and it shows how equation-based object-oriented modelling can meet requirements that arise in such applications. Next, the implementation of an open-source component model library for building energy systems is presented. The library has been developed using the equation-based object-oriented Modelica modelling language. Technical challenges of modelling and simulating such systems are discussed. Research needs are presented to make this technology accessible to user groups that have more stringent requirements with respect to the numerical robustness of simulation than a research community may have. Two examples are presented in which models from the here described library were used. The first example describes the design of a controller for a nonlinear model of a heating coil using model reduction and frequency domain analysis. The second example describes the tuning of control parameters for a static pressure reset controller of a variable air volume flow system. The tuning has been done by solving a non-convex optimization problem that minimizes fan energy subject to state constraints. Keywords: building simulation; equation-based modelling; rapid prototyping; Modelica; controls 1. Introduction To design and operate energy efficient buildings, it is important to properly account for the dynamic system performance over a wide range of time scales and operating conditions. At the time scale of hours to days, the system dynamics determine how much energy can be stored passively or actively to exploit natural sources for heating and cooling. At the time scale of minutes or even seconds, the system dynamics deter- mine whether equipment is cycling, which can nega- tively impact its energy performance and may cause premature equipment failure. Also, the performance of certain equipment can peak at part load and degrade at low and high load. To design control algorithms that exploit such behaviour in order to increase system-level efficiency, simulation models need to reflect the change in efficiency at various steady-state and dynamic operating conditions. Temporally averaging the per- formance of cycling equipment, as is customary in hourly building simulation programs, is not always satisfactory as it does not account for the high cycling frequency which can degrade the equipment perfor- mance. An example is a direct evaporating cooling coil (DX coil) where the condensate may evaporate into the supply air when the compressor is switched off (Henderson and Rengarajan 1996). In industrial research, model-based system engineer- ing is increasingly used to reduce product development cycles and to fix errors early in the design. Such a process often involves experts from different disciplines who need to integrate models of various domains to analyse their interaction or to redesign components in a way that increases system-level efficiency or controllability (Banaszuk et al. 2007). Such processes require models that can be used beyond time-domain simulation, for example in conjunction with frequency domain analysis (to analyse stability and design beneficial dynamic behaviour) or with optimization algorithms (to optimize the design or operation). Using building simulation programs for such applications leads to new requirements for modelling and simulation tools. For example, to support the invention of new systems for space conditioning, building simulation programs need to allow a scientist to quickly add new models and use the models within rapid prototyping processes. For multidisciplinary research, it needs to be possible to integrate different models that have been developed concurrently by different domain experts who are part of a *Email: [email protected] Journal of Building Performance Simulation Vol. 2, No. 2, June 2009, 143–161 ISSN 1940-1493 print/ISSN 1940-1507 online The submitted manuscript has been authored by a contractor of the US Government under Contract No. DE-AC02-05CH11231. Accordingly, the US Government retains a nonexclusive royalty-free license to publish or reproduce the published form of this contribution, or allow others to do so, for US Government purposes. DOI: 10.1080/19401490902818259 http://www.informaworld.com Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Transcript of Modelica-based modelling and simulation to support ... · building simulation programs are...

Page 1: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

Modelica-based modelling and simulation to support research and developmentin building energy and control systems

Michael Wetter*

Lawrence Berkeley National Laboratory, Energy and Environmental Technologies Division, Building Technologies Program,Berkeley, CA, USA

(Received 1 December 2008; final version received 12 February 2009)

Traditional building simulation programs possess attributes that make them di!cult to use for the design andanalysis of building energy and control systems and for the support of model-based research and development ofsystems that may not already be implemented in these programs. This article presents characteristic features of suchapplications, and it shows how equation-based object-oriented modelling can meet requirements that arise in suchapplications. Next, the implementation of an open-source component model library for building energy systems ispresented. The library has been developed using the equation-based object-oriented Modelica modelling language.Technical challenges of modelling and simulating such systems are discussed. Research needs are presented to makethis technology accessible to user groups that have more stringent requirements with respect to the numericalrobustness of simulation than a research community may have. Two examples are presented in which models fromthe here described library were used. The first example describes the design of a controller for a nonlinear model of aheating coil using model reduction and frequency domain analysis. The second example describes the tuning ofcontrol parameters for a static pressure reset controller of a variable air volume flow system. The tuning has beendone by solving a non-convex optimization problem that minimizes fan energy subject to state constraints.

Keywords: building simulation; equation-based modelling; rapid prototyping; Modelica; controls

1. Introduction

To design and operate energy e!cient buildings, it isimportant to properly account for the dynamic systemperformance over a wide range of time scales andoperating conditions. At the time scale of hours todays, the system dynamics determine how much energycan be stored passively or actively to exploit naturalsources for heating and cooling. At the time scale ofminutes or even seconds, the system dynamics deter-mine whether equipment is cycling, which can nega-tively impact its energy performance and may causepremature equipment failure. Also, the performance ofcertain equipment can peak at part load and degrade atlow and high load. To design control algorithms thatexploit such behaviour in order to increase system-levele!ciency, simulation models need to reflect the changein e!ciency at various steady-state and dynamicoperating conditions. Temporally averaging the per-formance of cycling equipment, as is customary inhourly building simulation programs, is not alwayssatisfactory as it does not account for the high cyclingfrequency which can degrade the equipment perfor-mance. An example is a direct evaporating cooling coil(DX coil) where the condensate may evaporate into the

supply air when the compressor is switched o"(Henderson and Rengarajan 1996).

In industrial research, model-based system engineer-ing is increasingly used to reduce product developmentcycles and to fix errors early in the design. Such a processoften involves experts from di"erent disciplines whoneed to integrate models of various domains to analysetheir interaction or to redesign components in away thatincreases system-level e!ciency or controllability(Banaszuk et al. 2007). Such processes require modelsthat can be used beyond time-domain simulation, forexample in conjunction with frequency domain analysis(to analyse stability and design beneficial dynamicbehaviour) or with optimization algorithms (to optimizethe design or operation).

Using building simulation programs for suchapplications leads to new requirements for modellingand simulation tools. For example, to support theinvention of new systems for space conditioning,building simulation programs need to allow a scientistto quickly add new models and use the models withinrapid prototyping processes. For multidisciplinaryresearch, it needs to be possible to integrate di"erentmodels that have been developed concurrently bydi"erent domain experts who are part of a

*Email: [email protected]

Journal of Building Performance SimulationVol. 2, No. 2, June 2009, 143–161

ISSN 1940-1493 print/ISSN 1940-1507 onlineThe submitted manuscript has been authored by a contractor of the US Government under Contract No. DE-AC02-05CH11231. Accordingly, the US Governmentretains a nonexclusive royalty-free license to publish or reproduce the published form of this contribution, or allow others to do so, for US Government purposes.DOI: 10.1080/19401490902818259http://www.informaworld.com

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 2: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

multidisciplinary research team. For controls designand analysis, building simulation programs need torepresent the dynamic behaviour of components andtheir interaction within a system. For generating asimulation model of an HVAC system and its controlsfrom a Building Information Model, building simula-tion programs should be able to represent any HVACand controls configuration that can be built in reality.This would allow using any valid Building InformationModel that contains not only building envelope databut that may in the future also contain data for HVACcomponents, their system configuration and thespecification of control algorithms.

We recognize that vendors may not release theperformance data and control algorithms at a level ofdetail needed for a proper simulation of the dynamicsystem performance. In such situations, one can stilluse the pragmatic approach of implementing simplifiedequipment performance curves and control algorithmswith equation-based modelling languages, using thescarce information available, as is frequently done intoday’s building simulation programs.

2. Traditional building simulation programs

To better distinguish the modelling and simulationtechnique described in this article from the way thatbuilding simulation programs are typically written, weintroduce the term traditional building simulationprograms. By traditional building simulation pro-grams, we mean building simulation programs thatare written using an imperative language, such asFORTRAN, C and C!!. Examples of traditionalbuilding simulation programs include DOE-2, ESP-rand EnergyPlus (Winkelmann et al. 1993, Clarke 2001,Crawley et al. 2001). In such programs, a developerwrites sequences of computer instructions that assignvalues to variables in a predefined order of execution.Typically, such programs mix code that describes thephysical process with code for data management andfor numerical solution methods.

Traditional building simulation programs have ingeneral not been designed based on the aboverequirements. Meeting these requirements requiresmodelling techniques that are di"erent from thetechniques used in these programs, in which thesemantic gap between simulation model and actualcomponent can be large and which often mix code forexpressing the physical behaviour with code for datamanagement and numerical solution methods. Areason for this semantic gap is that models intraditional building simulation programs are writtenin a way that was motivated by how computers processinstructions. For example, when implementing aphysical model, a program developer sorts and

manipulates the physical equations based on whatvariables are known (the input) and what variablesneed to be computed (the output). Then, the programdeveloper writes causal, sorted variable assignmentsand implements them in a source code. This sourcecode may call other program procedures, therebytransferring the locus of control until the response of asubsystem to its input variables is computed. Duringthis process, program procedures may set flags torequest from the solver the re-simulation of asubsystem. Clearly, this is not how one would statethe physical laws that govern constraints betweencomponent interface variables and how one woulddescribe how components interact with each other.Rather, it was the only approach for writing buildingsimulation programs at a time when more moderntools for modelling, symbolic algebra, numericalsolution and code generation were in their infancy.

3. Limitations of traditional building simulationprograms

In traditional building simulation programs, componentmodels frequently integrate their own numerical solverand mix program flow logic with equations that simulatethe physical behaviour. This leads to a program code thatis hard tomaintain and for which it is di!cult to add newmodels. The nested solvers can also lead to significantnumerical noise in the simulation results that can makethe use of optimization programs di!cult (Wetter andWright 2004,Wetter and Polak 2004b). Furthermore, thelack of separation between models, data and solversmakes it hard to integrate models from di"erentdisciplines for co-simulation such as in Trcka et al.(2006, 2007) and Wetter and Haves (2008). Because themajority of building simulation programs do not modelthe dynamics of HVAC systems and sometimes imple-ment an idealized controller directly in a componentmodel,many standard control sequences such as the onesdescribed by ASHRAE (2005) and CIBSE (2000) aredi!cult if not impossible to model. For example, inEnergyPlus, fan coil units are controlled based on thezone heating and cooling load and not based on a zonethermostat. This makes it hard to use such models inconjunction with models of control systems.

As part load performance and system controlsbecome of increasing importance in very low energybuildings, energy simulations need to properly resolvethe nonlinear dynamic behaviour of building energyand their control systems, and capture the dominantdynamics that may lead to equipment short-cycling.When developing models for such systems, one obtainssystems of di"erential equations where the timeconstants can vary significantly among di"erentcomponents. These systems of di"erential equations

144 M. Wetter

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 3: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

may be coupled to algebraic equations and todi"erence equations. For the e!cient numerical solu-tion of such systems, algorithms for symbolic compu-ter algebra (such as partitioning and tearing) andimplicit numerical solvers for di"erential equationsshould be used (Cellier and Kofman 2006).

With respect to composing HVAC systems fromcomponent models, we note that in some traditionalbuilding simulation programs, the arrangement ofHVAC and control components is governed bycomposition rules (that define how components canbe assembled to form a system) which are not devisedbased on how actual HVAC components can beconnected to form a system. Rather, the compositionrules were defined such that an e!cient numericalsolution could be obtained in a program architecturethat distributes solvers to individual components andsubsystems and that does not make use of symbolicmanipulations. This led to program architectures withsequential simulation of loads, systems and plants, orto program architectures that are based on fluid loops.The consequence is that translating an HVAC systemfrom a Building Information Model to an energysimulation program is only possible if the HVACsystem instantiation in the BIM has been done suchthat the component connectivity conforms to thecomposition rules of the energy simulation program.This is, for example, followed in the approachdescribed by Bazjanac and Maile (2004). Althoughthis approach may present a working solution fortraditional HVAC systems and controls, it presents achallenge for the use of BIM for non-standard HVACsystems and to represent novel control algorithms.

4. Building system library

Because of these limitations, we started an open-sourcedevelopment of a new component library for buildingenergy systems using the equation-based object-oriented modelling language Modelica (Mattsson andElmqvist 1997). For early applications, we are primar-ily interested in:

. o"ering innovative companies and researchers aplatform to stimulate innovations in energy-e!cient building systems;

. enabling virtual rapid prototyping to evaluatedi"erent concepts rapidly so that promisingalternatives can be identified for further refine-ment and product development;

. enabling researchers to quickly add models ofemerging technologies into the simulation envir-onment to do performance assessment; and

. enabling controls engineers to extract di"erentsubsystem models from models that are used for

the design of the building energy system. Thesemodels may then be used within a feedbackcontrols design process, or they may be em-bedded within building control systems formodel-based controls, fault detection anddiagnostics.

In the long term, we envision the models being usedin a work flow that automatically generates asimulation model from a BIM that includes amodular definition of HVAC systems and controlalgorithms.

Modelica has been applied earlier for buildingenergy modelling applications but an extensive librarywith both steady-state and dynamic component modelsfor building energy systems is not yet available. OtherModelica development has been reported by Merz(2002) and Felgner et al. (2002) who describe thelibrary ATPlus for thermal building simulation. Hohet al. (2005) expanded the components of the ATPluslibrary to include a room model with heat exchangersthat are embedded in wall constructions. Nytsch-Geusen et al. (2005) developed a hygrothermalbuilding model as part of a Modelica library formultizone building heat and mass transfer analysis. Amulti-zone thermal building model is described inWetter (2006b) and a multizone airflow model isdescribed in Wetter (2006a).

4.1. Characteristics of the target applications

To further illustrate why we are interested in a newapproach for modelling and simulation of buildingsystems, and to rationalize our selected implementa-tion, we will now discuss some characteristics of theabove applications:

4.1.1. E!cient numerical solution

To discuss the computation time, consider theequation

seconds

program" instructions

program

! "clocks

instruction

! "seconds

clocks

! "

#1$

that describes the time needed to execute a program asthe product of the number of instructions of theprogram, times the average clock cycles needed toprocess an instruction, times the seconds that elapseper clock cycle. As application developers, we caninfluence the first two terms on the right-hand side,whereas the third is given by the processor clock.

The instructions to be executed by the programcan be reduced by selecting e!cient symbolic and

Journal of Building Performance Simulation 145

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 4: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

numerical algorithms and a good software structure.With regard to numerical algorithms, we note that inbuilding energy systems, time constants vary betweenseconds for feedback control to days for energy storage.To ensure stability, to control the error of the numericalsolution and for computational e!ciency, solving suchsystems requires implicit integration algorithms withadaptive step sizes (Hairer and Wanner 1996, Cellierand Kofman 2006). This, in turn, can lead to largelinear and nonlinear systems of equations that need tobe solved simultaneously. Since the computation time oflinear and nonlinear solvers is typically proportional ton2 to n3, where n denotes the number of unknowns thatare solved for simultaneously, it is generally advanta-geous to reduce n. For equation-based languages, thiscan be done by symbolically manipulating the system ofequations using methods such as partitioning, tearingand inline integration (Elmqvist et al. 1995, Bunus andFritzson 2004, Cellier and Kofman 2006), which aresimilar to the methods used in SPARK (Sowell et al.1986, Sowell and Haves 2001, Wetter et al. 2008).However, traditional building simulation programs useimperative programming, such as procedural code, thatdefines the sequences of computer instructions asopposed to only the logic of the computation as adeclarative language would do.1 This imperative modelformulation does not allow the use of the abovesymbolic manipulations.

The number of cycles it takes to process aninstruction can be reduced by using algorithms thattake advantage of parallel hardware. Exploitingparallelism in hardware becomes increasingly impor-tant because the third term on the right-hand side isnot expected to decrease significantly in the future(Asanovic et al. 2006). Increasing parallelism is there-fore the primary method of reducing the computingtime. Taking advantage of this technological develop-ment requires changes in the software architecture inorder to implement libraries that exploit parallelism,such as the ones described by Vuduc et al. (2005). Italso requires adding parallelization constructs tohigher level code. The fact that the seconds/clock arenot decreasing much but instead the hardware isbecoming increasingly parallel has far reaching con-sequences for the software community (see, forexample, Asanovic et al. (2006)). Taking advantageof these technological changes is easiest if programs aredesigned such that they separate concerns for modelformulation, symbolic processing, data managementand numerical solution. This allows using highlye!cient libraries for computational kernels (i.e. com-putational tasks that are common to many applica-tions such as solvers for linear systems of equations)that can be updated with few changes to the applica-tion program as the hardware changes and the state of

the art in the scientific computing community ad-vances. It is questionable that traditional buildingsimulation programs, which contain hundreds ofthousands of lines of code and whose softwarearchitecture has not been designed for parallelcomputation, can take e"ective advantage of thisdevelopment.

4.1.2. Management of complexity

The flat model representation that can typically befound in today’s building simulation programs is notwell suited to manage the complexity of large systemmodels. Instead, a modelling language should allow forthe management of the complexity of building systemmodels by providing means for composing systemmodels hierarchically (to encapsulate subsystem mod-els), for object-inheritance (to reuse existing basicmodels and refine their implementation), for object-instantiation (to use and parameterize an object in asimulation model) and for polymorphism (to changethe model semantics based on the environment that themodel is exposed to). There should also be a capabilitythat allows a model builder to assemble system modelsas one would connect components in an actual system,with acausal connections that link model ports thatcarry physical quantities such as mass flow rate, speciesconcentration, pressure and temperature. Theserequirements are part of the object-oriented modellingparadigm that is described by Cellier (1996) andrealized in the Modelica language.

4.1.3. Simulation of dynamic e"ects

Time domain simulation of equipment that switches onand o" by averaging its performance over a fixed timestep can lead to incorrect prediction of the equipmentperformance. For example, a DX coil that short-cyclesat high frequency has a lower latent heat capacitycompared to the same coil that cycles at lowerfrequency because the water film that deposits on thecoil can evaporate into the supply air stream when thecompressor is switched o" (Henderson and Rengar-ajan 1996). Furthermore, models that time-average thedynamic performance are not applicable for analysingthe robustness and dynamic performance of feedbackcontrol loops. Time-averaging the dynamics also limitsthe use of models in operation for model-basedcontrols, fault detection and diagnostics.

4.1.4. Use of models beyond time domainsimulation

Models can serve more applications than just timedomain simulation. For example, control theory for

146 M. Wetter

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 5: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

linear time invariant systems provides a rich frame-work for systems of the form

_x#t$ " Ax#t$ ! Bu#t$; #2a$

y#t$ " Cx#t$ !Du#t$; #2b$

where A, B, C and D are matrices with constantcoe!cients, x(%) is the state vector, u(%) is the controlinput vector and y(%) is the output vector. In Section4.6.1 we show how such theory can be used inconjunction with a nonlinear Modelica model for aheat exchanger to design a controller.

4.1.5. Use of models in conjunction with optimizationalgorithms

To prove convergence of optimization algorithms to astationary point, the cost function needs to be oncecontinuously di"erentiable. There is a large class ofoptimization algorithms, some of which do not requireknowledge of the gradient, that can be used toe!ciently solve such problems (Polak 1997, Koldaet al. 2003, Polak and Wetter 2006). It is generallyaccepted in the optimization community that at leastfor the final iterates, the simulations need to be donewith high enough accuracy of the numerical solvers tomake the numerical noise in the cost functionnegligible. This has been shown to be di!cult withbuilding simulation programs that have several solversspread throughout their code, often without giving theuser the means to use tight solver tolerance (Wetterand Polak 2004b, Wetter and Wright 2004) or toadaptively adjust them during the simulation to reducethe computation time such as in Wetter and Polak(2004a).

4.1.6. Generation of a simulation model from a BIM

We envision using a Building Information Model togenerate a model that can be used for energy simulationfrom a component-based BIM representation of thebuilding, its HVAC system and its control system. Toaccomplish this, it seems to be most natural toencapsulate models for simulation in the same way ascomponents are delivered to a building. Furthermore,the rules that describe how component models can beconnected to each other to form a system model shouldbe as close as possible to the rules that describe howactual components can be connected to each other.

In view of these characteristics, we suggest revisit-ing the current approach of writing building simulationprograms. Instead of writing programs that describehow a building energy system should be simulated, i.e.

in what sequence equations are evaluated, howvariables are propagated from one routine to anotherand how equations are being solved, one should writemodels that define the algebraic and dynamic relation-ships between their interface variables, and composesystem models hierarchically. How to generate acomputer code for simulation from these systems ofequations should be left to software that manipulatesthe equations symbolically and links them to numericalsolvers. Clearly, this poses formidable challenges tosymbolic and numerical solvers. It is the subject of theresearch described here to explore a model formulationthat allows robust and e!cient numerical simulations,and to identify research and development needs tomake equation-based modelling accessible to a largercommunity than simulation specialists.

4.2. Implementation

To implement our modelling library we selected theModelica language. Modelica is a free open-sourcelanguage for object-oriented equation-based modellingof systems that are described by di"erential, di"erenceand algebraic equations. Its broad support in manyindustrial domains positions it well to become the de-facto standard for modelling of dynamic systems.Thus, we believe it has the potential to become alanguage that allows exchanging models among usersof di"erent engineering domains, including buildingtechnologies, that may use di"erent modelling andsimulation environments, similar to what wasattempted by Sahlin and Sowell (1989) with theNeutral Model Format language.2 We note thatequation-based modelling and simulation was intro-duced to the building simulation community close totwo decades ago (Sowell et al. 1986, Sahlin and Sowell1989, Charlesworth et al. 1991, Klein and Alvarado1992). What is di"erent from earlier e"orts is thatModelica is supported by various industrial sectorswhich broadens the resources available to develop thelanguage and the modelling and simulation environ-ments. In addition, there have been various advancesin symbolic and numerical methods as well as incomputer science and computer hardware that makethe approach more feasible today.

Before discussing the architecture of our library, wepresent a brief overview of Modelica and refer for anin-depth discussion to Mattsson and Elmqvist (1997),Tiller (2001) and Fritzson (2004). In 1996, a con-sortium was formed to develop the Modelica language.The goal of the consortium is to combine the benefitsof existing modelling languages and to define a newuniform language for model representation by creatinga modelling language that allows modelling systemsthat involve multiple engineering domains such as

Journal of Building Performance Simulation 147

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 6: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

electrical engineering, thermodynamics, heat transfer,fluid dynamics and controls (Fritzson and Engelson1998). Modelica is an equation-based, acausal, object-oriented modelling language that is designed forcomponent-oriented modelling of dynamic systems.Models are described by di"erential equations, alge-braic equations and discrete equations. Using standar-dized interfaces, the mathematical relations of a modelbetween its interface variables are encapsulated, andthe model can be represented graphically by an icon.This encapsulation together with the standardizedinterface variables facilitate model reuse, modelexchange and connecting component models tosystem models using a graphical or textual editor.Since Modelica is a standardized language, it is apromising choice for ensuring that models canindeed be shared and exchanged by a large usercommunity.

A tenet of Modelica is that each component shouldrepresent a physical device with physical interfaceports. For ports of opaque heat conductors, interfacevariables are heat flow and temperature, and for anelement that transports a fluid, the port variables arepressure, species flow and enthalpy. This encapsulationtogether with acausal models enables a graphical,input–output free model construction. In a schematicmodel diagram of a physical system, icons correspondto actual components or subsystems and encapsulatethe equations that define the physics of the subsystem.Lines between the icons impose interface equations toconserve flow and to equate state variables, or theymay propagate signals in a control system.

Models can be encapsulated hierarchically. Thisfacilitates managing the complexity of large systems,reusing subsystem models and testing of subsystemmodels before they are assembled into a large systemmodel that may be di!cult to debug. To reducethe model development time, the object-oriented modelconstruction in Modelica allows experts of di"erentdomains, such as an HVAC engineer and a controlsengineer, to model their respective process, and laterinterface the models to analyse the complete system.This e"ectively allows concurrent, as opposed tosequential, model building.

Modelica libraries for multi-domain physics(http://www.modelica.org/libraries/) include modelsfor control systems, for thermal systems, for electricalsystems and for mechanical systems, as well as for fluidsystems and di"erent media (Elmqvist et al. 2003,Casella et al. 2006). Because the libraries usestandardized interfaces, models from di"erent librariescan be used within the same system model. An exampleof such a standardized interface is the HeatPortconnector of the Modelica Standard Library whichdefines a connector with temperature and heat flow.

It is implemented by the following lines of Modelicacode:

1 partial connector2 Modelica.Thermal.HeatTransfer.3 Interfaces.HeatPort4 ’’Thermal port for 1-D heat5 transfer’’;6 SI.Temperature T7 ’’Port temperature’’;8 flow SI.HeatFlowRate Q_flow9 ’’Heat flow rate (positive if

10 flowing into the component)’’;11 end HeatPort;

On line 8, the type prefix flow declares that all variablesconnected to Q_flow need to sum to zero. For example,if two HeatPorts are connected, the relationshipT1 " T2 and the conservation equation_Qflow;1 ! _Qflow;2 " 0 are generated. This connectorcan then be instantiated to define the interface in aone-dimensional heat transfer element with no energystorage. In Modelica’s thermal library, such a heattransfer element is implemented as

1 partial model Element1D2 ’’Partial heat transfer element3 with two HeatPort connectors4 that does not store energy’’5 SI.HeatFlowRate Q_flow ‘‘Heat flow6 rate from port_a ! port_b’’;7 SI.Temperature dT ‘‘port_a.T-8 port_b.T’’;9 public

10 HeatPort port_a;11 HeatPort port_b;12 equation13 dT " port_a.T – port_b.T;14 port_a.Q_flow " Q_flow;15 port_b.Q_flow " 7Q_flow;16 end Element1D;

Lines 5 to 8 contain the declaration of the variables _Qand DT that are typically computed in a one-dimensional heat transfer element. Lines 10 and 11instantiate the HeatPort connector to expose to theoutside of this model the port temperatures port_a.Tand port_b.T, as well as the port heat flow ratesport_a.Q_flow and port_b.Q_flow. The equationson lines 13 to 15 define the relationships between thevariables of the two HeatPort connectors and thevariables of the partial model Element1D. Note thatElement1D does not declare a relation between theheat flow rate and the temperatures, as this relation isdi"erent for conduction, convection or radiation.

148 M. Wetter

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 7: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

Because this relation is not specified, the model isdeclared partial to indicate that it can be extendedby other models to refine its implementation, but thatit cannot be instantiated as it does not define itssemantic. To implement a thermal conductor, theabove partial model can be extended as follows:

1 model ThermalConductor2 ‘‘Lumped thermal element3 transporting heat without storing it’’4 extends Interfaces.Element1D;5 parameter SI.ThermalConductance G6 ‘‘Constant thermal conductance’’;7 equation8 Q_flow " G*dT;9 end ThermalConductor;

This thermal conductor model can then be encapsulatedin a graphical icon using drawing elements that are partof the language standard, and hence, can be interpretedby di"erent Modelica modelling environments. By usinga di"erent parameter declaration on line 5 and adi"erent equation on line 8, the semantics can bechanged to represent other one-dimensional heattransfer elements such as a model for long-waveradiation between two surfaces. Note that the abovecode is not pseudo-code, but rather a completeimplementation of a heat conductor in the Modelicalanguage. (For simplicity, optional graphical annota-tions that can be interpreted by a graphical model editorand optional model documentation in html format havebeen omitted.) Here, a model developer only declaredthe variables and the constraints between heat flow rateand temperatures. Whether the model will solve for theheat flow rate or for a port temperature will bedetermined by a code generator that analyses the overallsimulation model in order to determine a numericallye!cient sequence of computations.

Modelica is a language that defines models but itcannot be executed directly. To create executable code,a Modelica simulation environment translates aModelica model to a programming language such asC and links it to numerical solvers. See, for example,Cellier and Kofman (2006) for a description ofalgorithms that are typically used in such a process.

The Software Component Model that is embodiedin the Modelica language enables a flexible reuse ofmodels. The Software Component Model consists ofcomponents, a connection mechanism and a componentframework (Fritzson 2004). Components are connectedusing Modelica’s connection mechanism. This can bevisualized in connection diagrams. The componentframework realizes components and connections andensures that communication works over the

connections. Connectors can contain physical variablessuch as temperature and heat flow rate, which aretypically implemented using acausal variables. They canalso contain signals such as a control input which aretypically implemented using causal variables, or theycan be composite and involve causal and acausalvariables. There are several connectors defined in theModelica Standard Library, and the design is such thatall independent variables that are necessary to define thedesired e"ects in a real interface are part of a connector.

The Software Component Model that is embodiedin Modelica allows connecting models as one wouldconnect real components with each other. Therefore, ifmodels are encapsulated the same way as componentsare encapsulated in a Building Information Model, aone-to-one translation between a BIM and an energysimulation model can be done. With many of today’sbuilding simulation programs, this is not possiblebecause building simulation programs impose rules forhow component models can be connected to form asystem model, and these rules are typically morerestrictive than how actual components can beconnected to form an HVAC system. An example ofsuch a situation is shown in Figure 1. The figureillustrates a cooling and ventilation system in whichcomponents are connected in a way that cannot bedirectly represented in the EnergyPlus whole buildingsimulation program. The left-hand side of the figureshows the schematic view of the actual system in whichthe room return air flows through an economizer andthen into a double-skin facade from which it isexhausted to the outside by the exhaust air fan. Theright-hand side of the figure shows the schematic viewof the model with the modifications that were neededto simulate it in EnergyPlus. In particular, anadditional economizer had to be added, and theexhaust air fan had to be placed in the supply airstream. This was needed as EnergyPlus does not allow

Figure 1. Schematic view of an HVAC system with exhaustair through a double-skin facade (left-hand side) andimplementation in the EnergyPlus whole building simulationprogram (right-hand side).

Journal of Building Performance Simulation 149

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 8: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

connecting two thermal zones, one for the room andone for the double-skin facade, with a flow path thatcontains the economizer. Although an expert modellermay be able to make such modelling decisions, itwould be impractical to write a BIM translator thatallows such special HVAC system configurations.However, in modular modelling languages such asModelica, a direct implementation of the actual systemis possible as components can be connected in any wayas long as the port variables are compatible.

4.3. Base class for library

In Modelica, there are currently two implementationsfor fluid flow models: the package Modelica.Thermal.FluidHeatFlow of the Modelica StandardLibrary and the package Modelica_Fluid (Casellaet al. 2006). The latter is intended to become part of theModelica Standard Library.

The package Modelica.Thermal.FluidHeat-Flow has been developed under the assumption thatthe mixture concentration remains constant, that themedium does not change phase and that the mediumproperties are constant. For many building HVACapplications, these assumptions are too restrictivesince, for example, change in air humidity or pollutantconcentration is often of interest. The packageModelica_Fluid is not based on these assumptions.Instead, models in the package Modelica_Fluidinstantiate a medium model that provides standardizedvariables and interfaces to medium property functionssuch as for density or viscosity. Medium models canrange in their fidelity from single-phase, single-substance, constant property media to detailed multi-phase, multi-substance media such as air with water inliquid and vapour phase, depending on the watervapour and saturation pressure. Since componentmodels are implemented separately from the mediummodels, the same component models can be used fordi"erent media. Because of this flexibility, our libraryis based on the package Modelica_Fluid. A goal ofModelica_Fluid is that every component can beconnected in an arbitrary way, and components suchas pipes can be reversed without a"ecting theperformance of the simulation model.

Modelica_Fluid is still under development, butit already provides a set of component models for one-dimensional thermo-fluid flow in pipe networks.However, the models are not meant to cover allapplication areas but rather serve as examples for howto implement additional components. In our library,we used some of the same base classes, reused certainmodels and added additional models that are morespecifically targeted towards building HVAC systemmodelling and simulation. For example, while

Modelica_Fluid provides spatially discretized heatexchanger models with detailed models for fluid flowfriction and convective heat transfer coe!cients, weimplemented additional heat exchanger models thatare more applicable for modelling and simulation ofbuilding HVAC systems during early design when littledetailed component data are available.

4.4. Buildings library packages

We organized our Buildings library into thepackages listed below. Additional packages includingmodels that link during the simulation to the BuildingControls Virtual Test Bed (Wetter and Haves 2008), andhence to EnergyPlus, will be added later. The library isavailable from http://simulationresearch.lbl.gov.

BaseClassesThis package contains base classesthat are used by several models of this library suchas a basic icon that may be extended by a model toprovide a uniformgraphicalmodel representation.Note that other packages may have their own sub-package BaseClasses that may provide basicmodels that are used within the correspondingpackage only. For example, the package Fluidshas a package Fluids. BaseClasses thatprovides a model for a flow resistance that isusedby afixedflow resistancemodel andby a valvemodel.Controls This package contains models ofcontinuous time and discrete time controllers.Fluids This package contains models for fluidflow components such as fixed flow resistances,two- and three-way valves with various openingcharacteristics, air dampers and fans. There arealso models for thermal energy storage tanks,furnaces and measurement sensors.Fluids.HeatExchangers Models in thispackage include various heat exchanger modelsincluding steady-state heat exchangers with fixede"ectiveness, dynamic heat exchangers that arediscretized along the two flow paths and a simpleheater or cooler whose heat transfer rate isproportional to a control input. There are alsomodels for cooling towers.Fluids. MassExchangers This package con-tains a model for a humidifier and a heat andmoisture exchanger.HeatTransfer This package contains modelsfor heat transfer elements such as a finite volumemethod for heat conduction in solids.Media This package contains media models thatcan be used in addition to the models provided byModelica.Media. Our models are in general lessdetailed to reduce simulation time. For example,

150 M. Wetter

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 9: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

the package contains a model for moist air withconstant specific heat capacity of air and watervapour, and models for dry and moist air with asimplified implementation of the gas law. There isalso a model for water with constant density.Utilities This package provides utility classesthat are used by models in several packages. Forexample, there are psychrometric models. Thereare also models that facilitate writing results tooutput files to augment the output capabilitiesprovided by the simulation environment and bythe Modelica Standard Library. In addition, thispackage contains functions that approximatesome non-di"erentiable functions by approxima-tions that are di"erentiable everywhere andwhose derivatives are continuous. Such functionsmay be used by a model developer to increasenumerical e!ciency.

4.5. Technical di!culties

The formulation of dynamical systems using equation-based languages typically leads to large sparse systemsof hybrid di"erential algebraic equations.3 A directsolution of these systems is not practical. Instead, thefollowing steps are typically involved to create acomputationally e!cient simulation program:

(1) The user constructs the model equations usinga graphical editor, a textual editor, or a modelgenerator.

(2) State variables are selected and the equationsare symbolically manipulated to reduce highindex di"erential algebraic equation systems.

(3) Block lower triangulation and tearing are usedto reduce the dimensionality of the linear andnonlinear system of equations.

(4) Program code is generated, compiled and linkedto libraries that contain numerical solvers.

(5) The hybrid di"erential algebraic equationsystems are solved to find consistent initialconditions.

(6) The equations are integrated over time.

Steps (2) to (6) can be done automatically without userintervention for simple systems, but they may requireuser intervention for more complex building energysystem models. In step (1), a model builder makes thedecision of what physical phenomena are to beincluded in the model. Here, the level of modellingdetail is selected based on the process that should beinvestigated and the availability, or uncertainty, of theprocess input data. To guide an algorithm in step (2), amodel builder can give hints to a symbolic processor toselect state variables and/or to tear equation systems.

For example, for a thermodynamic state, eithertemperature or enthalpy may be used as a statevariable, but selecting temperature may lead to non-linear equations that need to be solved numerically,while enthalpy may be expressed as an explicit functionof temperature. Such hints may be embedded in amodel library. On the basis of our experience, forbuilding energy and control systems, step (5) can bechallenging. Here, a user can give guess values to aidthe numerical solver in finding consistent initialconditions. Finding proper settings can in some casesrequire trial and error even for experienced users.

The need for providing good initial guessescurrently presents a risk for making equation-based,component-oriented modelling available to a large userbase that is not trained in these skills. It also presents arisk to use this technology in conjunction with codegenerators that may, for example, process a BIM togenerate a simulation model for performance assess-ment, or to use such programs during the operation ofthe building when they need to run unattended.Possible risk mitigation includes advances in symbolicand numerical methods, embedding good guess valuesin model libraries, and further research in howmodels should be formulated to ensure fast androbust numerical simulation. With respect to robustnumerical simulation, the current redesign of theModelica_Fluid library shows promising initialresults. Since version 1.0 of Modelica_Fluid, thelibrary has a new implementation for handling flowreversal in flow networks. The new implementation leadsin flow networks to residual equations that are contin-uous and often di"erentiable. In the past, these equationswere often discontinuous in the iteration variables whichfrequently caused numerical problems. While furtherexperiments on large and realistic benchmarks are stillpending, the initial experiments show significant improve-ments over the previous implementation in terms of theiranalytical properties (smoothness of the nonlinear systemof equations), and in terms of their numerical perfor-mance in computing consistent initial conditions andintegrating the equations in time.

We note that solvers in traditional buildingsimulation programs often fail to converge too. Acommon practice in such cases is to freeze the iterationvariable, accept the non-convergent solution andproceed to the next time step. However, as pointedout above, this can cause large numerical noise thatcan lead to incorrect results when analysis techniquesare used that require smoothness of the simulationresult with respect to input data, such as a sensitivityanalysis for identifying important parameters or non-linear programming for optimization.

Advances are also needed to translate run-timeexceptions into a language that can be understood by

Journal of Building Performance Simulation 151

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 10: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

the model user who may not have a background innumerical methods. Furthermore, diagnostics meth-ods, or expert systems, may be developed that guide auser in finding a better model configuration.

In summary, there are quite a few interesting openresearch problems in the field of equation-based model-ling for building systems. We believe that the benefits offurther progress in this area would be substantial asequation-based modelling enables many new applica-tions, it facilitates integration of models from di"erentengineering domains, it allows broadening the develop-ment e"ort for modelling and simulation environmentsacross di"erent disciplines, and it allows modelling at ahigher level of abstraction that is closer to how a humantypically describes an engineering problem.

4.6. Applications

We will now present examples in which we determinedcontrol parameters using frequency domain analysisand optimization. The models were constructed usingcomponent models of the above described ModelicaBuildings library, version 4.0.0, with Modelica_-Fluid 1.0 Beta 2 and the Modelica StandardLibrary 2.2.1. To build, simulate and linearize thesystem models, we used the Linux version of theModelica modeling and simulation environment Dy-mola 6.0b (Bruck et al. 2002). For the frequencydomain analysis, we used MATLAB1 2008a with theControl System ToolboxTM (Mathworks 2008). Theoptimization was done using GenOpt1 2.1.0 (Wetter2004).

4.6.1. Controls design using root locus

The root locus technique is a commonly used controlsdesign method for linear time invariant (LTI) systems.The root locus shows the location of the poles and zerosof the characteristic equation 1 ! k G(s) " 0 for avarying control gain k 2 [0,?), where G(s) is the openloop transfer function. We will now show the use of thistechnique to design a controller for a heating coil.

Figure 2 shows the Modelica model of the open-loop system. The circles are boundary conditions withconstant pressure and temperature. Their parametersare such that the water flow direction is from the modelsou_1 to sin_1 and the air flow direction is fromsou_2 to sin_2. The control input u is equal to thelift of a valve whose relationship between valve lift andvolume flow rate is linear (at a constant pressuredi"erence). The control objective was to track a setpoint for the heat exchanger air outlet temperature.The dynamic response of the outlet temperature sensorwas modelled using a linear first order di"erentialequation. The heat exchanger was a finite volume

model with heat capacities for the water in the tubes,for the tube metal wall and for the air. Each pipe wasdiscretized along its water flow path, and the air wasdiscretized along its flow path with an element for eachintersection of the air flow path with a pipe. Theconvective heat transfer coe!cient on the water side wasa function of the water mass flow rate, whereas the air-side convective heat transfer coe!cient was heldconstant as we did not vary the air flow rate in thisexample. The valve was sized such that its authority was0.5. For the closed loop model, we used a proportionalcontroller. The closed loop model defined a di"erentialalgebraic equation system with 2593 variables. It wascomposed of 405 component models (that wereprimarily used to define the heat exchanger model).There were a total of 36 state variables for the coilmodel and one state variable for the dynamics of thetemperature sensor at the coil air outlet. The biggestcoupled nonlinear system of equations was an 8 6 8system, which was reduced to a set of scalar equationsby the symbolic processor which also found analyticexpressions for all elements of the Jacobian matrices.

The closed loop system exhibited oscillatorybehaviour for large values of the proportional gainKp and large steady-state errors for small values. Thus,our objective was to find the value of Kp that givessmall steady-state error and non-oscillatory behaviour.

As the plant was nonlinear, we followed thefollowing design procedure:

(1) Bring the open loop system to di"erent steady-state conditions, and linearize the open loopresponse around these steady-state conditions.This yields, for each linearization, an LTImodel of the form _x " Ax!Bu, y " Cx!Du,with 37 state variables.

(2) For each LTI model, compute a reduced ordermodel, _~x " ~A ~x! ~Bu; y " ~C ~x! ~Du that hassimilar response to the original LTI model but

Figure 2. Open loop model for the heating coil.

152 M. Wetter

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 11: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

is better suited for controls design than the highorder model.

(3) For each reduced order model, design acontroller (that is applicable locally becausethe model is linearized) and then design acontrol law that is applicable for the wholerange of operating conditions.

(4) Test the controller on the original nonlinearmodel. If the control performance is unsatis-factory, repeat the previous step.

For step (1), we used the Dymola program to bring theplant to steady-state conditions for a small and largevalve opening. In particular, we set u " 0.05 andu " 0.95, respectively, simulated the open loop plantuntil it reached steady state, and then called thelinearization command of Dymola that extracts anLTI model around the current operating point. Thus,rather than implementing a linearized model thatwould be valid only locally, we implemented anonlinear model, let it reach two di"erent operatingpoints that were of interest, and then called alinearization command of the simulation environment.The linearization command conducted an inputperturbation and reinitialization of state variables as

needed during the perturbation to compute a linearapproximation to the original model.

For step (2), we imported the LTI model intoMATLAB and computed the Hankel singularvaluesfsig37i"1. The first few Hankel singular valueswere si " {29.29, 2.2997, 0.3334, 0.2778, . . .} foru " 0.05 and si " {14.48, 1.687, 0.5090, 0.0217, . . .}for u " 0.95. As the fourth values contributed little tothe response, we computed 3rd order reduced ordermodels for both values of u. Figure 3 compares theBode plots and step responses for the full order andthe reduced order models. The figures show that thereduced order models were a good fit.

Next, for step (3), we used the root locus techniqueto select control gains for each reduced order model.Figure 4 shows the root locus for both reduced ordermodels. From the root locus, we obtained the polesand their damping ratios z for di"erent proportionalgains Kp as listed in Table 1. The data show that forKp & 2 there is little damping at low valve lift.

For step (4), we simulated the original nonlinearsystem in Dymola for Kp " 1 and Kp " 2. The steady-state error was 0.06K for Kp " 1. For Kp " 2, weobserved oscillatory behaviour at low valve lift. Thus,we selected a linear gain schedule such that Kp(u"

Figure 3. Bode plots and step responses for full order models (with 37 states) and reduced order models (with 3 states). The toprow is for u " 0.05 and the bottom row for u " 0.95.

Journal of Building Performance Simulation 153

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 12: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

0.05) " 1 and Kp(u" 0.95) " 2. This linear gainschedule resulted in the step response shown inFigure 5, with a steady-state error below 0.4K. Toreduce the valve oscillation after the step signal att " 30 min would require a reduction in Kp and hencewould lead to a larger steady-state error. Thus, if thetransient response in Figure 5 is not acceptable, thenthe proportional controller would have to be replaced,for example, by a proportional-integral controller.

4.6.2. Precommissioning of a fan static pressure resetcontroller for a Variable Air Volume flow system

For Variable Air Volume (VAV) flow systems withdirect digital control to the zone level, the CaliforniaTitle 24 Energy Code requires supply pressure reset byzone demand (CEC 2005). A control logic that is usedby major control vendors is the Trim and Responselogic (Taylor 2007). This control logic may beimplemented as follows. If the supply fan is on, acentral controller samples the VAV damper positions

every 2 min. If no damper is close to fully open, thepressure set point is decreased by 10 Pascals; else it isincreased by 15 Pascals. When the fan switches o", theset point is set to 125 Pascals.

Since the default parameters for the pressureadjustment will work well only for few systems, a trialand error tuning is almost always required duringcommissioning (Taylor 2007). During commissioning,

Table 1. Damping ratio z for both reduced order modelsfor di"erent proportional gains Kp. The row z (u " 0.05) isfor the reduced order model that approximates the plant foru " 0.05.

Kp 0.13 0.5 1 2 5

z(u " 0.05) 0.5 0.23 0.096 0.048 unstablez(u " 0.95) 0.5 0.28 0.19 0.13 0.07

Figure 4. Root locus plot for the reduced order models. The red solid locus corresponds to the system linearized at u " 0.05and the blue dashed locus is for u " 0.95.

Figure 5. Closed loop step response with gain schedulingsuch that Kp(u" 0.05) " 1 and KP(u" 0.95) " 2. The topfigure is the actuator input, and the bottom figure is thetemperature measured at the coil outlet.

154 M. Wetter

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 13: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

the engineer adjusts pressure increments and decre-ments until the system is stable.

We will now perform this procedure using aModelica model that we linked to the GenOptoptimization program to find appropriate settingsthat may be used as a starting point during acommissioning process. For this example, we createda Modelica implementation of the VAV system modeldescribed in ASHRAE 825-RP (Haves et al. 1996).Unlike the model used by Haves et al. (1996), ourmodel also includes equations for the CO2 concentra-tion, in addition to equations for enthalpy (ortemperature), pressure and mass flow rate. We alsoadded models of completely mixed air volumes tomodel the CO2 storage in the room air and in thereturn air plenum. Figure 6 shows the system model inModelica. On top are the controllers for thestatic pressure reset and the fan frequency drives.The blue circles on the left are ambient conditions,which are connected to an outside air mixing box.There are also flow resistances for the ducts and thesupply and return fans. On the right is a system modelthat encapsulates the supply ducts, the return ductsand the six rooms.

Figure 7 shows the implementation of the roommodels. Each room has an individual VAV damperwith nonlinear characteristics between opening angleand flow rate. The model with label vav contains theVAV damper and a flow resistance that has beenparameterized to account for the duct and di"userresistance. This model is connected to an instanta-neously mixed room volume which is labeled vol.Counterclockwise, this room volume model is con-nected to a model for the room leakage to the exterior

(with label lea), to a port that allows connectingdi"erent rooms with each other (using a flow resistanceto separate adjacent rooms), to a CO2 emission model(its input is the number of people), and to anothermixed air volume that models the CO2 concentrationin the exhaust air plenum. Next, there is another portthat is used to connect the room volume to anotherroom to its right and to a CO2 sensor. The CO2 sensoris connected to a model that converts mass fraction tovolume fraction. Its output is connected to a propor-tional controller with saturation. The controller outputis connected to a model for the actuator motor, whichhas a finite travel speed and a hysteresis that causes itto adjust the damper position only if the position errorexceeds a threshold. This configuration is used for eachof the six rooms.

The six rooms are then connected with each otherusing a pressure drop element to model interzonal airexchange, and they are connected to an air distributionsystem for the supply and return duct. This subsystemmodel is then encapsulated into the icon with label rooin Figure 6 and connected to the plant model to formthe overall system model.

In the system model, all air mass flow rates arecomputed based on the flow friction and the fan curvethat relates fan volume flow rate with fan pressure raisefor the given number of revolutions which is determinedby a model for the fan frequency controller. The totalsystem model contained 730 simulation componentsthat led to a di"erential algebraic equation system with4420 scalar equations and 40 state variables. Somemodels triggered time events (e.g. for discrete timecontrols) or state events (e.g. for the hysteresis of thedamper position adjustment). The computation time to

Figure 6. Implementation of VAV system model in Modelica.

Journal of Building Performance Simulation 155

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 14: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

Figure 7. Implementation of the room models in Modelica.

simulate one day was about 10 min. One of the mainreasons for the large computation time was the discretetime control that led to time events, and themotormodelof the VAV damper that triggered state events due to itshysteresis model. In total, there were 1440 time eventsand 5172 state events. The time integration step size,which is adaptive, was never enlarged to more than 30 s,most likely due to the events. Thus, while this systemmodel is applicable for controls analysis, one wouldhardly use such a level of modelling detail for an annualsimulation. Rather, one may replace the discrete timecontrol with continuous time control to reduce the timeevent, neglect the hysteresis of the motor to eliminatestate events, and introduce a transport delay in thecentral plant’s supply and return duct to break a 50dimensional nonlinear equation system that solves forpressure and mass flow rates into three smaller equationsystems with dimensions 9, 15 and 21. When weimplemented these changes (in a more recent modelthat was based on Modelica_Fluid version 1.0,release candidate 1), the computation time was reducedby a factor of 50, and the numerical solver was able toenlarge the integration step size to amaximum of 1100 s.

To simplify the example, we assumed that thermalconditioning and ventilation were provided by separatesystems. Thus, the one control objective was to maintaina CO2 concentration in each room of 700PPM above theoutside air concentration by regulating the room VAV

dampers, and tominimize the fan static pressure using theTrim and Response logic. We assumed a fixed outside airdamper position of u " 0.5, an occupant density of up to0.15 person per m2 floor area, which varied over the dayfor each zone individually. A CO2 emission rate perperson of 8.18%1076 kg/s (" 15dm3/h CO2 emission perperson) was used (Lochau 1989). The VAV boxes arepressure dependent, i.e., their flow rate changes if thedi"erence between inlet and room static pressure changes.Each room has a continuous-time proportional controllerthat tracks the room CO2 concentration. Figure 8a showsthe time response of the system with base case controllersettings as listed in Table 2. The figure shows that duringthe occupied hours, there was a frequent change in ductstatic pressure (bottom figure) which caused an oscilla-tory behaviour of the VAV dampers (middle figure).

Next, to avoid the oscillatory VAV actuatormovement, we adjusted the sampling time ts, thepressure increment dpi and decrement dpd of the Trimand Response algorithm. We note that because of thenonlinearity of fan power consumption with respect toduct static pressure set point, on a temporal average,an oscillatory duct static pressure setpoint causes moreflow friction compared to a stable control, and henceleads to a larger fan energy use. Thus, instead of amanual trial and error procedure to find values for ts,dpi and dpe that lead to a stable control, we usedoptimization to find the value for x "D #ts; dpi; dpe$ thatminimizes the fan energy use, subject to a constraint

156 M. Wetter

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 15: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

Figure 8. CO2 concentrations above outside air concentration in the six rooms (with the set point shown in black), VAVdamper positions and duct static pressure for the base case and for the control settings obtained using optimization.

on the room CO2 concentration. In particular, wesolved

min x2Xf f#x$ j g#x$ " 0g; #3$

where

f#x$ " 1

E0

Z T

0Pf #x; t$ dt #4$

is the normalized fan energy use, X is the feasible setthat imposes upper and lower bounds for theindependent variables, T " 1 day is the simulationperiod and Pf (%,%) is the sum of the supply and returnfan power consumption. The term E0 "

R T0 Pf #x0; t$dt

is the fan energy consumption at the initial iterate x0. Itis used to normalize the cost function which willfacilitate the scaling of the constraint function g(%). Theconstraint function g: R3!R ensures that the CO2 setpoint in the rooms is not exceeded, except for apossible user-specified number of extreme zones inwhich the CO2 may not be tracked. Because we

configured the Trim and Response logic so that atleast three rooms require an increase in static pressurebefore the fan static pressure set point is increased, wedefined the constraint function as

g#x$ " 1

T

Z T

0#maxf0; #yj#x; t$=xs$ ' 1=#2Kp$

' 1 j j 2 J#x; t$g$2 dt; #5$

where J(% , %) is the index set of all VAV dampersexcept the two with the biggest set point violation,yj (% , %) is the measured room CO2 concentration,xs " 700 PPM is the CO2 set point (above the outsideair concentration) and Kp " 10 is the proportionalgain of the P controller for the room air dampers. Theterm 1/(2Kp) is used to account for the steady-stateerror associated with proportional controllers.

To compute a solution for (3), we solved thesequence of optimization problems

Pk min x2Xyk#x$; #6$

Journal of Building Performance Simulation 157

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 16: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

where yk(%), for k2N, is the optimality function,defined as yk#x$ "

Df#x$ ! k4 g#x$ for k2N4. We solved

(6) for k2 {1,2,3,4}, using the GenOpt optimizationprogram. Parametric studies showed that f(%) is non-convex and may have local minima. We also note thatf(%) is non-di"erentiable because of the state-eventsand time-events. Therefore, we used GenOpt’s ParticleSwarm Optimization algorithm PSOCCMesh,which is a global optimization algorithm for non-di"erentiable cost functions. We will denote by x* thebest iterate found when solving Pk and by x0 the initialiterate.

In addition to doing the optimization, we alsotested how robust the optimal parameter settings arewith respect to changes in the CO2 emission profiles.For this robustness test, for each room we changed thetime profiles and their magnitude. For the new set ofprofiles, we conducted two simulations, one with theinitial iterate x0 and one with x* which was obtainedwhen solving the optimization problem (6) with theoriginal set of CO2 emission profiles. Thus, x* need notbe optimal for the new set of CO2 emission profiles, butour objective is to see if x* also leads to goodperformance under this new set of CO2 emissionprofiles. The performance indices were f(%), as definedin (4), and the normalized distance s(%) travelled by theactuators of all VAV dampers during the simulationperiod.

Table 2 lists the initial values and the final values ofthe optimization, together with the results of theoptimization and the robustness test. For both CO2

emission profiles, the optimized parameter settingsreduced the fan energy consumption by 3% to 4% andthe distance s(%) by about 14%. For the modified set ofCO2 emission profiles, the fan energy was significantlysmaller because less CO2 was emitted. Figure 8 alsoshows that the optimized parameter settings x* led to

fewer oscillations of the VAV dampers because of aless aggressive re-adjustment of the static pressure setpoint. The CO2 concentrations are, however, stillmaintained within the acceptable limit, i.e., g(x) " 0for all four simulations. There is a steady-state controlerror between 18:00 and 22:00, as shown in Figure 8,because during this time period, the fan is still on (as itis operated on a timer) while all VAV boxes are closed.

5. Conclusions

We showed that equation-based object-oriented mod-elling allows analysing problems that are beyond thecapabilities of traditional building simulation pro-grams. Compared to earlier e"orts to establishequation-based object-oriented modelling in the build-ing simulation community, we believe that the devel-opment of Modelica, which is supported across manyengineering domains, provides an opportunity torevive the e"ort of establishing more modular andflexible modelling and simulation techniques forbuilding energy and control systems. As Modelica isan open-source language for which several commercialand open-source modelling and simulation environ-ments are both existing and emerging, it provides anopen environment for collaboration and modelexchange.

Although there are many challenges to be over-come, we believe that equation-based object-orientedmodelling allows the field of building simulation toprogress towards the next generation of tools. Such aprogression is similar to the developments in computerscience in which the level of abstraction at whichprograms are formulated increased from machinelanguage to symbolic assembler, to macro processors,to high-level procedural languages (such as FOR-TRAN) and further to object-oriented languages(Shaw and Garlan 1996). It would be rather surprisingif the field of building simulation were to stagnate atprocedural languages that frequently led to largemonolithic simulation programs, which are hard tomaintain and for which adding new models andanalysis features is a significant time investment. Amore flexible modelling environment also has thepotential to better support design processes that reducecost and development time, such as model-basedsystem-level design, in which systems are expressed atan increasingly higher level of abstraction to allow adesigner to focus on the system architecture ratherthan its details of implementation (Sangiovanni-Vincentelli 2007).

However, further research and development isneeded to make available equation-based object-oriented modelling and simulation to a larger audiencefor whom debugging non-convergent models is not an

Table 2. Base case and results of the control parameteroptimization.

original CO2

profilemodified CO2

profile

basecase, x0

optimum,x*

basecase, x0

optimum,x*

sampling timets in [s]

120 220 120 220

pressure incrementdi in [Pa]

15 5 15 5

pressure decrementdd in [Pa]

710 720 710 720

fan energy use f(x) 1 0.966 0.642 0.614constraint

violation g(x)0 0 0 0

distance s(x) 1 0.853 0.816 0.702

158 M. Wetter

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 17: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

option. Such research and development is part of thefuture work on the Modelica-based library for buildingenergy and control systems described here.

To further disseminate equation-based object-oriented modelling and simulation to the buildingsimulation community, the question, however, is nothow to get existing users to adapt to a new technology,but rather how to better integrate modelling into rapidprototyping for inventing new building systems, andinto the design and operation of buildings. Newtechnologies are seldom introduced by forcing achange onto existing users, but rather through theenabling of processes that add value for the user andthat were not possible before.

Nomenclature

Conventions

(1) Elements of a set or a sequence are denoted bysubscripts.

(2) f(%) denotes a function where (%) stands for theundesignated variables. f(x) denotes the valueof f(%) for the argument x. f: A!B indicates thatthe domain of f(%) is in the space A, and that theimage of f(%) is in the space B.

(3) We say that a function f: Rn!R is oncecontinuously di"erentiable if f(%) is defined onRn, and if f(%) has a continuous derivative on Rn.

Symbols

f(%) cost functiong(%) constraint functionyk(%) optimality function, for k 2 NKp proportional gainG(s) open loop transfer functiont timeu control signalx independent parameterxk iterate of the optimization algorithm, for k2Nx* best iterate found by the optimization algorithmy measurement signals Hankel singular values of the linearized systemz damping ratioa2A a is an element of AN {0,1,2,. . .}R set of real numbers"D equal by definition

Acknowledgements

This research was supported by the Assistant Secretary forEnergy E!ciency and Renewable Energy, O!ce of BuildingTechnologies of the US Department of Energy, underContract No. DE-AC02-05CH11231. The author would

like to thank Scott A. Borto" at the United TechnologiesResearch Center for his input to the controls design exampleand Philip Haves, Brian A. Co"ey and Walter F. Buhl, all atthe Lawrence Berkeley National Laboratory, as well as theanonymous reviewers, for their valuable feedback to themanuscript.

Notes

1. For example, the statement Q1:"-Q27Q3; isimperative and describes that Q1 is to be computed byassigning the sum of -Q2 and -Q3. A declarativestatement may have the form 0 " Q1!Q2!Q3;which only describes how the three variablesare related, but it does not specify what computerinstructions need to be done to compute one from theother two.

2. Within the ASHRAE Technical Committee 4.7, theprospect of Modelica was already mentioned in 1998when Sowell reported on this language. The committeereported that Modelica could eventually subsume NMFbut it was decided to press for NMF and monitor theModelica progress (Spitler 1998).

3. By hybrid di"erential algebraic systems of equations,we mean di"erential and di"erence equations that arecoupled to continuous and discrete algebraic equations.An example is a chiller control that may be expressed asa state machine that is linked to a discrete timecontroller for a mechanically cooled building, whichmay be described by di"erential and algebraicequations.

4. The term k4 adds a penalty to f(%), if constraints areviolated, that is increasing in k, for k2N.

References

Asanovic, K., et al., 2006. The landscape of parallel computingresearch: a view from Berkeley. Technical report UCB/EECS-2006-183. Berkeley: EECS Department, Univer-sity of California.

ASHRAE, 2005. Sequences of operation for common HVAC/Systems. Atlanta, GA. ISBN 1-931862-98-2.

Banaszuk, A., Mehta, P.G., and Hagen, G., 2007. The role ofcontrol in design: from fixing problems to the design ofdynamics. Control Engineering Practice, 15 (10), 1292–1305.

Bazjanac, V. and Maile, T., 2004. IFC HVAC interface toEnergyPlus – a case of expanded interoperability forenergy simulation. In: Proceedings of SimBuild 2004,Aug, Boulder, CO.

Bruck, D., et al., 2002. Dymola for multi-engineeringmodeling and simulation. In: M. Otter, ed. Proceedingsof the 2nd Modelica conference, Mar, Oberpfa"enhofen,Germany. 55–1–55–8.

Bunus, P. and Fritzson, P., 2004. Automated static analysisof equation-based components. Simulation, 80 (7–8),321–345.

Casella, F., et al., 2006. The Modelica fluid andmedia library for modeling of incompressible andcompressible thermo-fluid pipe networks. In: C. Kraland A. Haumer, eds. Proceedings of the 5-th InternationalModelica Conference, Vol. 2, Sep, Vienna, Austria, 631–640.

CEC, 2005. Building energy e!ciency standards, nonresiden-tial compliance manual. Sacramento, CA.

Journal of Building Performance Simulation 159

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 18: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

Cellier, F.E., 1996. Object-oriented modeling: means fordealing with system complexity. In: Proceedings 15thBenelux Systems and Control Conference, Mierlo, TheNetherlands, 53–64.

Cellier, F.E. and Kofman, E., 2006. Continuous systemsimulation. New York: Springer.

Charlesworth, P., et al., 1991. The energy kernel system. In:J.A. Clarke, J.W. Mitchell, and R.C.V. de Perre, eds.Proceedings of the IBPSA Conference, Aug, Nice, France.

CIBSE, 2000. Building control systems, CIBSE Guide H.London: Butterworth-Heinemann.

Clarke, J.A., 2001. Energy simulation in building design. 2nded. Oxford, UK: Butterworth-Heinemann.

Crawley, D.B., et al., 2001. EnergyPlus: creating a new-generation building energy simulation program. Energyand Buildings, 33 (4), 443–457.

Elmqvist, H., Otter, M., and Cellier, F., 1995. Inlineintegration: a new mixed symbolic/numeric approachfor solving di"erential– algebraic equation systems. In:Keynote Address, Proceedings. ESM095, Jun, Prague,CzechRepublic, xxiii–xxxiv.

Elmqvist, H., Tummescheit, H., and Otter, M., 2003. Object-oriented modeling of thermo-fluid systems. In: P.Fritzson, ed. Proceedings of the 3rd Modelica conference,Nov, Linkoping, Sweden, 269–286.

Felgner,F.,et al., 2002.Simulationof thermalbuildingbehaviourinModelica. In:M.Otter, ed.Proceedingsof the2ndModelicaconference, Mar, Oberpfa"enhofen, Germany, 147–154.

Fritzson, P., 2004. Principles of object-oriented modeling andsimulation with Modelica 2.1. Piscataway, NJ: Wiley.

Fritzson, P. and Engelson, V., 1998. Modelica – a unifiedobject-oriented language for system modeling andsimulation. Lecture Notes in Computer Science, 1445.

Hairer, E. and Wanner, G., 1996. Solving ordinary di"erentialequations. II. 2nd Springer series in computationalmathematics. Berlin: Springer-Verlag.

Haves, P., et al., 1996. A standard simulation testbed for theevaluation of control algorithms & strategies. Final Report825-RP, ASHRAE, Atlanta, GA.

Henderson, H. and Rengarajan, K., 1996. A model to predictthe latent capacity of air conditioners and heat pumps atpart- load conditions with constant fan operation.ASHRAE Transactions, 102 (1), 266–274.

Hoh, A., et al., 2005. A combined thermo-hydraulicapproach to simulation of active building componentsapplying Modelica. In: G. Schmitz, ed. Proceedings of the4th Modelica conference, Mar, Hamburg, Germany.

Klein, S.A. and Alvarado, F.L., 1992. Engineering equationsolver (EES).

Kolda, T.G., Lewis, R.M., and Torczon, V., 2003.Optimization by direct search: new perspectives onsome classical and modern methods. SIAM Review, 45(3), 385–482.

Lochau, R., 1989. Physiologische Grundlagen. In: W. Leiner,H. Schedwill, G. Seng, and W. Stabler, eds.Handbuch derKlimatechnik, Vol. 1. Karlsruhe, Germany: Verlag C.F.Muller GmbH, 93.

Mathworks, 2008. Control System Toolbox 8.2, Natick, MA.Mattsson, S.E. and Elmqvist, H., 1997. Modelica – an

international e"ort to design the next generation model-ing language. In: L. Boullart, M. Loccufier, and S.E.Mattsson, eds. 7th IFAC Symposium on Computer AidedControl Systems Design, Apr, Gent, Belgium.

Merz, R.M., 2002. Objektorientierte modellierung thermischenGebaudeverhaltens. Thesis (PhD). UniversitatKaiserslautern.

Nytsch-Geusen, C., et al., 2005. A hygrothermalbuilding model based on the object-oriented modelinglanguage Modelica. In: I. Beausoleil-Morrison and M.Bernier, eds. Proceedings of the Ninth InternationalIBPSA Conference, Vol. 1, Aug, Montreal, Canada.867–876.

Polak, E., 1997. Optimization, algorithms and consistentapproximations. Applied Mathematical SciencesVol. 124. New York: Springer Verlag.

Polak, E. and Wetter, M., 2006. Precision control forgeneralized pattern search algorithms with adaptiveprecision function evaluations. SIAM Journal on Opti-mization, 16 (3), 650–669.

Sahlin, P. and Sowell, E.F., 1989. A neutral format forbuilding simulation models. In: Proceedings of the SecondInternational IBPSA Conference, Jun, Vancouver, BC,Canada, 147–154.

Sangiovanni-Vincentelli, A., 2007. Quo Vadis, SLD?Reasoning about the trends and challenges ofsystem level design. Proceedings of the IEEE, 95 (3),467–506.

Shaw, M. and Garlan, D., 1996. Software architecture:perspectives on an emerging discipline. New Jersey:Prentice Hall.

Sowell, E.F., et al., 1986. A prototype object-based system forHVAC simulation. Technical report LBL-22106, Lawr-ence Berkeley National Laboratory.

Sowell, E.F. and Haves, P., 2001. E!cient solution strategiesfor building energy system simulation. Energy andBuildings, 33 (4), 309–317.

Spitler, J.D., 1998. ASHRAE TC 4.7 Minutes.Taylor, S.T., 2007. VAV system static pressure setpoint reset.

ASHRAE Journal, 24–32.Tiller, M.M., 2001. Introduction to physical modeling with

Modelica. Norwell, MA: Kluwer Academic Publisher.Trcka, M., Hensen, J.L.M., and Wijsman, A.J.T.M., 2006.

Distributed building performance simulation - a novelapproach to overcome legacy code limitations. ASHRAEHVAC&R, 12 (3a), 621–640.

Trcka, M., Wetter, M., and Hensen, J., 2007. Comparison ofco-simulation approaches for building and HVAC/RSimulation. In: J. Yi, Z. Yingxin, Y. Xudong, and L.Xianting, eds. Proceedings of the 10-th IBPSAConference, Beijing.

Vuduc, R., Demmel, J.W., and Yelick, K.A., 2005. OSKI: Alibrary of automatically tuned sparse matrix kernels.Journal of Physics: Conference Series, 16, 521–530.

Wetter, M., 2004. GenOpt, generic optimization program, UserManual, Version 2.0.0. Technical report LBNL-54199.Berkeley, CA, USA: Lawrence Berkeley NationalLaboratory.

Wetter, M., 2006a. Multizone airflow model in Modelica. In: C.Kral and A. Haumer, eds. Proceedings of the 5th Interna-tional Modelica Conference, Vol. 2, Sep, Vienna, Austria,431–440.

Wetter, M., 2006b. Multizone building model for thermalbuilding simulation in Modelica. In: C. Kral and A.Haumer, eds. Proceedings of the 5th InternationalModelica Conference, Vol. 2, Sep, Vienna, Austria,517–526.

Wetter, M. and Haves, P., 2008. A modular building controlsvirtual test bed for the integration of heterogeneoussystems. In: Proceedings of SimBuild, Aug, Berkeley, CA.

Wetter, M., et al., 2008. Using SPARK as a solver forModelica. In: Proceedings of SimBuild, Aug, Berkeley,CA.

160 M. Wetter

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009

Page 19: Modelica-based modelling and simulation to support ... · building simulation programs are typically written, we introduce the term traditional building simulation programs. By traditional

Wetter, M. and Polak, E., 2004a. Building designoptimization using a convergent pattern search algorithmwith adaptive precision simulations.Energy andBuildings, 37(6), 603–612.

Wetter, M. and Polak, E., 2004b. A convergent optimizationmethod using pattern search algorithms with adaptiveprecision simulation. Building Services EngineeringResearch and Technology, 25 (4), 327–338.

Wetter, M. and Wright, J., 2004. A comparison ofdeterministic and probabilistic optimization algorithmsfor nonsmooth simulation-based optimization. Buildingand Environment, 39 (8), 989–999.

Winkelmann, F.C., et al., 1993. DOE-2 Supplement, Version2.1E. Technical report LBL-34947, Lawrence BerkeleyNational Laboratory, Berkeley, CA, USA.

Journal of Building Performance Simulation 161

Downloaded By: [ETH-Bibliothek] At: 19:46 19 October 2009