Sei sulla pagina 1di 356

R.

Scott Cooper
The Designers Guide to
Analog & Mixed-Signal Modeling
Illustrated with VHDL-AMS and MAST

Copyright Notice
Copyright 2004 Synopsys, Inc. All rights reserved. Permission is granted to reproduce and distribute
complete copies of this book solely for non-commercial purposes. Any such copies must maintain the
trademark and copyright notices contained herein.
Destination Control Statement
All technical data contained in this publication is subject to the export control laws of the United
States of America. Disclosure to nationals of other countries contrary to United States law is
prohibited. It is the readers responsibility to determine the applicable regulations and to comply with
them.
Disclaimer
SYNOPSYS, INC., AND ITS LICENSORS MAKE NO WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, WITH REGARD TO THIS MATERIAL, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.
Registered Trademarks ()
Synopsys, Saber are registered trademarks of Synopsys, Inc.


Dedications
To Lori , Kendra, and R.J.
for putti ng up wi th the l ong hours and l ate ni ghts,
I thank you very much...
To Ron Ei cher and the Lockheed-Mar ti n I nerti al Gui dance Lab team
fi rst and most for teachi ng me how to be a desi gn engi neer,
and al so for i ntroduci ng me to the wor l d of si mul ati on.
Thank you!



Table of Contents
Table of Contents .............................................................................................................................. 5
Preface ............................................................................................................................................. 13
Chapter 1. The Promise of MSHDLs ............................................................................................ 1
1.1. Why MSHDLs? .................................................................................................................. 1
1.2. About VHDL-AMS and MAST ......................................................................................... 1
1.3. Who Can Benefit From MSHDLs? .................................................................................... 2
A. IC Designers .................................................................................................................. 3
B. ASIC Library Developers .............................................................................................. 3
C. ASIC Library Users ....................................................................................................... 3
D. Board Designers............................................................................................................. 3
E. System Designers ........................................................................................................... 4
1.4. Why Create Your Own Models?......................................................................................... 4
A. Vendors Dont Have All Models ................................................................................... 4
B. Structural (Macro-) Modeling has Limitations .............................................................. 4
C. Designers Get the Best of Both Worlds ......................................................................... 5
Chapter 2. Time-Domain Simulation ............................................................................................ 7
2.1. Systems of Equations.......................................................................................................... 7
2.2. Digital Computer Simulation.............................................................................................. 8
2.3. Linear Algebraic Equations .............................................................................................. 10
A. Linear Algebraic Example........................................................................................... 10
2.4. Linear Differential-Algebraic Equations .......................................................................... 13
A. Numerical Integration.................................................................................................. 14
6 Contents

B. Linear DAE Example................................................................................................... 15
2.5. Nonlinear Algebraic Equations......................................................................................... 19
A. Newton-Raphson Method............................................................................................ 19
B. Linearizing the Characteristic Equations ..................................................................... 24
C. Nonlinear Algebraic Example...................................................................................... 26
2.6. Nonlinear Differential-Algebraic Equations..................................................................... 29
A. Predictors and Correctors............................................................................................. 29
B. Nonlinear DAE Example ............................................................................................. 31
2.7. Chapter Summary ............................................................................................................. 35
Chapter 3. VHDL-AMS Overview ............................................................................................. 37
3.1. VHDL-AMS Model Terminology .................................................................................... 37
3.2. VHDL-AMS Modeling Options ....................................................................................... 38
A. Parameterizing Existing Models.................................................................................. 38
B. Structural Modeling (Macromodeling) ........................................................................ 39
C. Behavioral Modeling.................................................................................................... 43
D. VHDL-AMS Solvability Conditions ........................................................................... 46
3.3. AMS-Extensions for VHDL............................................................................................. 46
3.4. Constants and Generics..................................................................................................... 49
3.5. Test Benches ..................................................................................................................... 51
3.6. VHDL-AMS Model Listing Conventions ........................................................................ 52
3.7. Chapter Summary ............................................................................................................. 52
Chapter 4. MAST Overview ....................................................................................................... 53
4.1. MAST Model Terminology .............................................................................................. 53
4.2. MAST Modeling Options ................................................................................................. 54
A. Parameterizing Existing Models.................................................................................. 54
B. Macromodeling (Structural Modeling) ........................................................................ 56
C. Behavioral Modeling.................................................................................................... 61
D. MAST Solvability Conditions ..................................................................................... 63
4.3. MAST Structure and Conventions.................................................................................... 63
A. MAST Conventions and Syntax .................................................................................. 63
Contents 7


B. General MAST Template Structure ............................................................................. 65
4.4. Test Circuits ...................................................................................................................... 69
4.5. Chapter Summary ............................................................................................................. 69
Chapter 5. Introduction to Conserved System Modeling ............................................................ 71
5.1. Simulation Models............................................................................................................ 71
A. Across and Through Variables..................................................................................... 71
B. Conservation Laws....................................................................................................... 72
5.2. Defining the Model ........................................................................................................... 72
5.3. Electrical Building BlocksIdeal .................................................................................... 73
A. Constant Current Source.............................................................................................. 73
B. Constant Voltage Source .............................................................................................. 74
C. Linear Resistor ............................................................................................................. 76
D. Linear Capacitor .......................................................................................................... 77
E. Linear Inductor............................................................................................................. 78
F. Voltage-Controlled Current Source (VCCS) ................................................................ 80
G. Behavioral Op AmpIdeal ......................................................................................... 81
5.4. Electrical Building BlocksNon-Ideal............................................................................ 86
A. Resistor with Temperature Dependency...................................................................... 86
B. Capacitor with ESR and Leakage ................................................................................ 88
C. Behavioral Op Amp with Input/Output Characteristics............................................... 89
5.5. Chapter Summary ............................................................................................................. 93
Chapter 6. Developing User-Friendly Models ............................................................................ 95
6.1. Bullet-Proofing Techniques .............................................................................................. 95
A. Example: Linear Resistor............................................................................................. 96
B. Example: Behavioral Op Amp...................................................................................100
6.2. Overcoming Numerical Limitations ............................................................................... 109
A. Solution 1 - Create "Design-Dependent" Components.............................................. 110
B. Solution 2 - Normalize Argument Values .................................................................. 110
6.3. Making Models Characterizable..................................................................................... 112
8 Contents

A. Characterization Approaches..................................................................................... 112
6.4. Making Models Readable with Functions ...................................................................... 113
6.5. Chapter Summary ........................................................................................................... 116
Chapter 7. Advanced Modeling Concepts ................................................................................ 117
7.1. Piecewise Linear Modeling ............................................................................................ 117
A. Voltage Limiter .......................................................................................................... 117
B. Ideal Diode................................................................................................................. 120
7.2. Time-Dependent Modeling............................................................................................. 121
A. Exponential Waveform Source .................................................................................. 122
B. Pulse Waveform Source ............................................................................................. 124
C. Sinusoidal Waveform Source..................................................................................... 129
7.3. Foreign Subroutines........................................................................................................ 134
A. Foreign Subroutines with VHDL-AMS..................................................................... 135
B. Foreign Subroutines with MAST ..............................................................................136
7.4. Chapter Summary ........................................................................................................... 140
Chapter 8. Signal Flow (Non-Conserved) Modeling ................................................................ 141
8.1. The Top-Down Design Approach...................................................................................141
8.2. Characteristics of Signal Flow Models........................................................................... 144
8.3. Signal Flow Modeling in the Time Domain ................................................................... 144
A. Gain Block................................................................................................................. 145
B. Two-Input Summer ....................................................................................................146
C. Differentiator.............................................................................................................. 147
D. Double Differentiator................................................................................................. 148
E. Integrator .................................................................................................................... 149
F. Lead-Lag Compensator .............................................................................................. 150
G. Limiter Function......................................................................................................... 152
8.4. Signal Flow Modeling in the Frequency Domain........................................................... 154
A. Two Pole Filter........................................................................................................... 155
B. General Purpose 2nd Order Filter ..............................................................................157
Contents 9


8.5. Chapter Summary ........................................................................................................... 159
Chapter 9. Mixed-Signal Modeling ........................................................................................... 161
9.1. Solving Continuous and Discrete Systems ..................................................................... 162
9.2. Analog to Digital Modeling Techniques......................................................................... 164
A. Detect Analog Thresholds .........................................................................................164
B. Schedule Digital Events............................................................................................. 166
C. Analog to Digital Model Examples ........................................................................... 166
9.3. Digital to Analog Modeling Techniques......................................................................... 180
A. Detect Digital Events................................................................................................. 180
B. Synchronize Digital and Analog Signals ................................................................... 181
C. Provide Continuous Transitions for Analog Signals.................................................. 182
D. Digital to Analog Model Examples ........................................................................... 184
9.4. Connecting Analog and Digital Models ......................................................................... 192
A. Interface Models ........................................................................................................ 192
B. Example - A/D Interface Model................................................................................. 193
C. Example - D/A Interface Model................................................................................. 198
9.5. Chapter Summary ........................................................................................................... 201
Chapter 10. Sampled Data Modeling .......................................................................................... 203
10.1. Characteristics of Sampled Data Models...................................................................... 203
10.2. Z-Domain Building-Block Models............................................................................... 204
A. Sample/Hold (analog to z-domain)............................................................................ 204
B. Linear Combination ................................................................................................... 207
C. Delay.......................................................................................................................... 209
10.3. Transforming From S-domain to Z-Domain................................................................. 212
A. Transforming a Lowpass Filter.................................................................................. 212
B. Creating Difference Equations...................................................................................214
C. Creating the Simulation Models ................................................................................ 215
10.4. Chapter Summary ......................................................................................................... 219
Chapter 11. Hydraulic and Mechanical Modeling ...................................................................... 221
10 Contents

11.1. ABS System.................................................................................................................. 221
11.2. Hydraulic System Operation and Models ..................................................................... 222
A. Fluid Chamber ........................................................................................................... 225
B. Spring Acting Extend Actuator.................................................................................. 229
C. Accumulator............................................................................................................... 232
D. 2-Way Hydraulic Valve.............................................................................................. 235
11.3. Mechanical System Operation and Models ..................................................................241
A. Translational Mass ..................................................................................................... 244
B. Translational Nonlinear Spring.................................................................................. 245
C. Translational Damper................................................................................................. 247
D. Translational Hard Stop............................................................................................. 248
11.4. Mixing Technology Domains........................................................................................ 250
A. Electrical/Mechanical DC Motor............................................................................... 251
B. Mechanical/Hydraulic Pump...................................................................................... 253
11.5. Chapter Summary ......................................................................................................... 257
Chapter 12. Simulator Convergence ........................................................................................... 259
12.1. Numerical Oscillation and Divergence......................................................................... 259
A. Numerical Oscillation................................................................................................ 259
B. Numerical Divergence ............................................................................................... 260
C. Newton Damping....................................................................................................... 260
12.2. Other Convergence Problems and Solutions ................................................................ 264
A. Discontinuous Functions ........................................................................................... 264
B. Discontinuous First Derivatives................................................................................. 267
C. Zero Slope Models ..................................................................................................... 271
12.3. Debugging Models........................................................................................................ 274
A. Define Test Circuits ................................................................................................... 274
B. Use Available Debugging Utilities ............................................................................ 275
C. Use Embedded Model Messaging..............................................................................275
12.4. Chapter Summary ......................................................................................................... 277
Contents 11


Appendix A. DAE Simulator Example Solutions ..................................................................279
A.1. Linear Algebraic Equation Solutions............................................................................. 279
A. Linear Algebraic Example.........................................................................................281
A.2. Linear Differential-Algebraic Equation Solutions......................................................... 283
A. Linear DAE Example................................................................................................. 284
A.3. Nonlinear Algebraic Equation Solutions ....................................................................... 288
A. Nonlinear Algebraic Example ...................................................................................289
A.4. Nonlinear DAE Solutions .............................................................................................. 292
A. Nonlinear DAE Example........................................................................................... 292
Appendix B. MAST Supplement ........................................................................................... 301
B.1. Mathematical Functions and Expressions...................................................................... 301
A. Expressions With Operators ...................................................................................... 301
B. Mathematical Functions............................................................................................. 302
C. If Statements and Expressions ...................................................................................302
B.2. Mixed-Signal Modeling ................................................................................................. 304
A. Variable Types............................................................................................................ 304
B. When Statements........................................................................................................ 304
B.3. Simulator Variables and Functions................................................................................. 305
A. Simulator Variables (Simvars) ...................................................................................305
B. Event_on Function ..................................................................................................... 306
C. Schedule_event Function........................................................................................... 307
D. Deschedule Function.................................................................................................. 308
E. Schedule_next_time Function.................................................................................... 308
F. Threshold Function..................................................................................................... 309
B.4. Stress Analysis ............................................................................................................... 310
A. DC Motor Model Example ........................................................................................ 312
B. Built-in Bullet-Proofing Functions ............................................................................ 313
B.5. Statistical Analysis ......................................................................................................... 315
A. Statistical Resistor Model Example........................................................................... 316
12 Contents

B.6. Sample Points................................................................................................................. 317
A. Sample-Point Considerations..................................................................................... 317
B. Sample Point (and Newton Step) Specification Syntax............................................. 319
Appendix C. Glossary of Terms ............................................................................................ 321
C.1. General Terms ................................................................................................................ 321
C.2. VHDL-AMS Terms........................................................................................................ 323
Appendix D. References ........................................................................................................ 329
Appendix E. Index ................................................................................................................. 331


Preface
I will always remember my fifth year out of college. I had just been made a lead analog design
engineer in an R&D department for a large aerospace company. My first project in this role was to
determine if the existing hydraulics-based thrust-vector control (TVC) actuatorsthe steering
nozzles for heavy launch vehiclescould be replaced with all-electric actuators.
This was a daunting task to say the least. I was still learning the ropes as a design engineer, yet was
expected to build a functional proof-of-concept prototype of this new all-electric TVC actuator. I
was in over my head and I knew it. The risk of not being able to successfully complete the project
was very high, and I hoped that simulation technology could help me through the crisis.
I was using a popular SPICE-based tool for circuit simulations at the time. This tool worked great
for the majority of my projects to date, which consisted mainly of electronic filters and other analog
signal conditioning electronics.
But as I began designing and simulating pieces of the new all-electric TVC system, it became
increasingly difficult to get any real benefit from the simulatorI was having to force-fit my
design ideas into clunky and often inappropriate simulator implementations. I was modeling
mathematical functions out of collections of op amps, rather than in the software language in which
they were to be implemented on the real system; I was modeling decision-matrix functions out of
logical gates, rather than EPLD programming languages.
The models to get the job done were just not available: I needed mixed-technology models for an
induction motor, a tachometer, and a torque sensor; I needed mathematical-based models for
sinusoidal phase and coordinate frame transformers; and I needed mixed-signal models for EPLD
and microprocessor algorithm testing. My simulator did not have these models or capabilities.
It was at this juncture that I began to realize a fundamental truth: my simulator was ill-equipped to
handle real system designsparticularly mixed-signal and mixed-technology systems. It wasnt
just the lack of models, but the lack of any convenient way to develop either mixed-technology or
mixed-signal models. And there was certainly no way to simulate the TVC system along with the C
software algorithms that controlled it (which I wanted to test and debug while the system was being
built).
Then I made a wonderful discovery. I was introduced to the Saber simulator originally developed
by Analogy, Inc., now owned by Synopsys. Saber was different than my SPICE simulatorit was
based on a Mixed-Signal Hardware Description Language (MSHDL) called MAST. Saber models
were developed with a modeling language!
With MAST I enjoyed great modeling freedom. I was not only able to develop the various mathe-
matical-based models I needed, but was also able to develop mixed-signal and mixed-technology
14 Preface

models. And, much to my great surprise, I was also able to couple C algorithms into the models,
and validate actual software code prior to the prototype being built!
This is the power of MSHDLs. It is the freedom to describe models in terms that best fit the
situation. No more restrictive force-fitting of mechanical effects into the electrical domain, but total
freedom to use the actual, physical mathematics that describe the desired behaviorno matter the
technology.
And its not just physical effects. MSHDL models can be made at any level of abstractionfrom
simple transfer function s-domain descriptions, to detailed physics-based descriptions. And they
can be mixed throughout multiple levels of hierarchy!
And by the way, the project was an astounding success! The prototype was built, and it worked as
predicted by the simulator. Our company won coveted government funds to continue the project.
I have been a big believer in MSHDL-based simulation ever since.
Scott Cooper
Overview
This book is about analog and mixed-signal modeling with hardware description languages.
Models are illustrated in both the VHDL-AMS and MAST modeling languages. These two
languages were chosen for the examples because they are both heavily used in the systems arena,
and because I had hands-on access to simulators supporting them both. The SaberHDL simulator
from Synopsys was used to develop and test the VHDL-AMS models listed in this book; the Saber
simulator, also from Synopsys was used to develop and test the MAST models.
This book is not intended as a language reference for either VHDL-AMS or MAST. The focus of
the book is on modeling concepts first, and language implementations second. As dozens of VHDL
books are currently in print, standard VHDL reference material is not reproduced here, except as
needed to explain the operation of model examples. MAST reference works, on the other hand, are
not widely available. Appendix B serves as a brief MAST reference source.
This book is organized into the following chapters:
Promise of MSHDLs - This chapter gives an overview of MSHDLs. It shows the
advantages these types of non-restrictive modeling languages provide for the user.
Time-Domain Simulation - MSHDL simulators solve differential-algebraic equations.
Such simulators all have common characteristics and employ similar algorithms. This
chapter describes the process and algorithms employed by this class of simulators for
time-domain analysis.
VHDL-AMS Overview - This chapter presents a brief overview of VHDL-AMS.
Examples of parameterizing existing VHDL-AMS models are given, as well as how to
develop structural models. Behavioral modeling is also introduced, along with several
Preface 15


VHDL-AMS language features.
MAST Overview - This chapter presents a brief overview of MAST. Examples of
parameterizing existing MAST models are given, as well as how to develop macromodels.
Behavioral modeling is also introduced along with several MAST language features.
Introduction to Conserved System Modeling - Several conservation-based models are
discussed in this chapter. Both ideal and non-ideal modeling examples are given.
Developing User-Friendly Models - This chapter discusses bullet-proofing techniques
for models; how to model around common numerical limitations of simulators; making
models characterizable; and making models readable by using functions.
Advanced Modeling Concepts - Piecewise linear and time-domain modeling are
discussed in this chapter, along with how to couple subroutines written in a programming
language with VHDL-AMS or MAST models.
Signal Flow Modeling - This chapter introduces non-conserved model development.
Distinctions between non-conserved and conserved modeling are made, and the
advantages of each are discussed.
Mixed-Signal Modeling - This chapter is focused on mixed-signal models. Several
examples of mixed A to D and D to A models are given, as well as general discussions
regarding mixed-signal simulation.
Sampled Data Modeling - This chapter illustrates z-domain model development, and also
shows how to transform s-domain system descriptions into the z-domain.
Hydraulic and Mechanical Modeling - In this chapter an anti-lock brake system (ABS)
design in discussed. Several mechanical and hydraulic models which comprise this system
are detailed.
Models and Convergence - "Good modeling for convergence" guidelines are discussed
in this chapter, as well as some useful model debugging techniques.
Appendices - Detailed differential-algebraic equation (DAE) example solutions, MAST
reference, glossary of terms, suggested reading references, and a subject index are
included as appendices to the book.
Together, these chapters should give the reader a solid foundation for modeling with VHDL-AMS
and MAST.
Some readers will be interested in either VHDL-AMS or MAST, but not both. The document has
been organized so that either language can be learned independently. The overall theme of the book
16 Preface

is to introduce a modeling topic and describe it mathematically. Then separate VHDL-AMS and
MAST implementations of the model will be given.


18 Preface



chapter 1
The Promise of MSHDLs
Mixed-signal hardware description languages (MSHDLs) are powerful tools with which systems
and circuits of virtually any complexity can be modeled for simulation. Not only mixed-signal
systems, but mixed-technology systems can be modeled as well.
The range of applications resulting from this capability is astounding. From ICs to ASICs to
electronic board-level designs to hierarchical systems designsall can be modeled with MSHDLs,
and even simulated together as desired.
1.1. Why MSHDLs?
Mixed-signal simulation is an essential element in todays design environment. This is not just due
to the fact that most electronic systems today contain some combination of analog and digital
circuitry, but also because the size, complexity, and operating speeds of these circuits and systems
have grown tremendously over the last decade.
Rising to meet the growing needs of their users, simulator vendors have made great advances in
creating tools that are easy-to-use while still providing the accuracy essential for design analysis.
Today, mixed-signal simulators are as available as those used exclusively for analog or digital
designs, and engineers are using them routinely on a wide variety of projects.
Mixed-signal simulation has led to dramatic improvements both in design quality and in
time-to-market. Designers who are now finding mixed analog/digital circuit design increasingly
common come from a wide range of disciplines, including IC, ASIC, board, and system design.
Mixed-signal modeling languages have also been developed. The three dominating options are
MAST, and the new VHDL-AMS and Verilog-AMS languages.
1.2. About VHDL-AMS and MAST
The design objectives of both the VHDL-AMS and MAST modeling languages support the
hierarchical description and simulation of analog, digital, and mixed analog/digital systems with
conservative and non-conservative semantics. The languages support modeling of lumped systems
at a variety of abstraction levels, from system to board to chip.
2 Chapter 1The Promise of MSHDLs

Modeling is not restricted to electrical systems but also supports thermal, hydraulic, optical, and
other disciplines. Designs with mixed-technologies can be described and simulated without
restrictions, including components that span technologies like electrical/mechanical and
mechanical/hydraulic devices. Support for mixed-technology applications is particularly important
for designers that apply chips in a larger design, because experience shows that most of the errors in
such situations occur at the interfaces, either because the interfaces were not understood completely
or because they were not specified correctly.
The analog parts of these languages have a strong foundation in the theory of differential-algebraic
equations, a theory developed over the past twenty years by numerical mathematicians. This
foundation makes it unnecessary to specify how exactly a simulator must solve the equations, a
feature that gives the designer much desired flexibility to choose suitable algorithms.
This book provides numerous model examples written in both VHDL-AMS and MAST. While
many language features will be discussed, this book is not intended as either a VHDL-AMS or
MAST language referenceit is intended as a modeling reference, with examples in VHDL-AMS
and MAST. This book is also focused on analog and mixed-signal modeling (not digital modeling),
and this approach is reflected by the model examples.
1.3. Who Can Benefit From MSHDLs?
VHDL-AMS and MAST bring both immediate and long-term benefits for a designer. First, a
designer can implement a true top-down design methodology for analog and mixed-signal designs.
Experience with top-down design for digital systems has shown that this methodology improves
productivity and facilitates concurrent engineering where one subsystem is designed in one place,
and the other someplace else. Still, the subsystem can be tested as part of the whole system.
Second, since the languages remove the restrictions imposed by built-in models in many existing
tools, they open many new application areas for simulation, limited only by the languages and the
imagination of the user. The immediate benefit is that a designer can make design trade-offs across
technologies. For example, in an electronic fuel injection system, it may be more cost effective to
make a modification to the hydraulic part than to the electronic controller. The lack of such
capabilities has limited the simulation of many problems arising in industrial control.
Finally, in the long term, these languages will enable the development of new technology. If we
look at the digital world as an example, we can expect commercial products supporting the
synthesis of analog and mixed-signal devices. So far, analog synthesis has been confined to
universities, and one of its challenges has been to capture a design. Additionally, high level design
tools for analog and mixed-signal design can be expected. Finally, tools may be developed to
support the behavioral abstraction of a circuit level model.
So, who can benefit from MSHDLs?
Who Can Benefit From MSHDLs? 3


A. IC Designers
Integrated circuit designers typically create new designs based on rapidly evolving IC processes.
Existing design libraries are bypassed as process technology evolves or as new cells are required
for new applications.
The simulation models needed to support the required new libraries must fill two roles. First, they
must be able to be developed at different levels of complexity; second, they must be developed at
various levels of abstraction to support simulation from the primitive level all the way up to the
entire chip.
Due to the general movement toward mixed-signal designs, the ability to model an ever-increasing
amount of analog functionality along with digital logic circuits is essential. This trend is even more
prevalent for IC designers as digital technology approaches speed or density extremes, which
allows analog effects to crop up in otherwise pure digital designs. Often, to verify the operation of
high performance ICs, critical digital timing paths need to be represented as analog circuits or
transmission lines.
B. ASIC Library Developers
ASIC library development is similar to IC design, except that blocks of circuitry are represented by
a configurable functional cell. These cells must be represented, or modeled, as accurately as
possible so that their performance correctly maps to the underlying circuit topology.
Another requirement is fast model simulation, so large chip simulations are practical. Hardware
description languages for both digital and analog functionality is crucial to successfully simulate
ASIC cells.
C. ASIC Library Users
ASIC library users use cells from ASIC libraries to build complete designs. Both simulation
performance and flexibility are required by these users, as well as confidence that accuracy has
been built in by the library developer.
Users rarely build their own cells, concentrating instead on the higher-level circuits containing the
predefined cells. For ASIC users, it is useful to be able to simulate the circuit or system surrounding
the ASIC in order to verify the designs performance. In this sense, the needs of ASIC users are
closer to the needs of board designers than to IC designers.
D. Board Designers
Printed circuit board designers, like ASIC library users, build circuits from available standard parts.
Given the potential complexity at the board level, optimum simulation performance is often
preferable to detailed description of internal device characteristics.
4 Chapter 1The Promise of MSHDLs

If no models are available for certain standard parts, board designers may need to develop them
from available data sheets. For simulator performance and fast modeling, a high-level method is
needed for describing components and for simulating digital together with analog characteristics.
E. System Designers
System designers need a high-level perspective of their application. A variety of signal types must
be used to represent a system accurately, which may include standard ICs, ASICs, power devices,
microprocessors, transducers, and even electromechanical devices. This level of design requires a
versatile simulation approach that can handle concurrent simulation of all the different types of
components in the system.
People have been simulating circuits for years. One of the biggest limitations to system simulation
was the unavailability of models. With the introduction of MSHDLs, designers finally have the
power to create their own models.
1.4. Why Create Your Own Models?
A. Vendors Dont Have All Models
No matter how diligently model vendors work to keep up with new devices and components the
industry produces, they always lag behind the designers need for the models. Designers often
cannot wait and must decide to quickly develop a new electronic model, or model a mechanical
effect.
B. Structural (Macro-) Modeling has Limitations
Before the advent of MSHDLs, SPICE and SPICE derivatives were the only real choice for circuit
simulation. This approach has worked well in some areas, but not so well in others. The basic
method for creating a new model in SPICE is to combine pre-existing building blocks to achieve
Why Create Your Own Models? 5


the desired functionality. Take the simplified op amp structural model (macromodel) in Figure
1.4-1:
This op amp model was created by configuring predefined resistor, capacitor, transistor, and other
building blocks to achieve the desired function. While the function can be realized in this manner, it
is rather hard to parameterize and reconfigure if needed. For example, how can we easily determine
the break frequencies f
1
and f
2
? How about the open-loop gain? Input/output resistances?
Working with this type of macromodel can be a real limitation to a circuit or systems designer who
needs a model quickly. This type of designer just wants a model that can be easily parameterized
from a databook, but there is no one-to-one correspondence between the databook parameters and
the model implementation shown in Figure 1.4-1.
An even greater limitation of macromodeling is the need for the pre-defined building blocks in the
first place. Resistor, capacitor, transistor models and the like are commonly available as building
blocks, but what if a designer needs special effects for these models like temperature dependency?
What if the designer needs, for example, a z-domain component and no core model exists at all?
How about a hydraulic or mechanical component that cannot be easily described with standard
building block components? Designers may have several critical requirements that are not possible
to model using pre-defined building blocks.
C. Designers Get the Best of Both Worlds
Perhaps the most powerful feature of MSHDLs is their flexibility. Not only can traditional
structural macromodeling approaches be used, but behavioral models can be developedand both
of these capabilities can be combined in a single model. The real power of both VHDL-AMS and
MAST is that they give the designer the power to choose the appropriate modeling approach,
whether it be a structural macromodel, a behavioral description, or a combination of the two: the
designer gets to choose the best approach to solve the problem!
Figure 1.4-1. Boyle op amp macromodel (1973 IEEE).
6 Chapter 1The Promise of MSHDLs



chapter 2
Time-Domain Simulation
Before delving into discussions on modeling, a fundamental understanding of how digital computer
simulators work should prove useful.
How do simulators perform their magic? This chapter answers this question for analog
(continuous) differential-algebraic equation (DAE) solvers. Because this is a vast subject, and this
book is focused on modeling issues, the discussion is limited to the bread and butter of analog
systems simulation: the time domain. Mixed-signal systems will be discussed in Chapter 9:
Mixed-Signal Modeling.
2.1. Systems of Equations
What exactly does a simulator do? It solves systems of equations. There are many ways of doing
this, of course, and some of the more popular methods are discussed below.
Say for example, we wish to solve the following quadratic equation:
We could solve this equation (i.e. determine which two values of x make the equation true) using
standard factoring techniques. Our result would be:
and the solutions, obtained by setting each factor equal to zero and solving for x, would be: x = -1/2
and x = -1.
This method of factoring works fine for a quadratic equation such as this. However, as the order of
the system increases there is no simple factoring technique which can be employed. The same holds
true for equations containing transcendental functions. For example, there is no factoring technique
that will allow the following function to be solved:
2x
2
3x 1 + + 0 =
(2.1-1)
2x 1 + ( ) x 1 + ( ) 0 =
(2.1-2)
e
x
2x 2 + ( ) 0 =
(2.1-3)
8 Chapter 2Time-Domain Simulation

Even though this equation has only one unknown, the problem is that there is no obvious way to
separate the x from e
-x
without generating another transcendental function in x. This is a basic
limitation of conventional mathematical techniques.
So how do we get around this fundamental limitation? Digital computer simulation.
2.2. Digital Computer Simulation
Digital computer simulation has become an integral tool in the engineering community over the
past few decades. It is playing an ever-increasing role in the design of electrical and non-electrical
systems. The overall flow of the steps performed by a simulator to solve a network is illustrated in
Figure 2.2-1.
The main characteristic that distinguishes digital computer simulation is that all quantities take on
discrete valuesincluding time. To a digital computer simulator, time is broken down into
Time-Domain Simulation Flow
System described as network
equations.
Initial guess at step size.
If derivatives present, use numerical
integration to remove them.
If nonlinear, linearize the system.
Use standard techniques to solve
linear system (LU decomposition).
If convergence not achieved, perform
another iteration.
If error too big, reduce timestep, and
repeat steps beginning with numerical
integration.
If error OK, process digital events.
If simulation end time not reached,
take next step and repeat process.
If end time reached, write results.
Figure 2.2-1. Simulation flow for nonlinear differential-algebraic systems.
Solve the linear system
Numerical Integration
Linearize the system of equations
Converged?
No
Local Trerror No
within bounds?
Make initial guess of next time step h
Events processing
Yes
Yes
time = tend?
No
Yes
Write result
time = time + h
Reduce h
Formulation of the network equations
Digital Computer Simulation 9


incremental chunks called timesteps, and simulators will solve systems of equations at each one
of these timesteps, as shown in Figure 2.2-2.
Figure 2.2-2 is interpreted as follows: starting at time zero (t
n
), algebraic equations describing the
system are generated from a combination of the system models and their connections to each other.
Next, each node in the system is solved such that Kirchoffs Current LawKCL (or an equivalent
version of KCL for non-electrical systems) is satisfied for all nodes. In Figure 2.2-2, the solution at
time zero was determined at t
n
(which can be translated to "time now"). The node solution
corresponding to t
n
is represented by x
n
, and its solution is that point where it crosses the x-axis
(where y=0).
After a solution is obtained, time is advanced one step, indicated by t
n+1
(which can be translated to
"time now plus one timestep"). Then, the equations to be solved are re-generated, and a new
solution, x
n+1
is obtained. This process is repeated until the simulation end time is reached.
The solutions for various nodes are then typically plotted as a function of time, resulting in familiar
time-domain waveforms. These waveforms may appear as continuous functions of time, but they
are actually discrete points plotted at intervals equal to the step size used. These discrete points are
then typically connected by small straight lines, smoothing them, and producing the appearance of
continuous waveforms.
Although there are an infinite number of possible system configurations that can be simulated, the
systems of equations describing any continuous network will fall into one of the following four
categories:
Linear Algebraic Equations
Linear Differential-Algebraic Equations
Nonlinear Algebraic Equations
Nonlinear Differential-Algebraic Equations
y
y = f (x
n
, t
n
)
x
x
n
y
y = f (x
n+1
, t
n+1
)
x
x
n+1
y
y = f (x
n+2
, t
n+2
)
x
x
n+2
t
n
t
n+1
t
n+2
The simulator constructs and
solves the function y = f(x
n
, t
n
)
at the first timestep, t
n
.
When t
n
is solved, the function
y = f(x
n+1
, t
n+1
) is constructed
and solved at the following
timestep, t
n+1
.
When t
n+1
is solved, the
function y = f(x
n+2
, t
n+2
) is
constructed and solved at the
following timestep, t
n+2
.
Figure 2.2-2. Equation generation at each timestep.
10 Chapter 2Time-Domain Simulation

Overviews of how each of these systems can be solved using digital computer simulation
techniques are presented in the remainder of this chapter. Detailed step-by-step solutions to
examples of these systems are presented in Appendix A.
This chapter will detail the steps by which these systems may be solved in general. There are
several techniques whereby simulators enhance the solvability and/or efficiency of simulation
which will not be discussed here. For example, a simulators ability to take advantage of sparse
matrices, and matrix pivoting techniques are useful to the simulator developer, but not essential to
circuit/system designers who want to develop a basic understanding of the simulation process.
2.3. Linear Algebraic Equations
The ability to solve linear algebraic equations lies at the core of digital computer simulators.
Networks of this type are by far the easiest to solve because there are no time-dependent elements
in the equations, and many powerful matrix algebra techniques can be directly employed to solve
them.
A. Linear Algebraic Example
We will use the network shown in Figure 2.3-1 to illustrate one method by which a simple linear
algebraic system may be solved using computer simulation.
In order to solve the linear network of Figure 2.3-1, we will employ the following steps:
1. Create a KCL equation for each node (v
1
and v
2
).
2. Convert resistance values to conductance values (this step can be combined with step 1).
3. Generate conductance, voltage, and source matrices, and express in network form.
4. Solve for the voltage matrix.
Performing these steps on the circuit shown in Figure 2.3-1:
Figure 2.3-1. Linear algebraic network example.
R
1
R
2
I
src
gnd
v
1
v
2
R
3
Linear Algebraic Equations 11


Create KCL Equation for Each Node
Use KCL at each of the voltage nodes, v
1
and v
2
to generate the system equations:
Convert Resistance Terms to Conductance
Multiplying through by G
2
and collecting terms:
Generate Conductance, Voltage and Source Matrices
In matrix form, these equations can be represented as Equation (2.3-4):
Solve for the Voltage Matrix
Equation (2.3-4) is a specific instance of the more general matrix equation form given by Equation
(2.3-5):
Replacing the coefficient matrix A with the conductance matrix G, the unknown x matrix with v,
and the matrix b with the current matrix i, (2.3-5) can be expressed as shown in Equation (2.3-6):
v
1
R
1
------
v
1
v
2

R
2
----------------- + i
src
=
v
1
v
2

R
2
-----------------
v
2
R
3
------ =
(2.3-1)
G
1
v
1
G
2
+ v
1
v
2
( ) i
src
=
G
2
v
1
v
2
( ) G
3
v
2
=
(2.3-2)
G
1
G
2
+ ( )v
1
G
2
v
2
i
src
=
G
2
v
1
G
2
G
3
+ ( )v
2
0 =
(2.3-3)
G
1
G
2
+ G
2
G
2
G
2
G
3
+ ( )
v
1
v
2
i
src
0
=
(2.3-4)
Ax b =
(2.3-5)
Gv i = (2.3-6)
12 Chapter 2Time-Domain Simulation

The voltage matrix v is then equal to the inverse of the conductance matrix G times the current
matrix i:
Equation (2.3-4) can then be solved using the form shown in (2.3-7) with standard matrix solution
techniques, such as Gaussian elimination or LU decomposition.
The system of Figure 2.3-1 was simulated using the following component and simulation values:
G
1
=0.5, G
2
=1, G
3
=1, timestep (h) = 1.0, initial v
1
=v
2
=0, and I
src
ramps from 0A to 1A in steps of
0.1A each second. The results of repeating the solution process for several timesteps are given in
Figure 2.3-2.
The solutions given in Figure 2.3-2 are what we would expect for a simple voltage divider circuit in
response to a ramp input.
As can be seen from the figure, the abscissa of each measured point corresponds to the timestep,
and the ordinate gives the voltage value (any differences between the data in the table and
measured data is due to the measurement approach).
A complete solution to this circuit is given in Appendix A.
The systems of equations used to describe a typical network will include differential as well as
algebraic terms. These equations are referred to as differential-algebraic equations (DAEs), and are
the subject of the next section.
v G
1
i = (2.3-7)
time v
1(n+1)
v
2(n+1)
1.0 0.100000 0.050000
2.0 0.200000 0.100000
3.0 0.300000 0.150000
4.0 0.400000 0.200000
5.0 0.500000 0.250000
6.0 0.600000 0.300000
7.0 0.700000 0.350000
8.0 0.800000 0.400000
9.0 0.900000 0.450000
10.0 1.000000 0.500000
Figure 2.3-2. Linear algebraic network response to ramp input.
Linear Differential-Algebraic Equations 13


2.4. Linear Differential-Algebraic Equations
So far we have discussed the important class of linear algebraic systems and their solutions. We
now complicate matters slightly by adding derivatives to the system of equations.
Differential equations require different solution techniques than algebraic equations because
differential equations cannot be solved in the traditional sensethe unknowns cannot be
algebraically separated from the differential operators and collected on one side of the equals sign.
For example, take a current source, resistor, and capacitor in parallel as shown in Figure 2.4-1.
The nodal equations describing this system are shown in Equation (2.4-1):
In this differential equation, v cannot be readily isolated from the rest of the equation. So how can
the system be solved? We will use a little common-sense to come up with a solution, and then
discuss formal approaches to solve linear differential-algebraic systems.
If we think about solving (2.4-1) on a digital computer, the derivative term, which represents the
slope of a line, can be expressed as shown in Equation (2.4-2):
Where v
new
and v
old
represent the voltages across the capacitor at the current and previous
timesteps, respectively, and step size is the size of the timestep. Another way to express (2.4-2) is
given in Equation (2.4-3):
Figure 2.4-1. Parallel IRC circuit.
R C
I
src
gnd
v
C
t d
dv v
R
---- + i
src
=
(2.4-1)
C
t d
dv
C
v
new
v
ol d

stepsize
---------------------------- (2.4-2)
C
t d
dv
C
v
n 1 +
v
n

h
------------------------
(2.4-3)
14 Chapter 2Time-Domain Simulation

Equation (2.4-3) gives a more conventional form for describing discrete quantities used with
computer simulation. In this case, the next (new) voltage value is designated v
n+1
, and the previous
(old) value is designated v
n
. The step size is denoted by the variable h.
Now, our original linear differential-algebraic problem given in (2.4-1) can be restated as shown in
Equation (2.4-4):
We have thus transformed a differential-algebraic equation into a time finite difference algebraic
equation. The voltage can now be determined by algebraically solving (2.4-4) for v
n+1
. The process
digital computers use to convert differential terms into algebraic terms is called numerical
integration.
A. Numerical Integration
In general, the basic approach used to solve a differential equation is to take out the differential
terms by integrating them. For a digital computer employing a DAE simulator, solving a
differential equation is generally accomplished with numerical integration methods. There are
several integration methods commonly employed in simulators. The most popular are forward
Euler, backward Euler (Gear 1), the trapezoidal method, and Gear 2. These will be discussed in
turn.
Forward Euler
The general equation for the forward Euler integration method is given in Equation (2.4-5):
This formula estimates the value of a function at the next timestep, t
n+1
, by adding the value of the
function at the current timestep to the product of the timestep size (step size) and the derivative of
the function at the current timestep.
In this case, the value of the function at the next timestep, Y(t
n+1
), depends only on information
from the current timestep, Y(t
n
). For this reason, the forward Euler integration method serves as a
good way to get an initial estimation of the value of a function at the next timestep.
Backward Euler
The backward Euler formula is shown in Equation (2.4-6):
C
v
n 1 +
v
n

h
------------------------
v
n 1 +
R
------------- + i
src
n 1 +
= (2.4-4)
Y t
n 1 +
( ) Y t
n
( ) stepsize
t d
d
Y t
n
( ) + = (2.4-5)
Y t
n 1 +
( ) Y t
n
( ) stepsize
t d
d
Y t
n 1 +
( ) + =
(2.4-6)
Linear Differential-Algebraic Equations 15


This is very similar to the forward Euler formula, with one important catch: the derivative of the
function at the next timestep must be known. But since that step has not yet occurred, this point
must be somehow guessed at or estimated. This brings us to the concept of prediction and
correction, which is discussed in Section 2.6. The backward Euler method is sometimes referred to
as Gear 1.
Trapezoid Rule
An often better numerical integration option than the backward Euler method is the trapezoid rule.
This approach works well because it uses the average of the forward Euler method (which tends to
produce negative errors), and the backward Euler method (which tends to produce positive errors),
so the errors average out somewhat. The trapezoid rule is given in Equation (2.4-7):
The trapezoid rule does have the same limitation as the backward Euler approach in the sense that
the derivative of the function at the next timestep must be known. Also, although it is very popular,
in some cases the trapezoid rule may cause ringing on the circuit being simulated. Another
algorithm, Gear 2 may be a better choice to avoid this problem.
Gear 2
The Gear 2 method extends the previous approaches by taking a weighted average of the next,
current, and previous solutions to better predict a solution at the next timestep. It is shown in
Equation (2.4-8):
In most cases, the Gear 2 method is nearly as accurate as the trapezoid rule, and also has the
advantage of being more stable. Because of this stability, it does not have a tendency to oscillate.
B. Linear DAE Example
To solve linear DAEs, an original equation is defined with algebraic as well as differential terms.
To solve these equations, a numerical integration formula, or combinations of numerical integration
formulas are employed. In essence, these integration formulas are used to transform the differential
Y t
n 1 +
( ) Y t
n
( )
stepsize
2
---------------------
t d
d
Y t
n 1 +
( )
t d
d
Y t
n
( ) + + = (2.4-7)
Y t
n 1 +
( )
4
3
---


Y t
n
( )
1
3
---


Y t
n 1
( )
2
3
---


stepsize
t d
d
Y t
n 1 +
( ) + =
(2.4-8)
16 Chapter 2Time-Domain Simulation

terms into algebraic terms. The numerical integration formulas can be rearranged to assist in this
substitution, as shown for the backward Euler formula in Equation (2.4-9):
The right-hand side of (2.4-9) can be directly substituted into the differential terms of the original
differential equation. This results in an algebraic equation.
We will use the network shown in Figure 2.4-2 to illustrate how a simple linear differential-alge-
braic system may be solved using digital computer simulation.
The steps for solving a linear DAE example using computer simulation are:
1. Use KCL to generate algebraic-differential equations.
2. Create conductance and capacitance matrices.
3. Isolate differential terms on one side of the equation.
4. Replace differential terms with numerical integration formula.
5. Solve the new, algebraic equations using standard matrix algebra techniques.
Generate System of Equations using KCL
The equations describing this network are as follows:
t d
d
Y t
n 1 +
( )
Y t
n 1 +
( ) Y t
n
( )
stepsize
----------------------------------------- =
(2.4-9)
Figure 2.4-2. Linear differential-algebraic network example.
R
1
C
1
I
src
gnd
v
1
R
2
v
2
R
3
C
2
G
1
v
1
C
1
t d
d
v
1
G
2
+ + v
1
v
2
( ) C
2
t d
d
v
1
v
2
( ) + i
src
=
G
2
v
1
v
2
( ) C
2
t d
d
v
1
v
2
( ) + G
3
v
2
=
(2.4-10)
Linear Differential-Algebraic Equations 17


Create Conductance and Capacitance Matrices
As you have doubtless noticed by now, there is a strong electrical prejudice with regards to digital
computer simulation nomenclature. The terms conductance and capacitance matrices are a
by-product of the original electrical-based applications of computer simulators. Although these
traditional terms will be used in this book, they could be translated into "algebraic-based" matrices
(for conductance) and "derivative-based" matrices (for capacitance), with respect to non-electrical
domains.
Using the standard terminology, we will solve differential-algebraic systems by first separating the
capacitance and conductance matrices, and expressing them as shown in Equation (2.4-11):
The original system equations expressed in this form are given in Equation (2.4-12):
It is because of the algebraic and differential aspects of the terms of these matrices that they are
separated. Those coefficients belonging to the given variables form the conductance matrix; those
coefficients belonging to derivatives of those variables form the capacitance matrix.
We will next isolate the derivatives and substitute in the desired numerical integration formula for
them. This will result is rearranging (2.4-11) to the form shown in Equation (2.4-13):
Isolate Differential Terms
Isolating the derivatives in the system equations, we get Equation (2.4-14):
Cv' Gv + i = (2.4-11)
C
1
C
2
+ ( ) C
2

C
2
C
2

t d
d
v
1
t d
d
v
2
G
1
G
2
+ ( ) G
2

G
2
G
2
G
3
+ ( )
+
v
1
v
2
i
src
0
=
(2.4-12)
v' C
1
i Gv ( ) = (2.4-13)
t d
d
v
1
t d
d
v
2
C
1
C
2
+ ( ) C
2

C
2
C
2

1
G
1
G
2
+ ( ) G
2
+
G
2
G
2
G
3
+ ( ) +
v
1
v
2
i
src
0
+




= (2.4-14)
18 Chapter 2Time-Domain Simulation

Replace Differential Terms with Integration Formula
The next step is to pick an integration formula and replace all left-hand side derivatives of (2.4-14)
with it. In this example, the backward Euler formula was chosen:
Solve the Algebraic Equations using Matrix Techniques
Once we have removed the differential terms, we have a set of linear, algebraic equations. The node
voltages can then be solved using matrix algebra.
The system of Figure 2.4-2 was simulated using the following component and simulation values:
G
1
=0.5, G
2
=1, G
3
=2, C
1
=1, C
2
=1, timestep (h) = 0.1. Initial v
1
=v
2
=0. I
src
=1A step. The results of
repeating this process for several timesteps and the corresponding voltage vs. time waveforms are
given in Figure 2.4-3.
The first column of the simulation results represents the simulation time, and the following
columns represent the voltages at v
1
and v
2
, respectively. As can be seen from the figure, the
abscissa of the measured points correspond to the timesteps, and the ordinate corresponds to the
voltage (any differences between the data in the table and measured data is due to the measurement
approach).
A full solution to this example is presented in Appendix A.
v
1 n 1 + ,
v
1 n ,

h
----------------------------------
v
2 n 1 + ,
v
2 n ,

h
----------------------------------
C
1
C
2
+ ( ) C
2

C
2
C
2

1
G
1
G
2
+ ( ) G
2
+
G
2
G
2
G
3
+ ( ) +
v
1
v
2
i
src
0
+




= (2.4-15)
time v
1, n+1
v
2, n+1
0.10 0.082019 0.069401
0.20 0.150882 0.117963
0.30 0.209925 0.152306
0.40 0.261467 0.176920
0.50 0.307140 0.194851
0.60 0.348101 0.208171
0.70 0.385184 0.218287
0.80 0.419003 0.226158
0.90 0.450014 0.232439
1.00 0.478570 0.237578
Figure 2.4-3. Linear DAE response to ramp input.
Nonlinear Algebraic Equations 19


2.5. Nonlinear Algebraic Equations
With both linear algebraic and linear differential systems, solutions may be obtained using standard
matrix solution techniques. Yet as powerful as they are, techniques such as Gaussian elimination
and LU Decomposition have a serious limitation: they only apply to linear systems of equations.
However, the vast majority of real-world problems will contain nonlinear elements. To overcome
these limitations, we linearize the nonlinear systems of equations about the solution point, then
solve them using standard matrix methods.
There are several numerical methods that can be used to solve nonlinear equations. The most
widely used, and for this reason the one discussed here, is the Newton-Raphson method (also
referred to as Newtons method).
A. Newton-Raphson Method
The Newton-Raphson method is a technique for taking successive approximations of real roots. It
is derived from Taylors Formula, shown in Equation (2.5-1):
Taylors Formula can be used to find polynomial approximations of functions. If only the
first-degree polynomial of the formula is used, (2.5-1) can be simplified to the form given by
Equation (2.5-2):
In (2.5-2), f(x) can be approximated as long as x is close to a.
By expressing the function such that the unknown root intersects the x-axis, we can set f(x) in
(2.5-2) equal to zero, and restate the formula as Equation (2.5-3):
Equation (2.5-3) represents the Newton-Raphson iteration method, and constitutes the fundamental
equation with which we will solve the majority of simulation circuits and systems. The
Newton-Raphson method solves for the next iteration of x, designated x
(1)
.
f x ( ) f a ( )
f a ( )
1!
---------- x a ( )
f a ( )
2!
----------- x a ( )
2

f
n ( )
a ( )
n!
--------------- x a ( )
n
+ + + + = (2.5-1)
f x ( ) f a ( ) = f a ( ) x a ( ) + (2.5-2)
x
1 ( )
x
0 ( ) f x
0 ( )
( )
f x
0 ( )
( )
------------------ = (2.5-3)
20 Chapter 2Time-Domain Simulation

To determine a solution to a nonlinear equation using the Newton-Raphson method, we start from a
good guess, x
(0)
and subtract from this starting point the function evaluated at x
(0)
, divided by the
derivative of the function evaluated at x
(0)
. We then use the newly-calculated value x
(1)
in place of
x
(0)
and repeat the process to calculate x
(2)
.
We keep iterating in this manner until a a solution is obtained (i.e. until the x-intercept is
converged upon). If the iterations are started off with a good guess, the Newton-Raphson method
will converge quadratically upon the solution.
This concept is shown graphically in Figure 2.5-1.
In Figure 2.5-1, x
(0)
is guessed. F(x) is then evaluated at x
(0)
, and the tangent at that point on f(x) is
shown to cross the x-axis at x
(1)
. This crossing point now becomes the first iteration to the initial
guess. This process is repeated using x
(1)
as the starting value, and once again a tangent line is
drawn at the new solution point. Finally, when the iterated solution is close enough, the process
terminates. The actual solution is located at the point where the waveform crosses the x-axis (the
x-intercept).
An important feature of Figure 2.5-1 is that the independent axis is not time. When performing
Newton-Raphson iterations, the simulator is solving for roots of equations. The actual timestep will
occur after the iteration process is complete. This will be discussed further in Section 2.6.
Square Root Example
A simple application of the Newton-Raphson method would be to approximate the square root of
seven. Stating this problem algebraically:
Using the Newton-Raphson method with a starting guess of 3, we would compute the first iteration
of the solution as follows:
y
x
(0)
y=f(x)
x x
(2)
x
(1)
Figure 2.5-1. Iterative root estimation using the Newton-Raphson method.
f x ( ) x
2
7 =
(2.5-4)
x
1 ( )
x
0 ( ) x
0 ( )
( )
2
7
2x
0 ( )
------------------------- - = 3
9 7
2 3
----------- - 2.667 = = (2.5-5)
Nonlinear Algebraic Equations 21


The second iteration would then be computed using the results of (2.5-5) as the starting point:
More iterations can be performed for greater accuracy.
Transcendental Function Example
To get an intuitive feel for using the Newton-Raphson method to solve systems of equations, we
will consider two functions. The first function is linear and is described by 2x + 2. The second
function in nonlinear, and described by e
-x
. Calculated values for each function are given in Tables
2.5-1 and 2.5-2:
When plotted on the same graph, these functions produce the waveforms shown in Figure 2.5-2.
The solution to this system of equations lies at that point where the two graphs intersect, at about
x = -0.3.
x
2 ( )
x
1 ( ) x
1 ( )
( )
2
7
2x
1 ( )
------------------------- - = 2.667
7.111 7
5.333
---------------------- 2.6458 = = (2.5-6)
x f
1
(x)
-2.00 -2.00
-1.00 0.00
0.00 2.00
1.00 4.00
2.00 6.00
Table 2.5-1. 2x + 2
x f
2
(x)
-2.00 7.40
-1.00 2.72
0.00 1.00
1.00 0.37
2.00 0.14
Table 2.5-2. e
-x
Figure 2.5-2. Graphical solution to functions of Tables 2.5-1 and 2.5-2.
-0.3
f
1,2
(x)
x
f
1
(x) = 2x + 2 f
2
(x) = e
-x
22 Chapter 2Time-Domain Simulation

By subtracting f
1
(x) from f
2
(x), a new equation f
3
(x) is produced. This new function evaluated at
several points is shown in Figure 2.5-3:
The graph of f
3
(x) is useful in that it illustrates that the solution for the new equation is located at
the x-intercept (where f
3
(x)= 0).
The Newton-Raphson method will now be employed to solve f
3
(x). We will start with an initial
solution guess of -0.5, and perform the following steps:
As you can see, the solution is converging somewhere around -0.3, as expected from Figure 2.5-3.
The Newton-Raphson method applied to this problem is shown graphically in Figure 2.5-4.
x f
3
(x)
-2.00 9.40
-1.00 2.72
0.00 -1.00
1.00 -3.63
2.00 -5.86
Table 2.5-3. e
-x
- 2x - 2
Figure 2.5-3. F
3
(x) obtained by subtracting f
1
(x) from f
2
(x).
x
1 ( )
x
0 ( ) 2x
0 ( )
2 e
x
0 ( )

+
2 e
x
0 ( )

+
------------------------------------------ = 0.5
1 2 1.65 +
2 1.65 +
--------------------------------- 0.322 = =
x
2 ( )
x
1 ( ) 2x
1 ( )
2 e
x
1 ( )

+
2 e
x
1 ( )

+
------------------------------------------ = 0.322
0.644 2 1.38 +
2 1.38 +
------------------------------------------- =
x
2 ( )
0.315 =
(2.5-7)
-0.5 -0.322 -0.315
x
y
Figure 2.5-4. Graphical example of Newton Raphson
method with numerical values.
Nonlinear Algebraic Equations 23


As can be seen from Figure 2.5-4, an initial x value is picked (-0.5). From this value, the
corresponding point on the function is determined using y=f(x). The derivative is then taken, and the
point where this tangent line intersects the x-axis, -0.322, is used as the x value for the next
iteration. The process is repeated until a solution of the desired accuracy is obtained.
A computer simulator has the arduous task of performing these iterations on every node of a design,
and for each timestep in a transient analysis. This overall process is illustrated graphically in Figure
2.5-5.
In Figure 2.5-5, Newton-Raphson iterations are shown as superscripts to x, while timesteps are
indicated by subscripts to x. The notation y=f(x
n
, t
n
) denotes that the given function is dependent on
the independent variable, x, as well as time, t.
Newton-Raphson Method with Multiple Variables
It is convenient to express multivariate systems of equations in matrix form. With matrices, these
equations are typically solved using the Newton-Raphson method as expressed in the form given in
Equation (2.5-8):
y
x
n
(0)
y=f(x
n
,t
n
)
x x
n
(n)
y
x
n+1
(0)
y=f(x
n+1
,t
n+1
)
x x
n+1
(n)
t
n
t
n+1
t
n+2
y
x
n+2
(0)
y=f(x
n+2
,t
n+2
)
x x
n+2
(n)
...
...
...
Figure 2.5-5. Equation generation and solution at each timestep.
After each algebraic function is
generated, the simulator uses
Newton-Raphson iterations to
converge on the solution (where
the given function crosses the
x-axis).
x J
1
f x ( ) =
(2.5-8)
24 Chapter 2Time-Domain Simulation

Where J is the Jacobian matrix, and consists of the partial derivatives of all terms in the function as
shown in Figure 2.5-6.
Equation (2.5-8) is the multivariate representation of the Newton-Raphson method as expressed
previously in (2.5-3). In essence, the Jacobian matrix represents an array of linearized function
segments. These linear segments are used to determine the x-intercept points discussed earlier.
Since all practical systems will have many variables, Equation (2.5-8) will be used exclusively
throughout the remainder of the text.
In the previous examples of the Newton-Raphson method, we literally took the derivative of the
given function in order to linearize it and determine the x-intercept. It turns out that there are other,
and sometimes superior methods for doing this. Three commonly used methods for linearizing the
characteristic equations are discussed next.
B. Linearizing the Characteristic Equations
In order to populate the Jacobian matrix, each term of the characteristic equation (i.e. each element
in the original matrix) must be linearized. Since the Newton-Raphson method is derived from only
the first-degree polynomial of Taylors Formula, applying it actually linearizes the equations about
x. The key then, lies in how the Newton-Raphson method is implemented. There are many ways to
do this, the three most popular are described below.
Taking the Slope (Method 1)
A common technique for equation linearization is to determine the slope of the point on the
characteristic equation which corresponds to the present value of the independent variable. This is
x
1

f
1
( )
k
x
2

f
1
( )
k

x
n

f
1
( )
k
x
1

f
2
( )
k
x
2

f
2
( )
k

x
n

f
2
( )
k

x
1

f
n
( )
k
x
2

f
n
( )
k

x
n

f
n
( )
k
Figure 2.5-6. Structure of a Jacobian matrix.
Nonlinear Algebraic Equations 25


the approach we have shown in the previous discussion, where the slope is computed by taking the
derivative of the function. This technique is illustrated in Figure 2.5-7.
In this case, v
o
represents the independent variable for which the slope of the function will be
generated. Simulators using this approach find, for the nonlinear equations, an approximate
solution that is controlled by one or more convergence parameters. While this approach is in some
ways appealing, the requirement for continuous derivatives makes modeling of such characteristics
very difficult, if they are described by different functions in different regions of the independent
variables.
Piecewise Linear Approximation (Method 2)
Another linearization technique is piecewise linear approximation, shown in Figure 2.5-8.
Rather than describing a nonlinear characteristic exactly, the piecewise linear approximation model
consists of a set of straight lines approximating the nonlinear equation.
v
out
v
in
v
0
Figure 2.5-7. Linearization by taking the slopeMethod 1.
Models include characteristic equations
as well as their derivatives with respect
to the independent variables.
Model equations and their derivatives
must be continuous functions of the
independent variables.
v
out
v
in
v
0
Figure 2.5-8. Piecewise linear approximationMethod 2.
The characteristic equations are obtained
before the simulation begins, so all the
simulator sees are the piecewise linear
models, which must be continuous, but
obviously have discontinuous derivatives.
These models are solved exactly using
special algorithms. However, the accuracy
can be changed only by changing the
model.
26 Chapter 2Time-Domain Simulation

Piecewise Linear Evaluation (Method 3)
The final linearization technique is called piecewise linear evaluation. The models consist of the
nonlinear equations plus a set of "sample points" for the independent variables. The simulator uses
the sample points to find piecewise linear approximations of the nonlinear equations, as shown in
Figure 2.5-9, where v1...v5 are the sample points.
For piecewise linear evaluation, the density of the sample points can be specified by the user. The
density can be thought of as a multiplier for the sample points. This enables the user to choose (at
run time) either increased accuracy or faster computation time. Given that the slope technique
cannot solve the equations exactly, this technique can produce results as accurate as those produced
by the slope technique, if the density of the sample points is sufficiently high.
C. Nonlinear Algebraic Example
We will use the network shown in Figure 2.5-10 to illustrate how a simple nonlinear algebraic
system may be solved using computer simulation.
v
out
v
in
v
0
v
1
v
2
v
3
v
4
v
5
Figure 2.5-9. Piecewise linear evaluationMethod 3.
The simulator solves the piecewise linear
approximations of the models exactly,
using specialized algorithms.
Again the accuracy of the solution
depends upon the piecewise linear
approximations, but the main advantage
of this approach is that the density of the
sample points is easily changed.
Figure 2.5-10. Nonlinear algebraic network example.
R
1
R
2
I
src
gnd
v
1
v
2
R
3
i = v
2
Nonlinear Algebraic Equations 27


The equations describing this network are as follows:
This is similar to the linear algebraic network in Figure 2.3-1 with an additional (v
2
)
2
component.
With the (v
2
)
2
term present, standard linear algebraic solution techniques cannot be used to solve
the system. To solve this nonlinear system of equations, we will perform the following steps:
1. Simplify the equations and calculate f
1
(v
1
, v
2
) and f
2
(v
1
, v
2
).
2. Generate the Jacobian matrix, J.
3. Determine the change in voltage from the previous iteration using .
4. Find the new voltage with .
5. Iterate starting from (1) using updated voltage values until convergence.
Calculate f(v)
This matrix is developed by collecting all terms of the original equations on the left-hand side and
setting them equal to zero. The upper row represents f
1
, the lower row represents f
2
:
Calculate Jacobian (J)
The Jacobian matrix is created by differentiating each equation (f
1
and f
2
), and populating a new
matrix with the results. The results occupy the same positions in the matrix as did the original
elements:
G
1
v
1
G
2
+ v
1
v
2
( ) i
src
=
G
2
v
1
v
2
( ) G
3
v
2
v
2
( )
2
+ =
(2.5-9)
v
x
J
1
f v ( ) =
v
x
( )
k 1 +
v
x
( )
k
v
x
+ =
f v ( )
G
1
v
1
G
2
+ v
1
v
2
( ) i
src

G
2
v
1
v
2
( ) G
3
v
2
v
2
( )
2

= (2.5-10)
J
v
1

G
1
G
2
+ ( )v
1
v
2

G
2
( )v
2
v
1

G
2
v
1
v
2

G
2
G
3
( )v
2
v
2
( )
2
[ ]
=
(2.5-11)
28 Chapter 2Time-Domain Simulation

After differentiation, the Jacobian matrix is reduced as shown:
Calculate Change in Voltage
The overall change in voltage from the previous iteration can be solved as:
Which in terms of the actual system can be expressed as:
Calculate the New Voltage
With v calculated, the new voltage can be found with:
Where (v
x
)
k+1
is the voltage of the next iteration, (v
x
)
k
is the current voltage, and v
x
is the change
in voltage calculated in (2.5-14).
Iterate Until Solution is Found and Advance Timestep
The final voltage change is found by iterating (2.5-14) and (2.5-15) until an acceptable level of
accuracy is reached. Once this is done, the timestep is advanced and the process is repeated.
The system of Figure 2.5-10 was simulated using the following component and simulation values:
G
1
=0.5, G
2
=1, G
3
=2, timestep (h) = 0.1. Initial v
1
=v
2
=0.2. I
src
=1A.
J
G
1
G
2
+ G
2

G
2
G
2
G
3
2v
2

=
(2.5-12)
v J
1
f v ( ) = (2.5-13)
v
G
1
G
2
+ G
2

G
2
G
2
G
3
2v
2

1
G
1
v
1
G
2
+ v
1
v
2
( ) i
src

G
2
v
1
v
2
( ) G
3
v
2
v
2
( )
2

= (2.5-14)
v
x
( )
k 1 +
v
x
( )
k
v
x
+ =
(2.5-15)
Nonlinear Differential-Algebraic Equations 29


The results of several iterations of this simulation are given in Table 2.5-4.
In Table 2.5-4, the first column gives the Newton-Raphson iteration number. The second and third
columns show the change in voltage from the previous iteration for v
1
and v
2
respectively. The
fourth and fifth columns give the new values for v
1
and v
2
.
In this case, it can be seen that for the initial iteration, v
1
is 0.639024V. This is the amount of
voltage change calculated. This value is added to the previous iteration value of 0.2V. In this case,
this is the first iteration, so the initial voltage value was used. The new node voltage for v
1
is the
sum of these values, which is 0.839024V. Now this value of v
1
will be used as the starting point of
the next iteration, and the process is repeated. As can be seen from Table 2.5-4, the simulation took
only two iterations to converge on a solution.
A complete solution to this example is presented in Appendix A.
2.6. Nonlinear Differential-Algebraic Equations
There is a final step in this development of numerical solutions to systems of equations. So far, we
have dealt with linear algebraic as well as linear differential-algebraic equations, and also with
nonlinear algebraic equations. However, we have not yet combined nonlinearities and differential
equations into a single network. In this section, we will discuss how to numerically analyze
nonlinear DAEs.
In order to solve nonlinear DAEs, we will employ prediction and correction methods. The concept
of predictors and correctors will be discussed next.
A. Predictors and Correctors
Prediction and correction in DAE simulators can be fairly confusing. What it boils down to is this:
in order to use the backward Euler, trapezoid, or Gear 2 integration formulas, the derivative of the
function being solved must be known for the next timestep. However, this value is not known,
because the next timestep is what we are solving for in the first place. So a predictor formula is
often used to come up with an initial value for the derivative of the function at the next timestep.
The forward Euler formula works well in this capacity because, unlike the other formulas
discussed, it does not require the derivative of the function at the next timestep: it only needs the
iter v
1
v
2
v
1(n+1)
v
2(n+1)
0 0.639024 0.058537 0.839024 0.258537
1 -0.000801 -0.001202 0.838223 0.257334
2 0.000000 -0.000001 0.838223 0.257334
3 0.000000 0.000000 0.838223 0.257334
Table 2.5-4. Nonlinear-algebraic network response to DC input.
30 Chapter 2Time-Domain Simulation

derivative at the current timestep. For this reason, the forward Euler method is often used as a
predictor algorithm, to guess at what the derivative of the function at t
n+1
will be. This predicted
value can then be used as a starting point for a corrector algorithm.
After making the prediction, the simulator iteratively tests it using the Newton-Raphson method
(typically), along with a corrector integration formula. Figure 2.6-1 illustrates this concept.
Starting from t
n
on the x-axis in Figure 2.6-1, a prediction is made as to where the solution will be
at t
n+1
. This first, predicted solution is designated x
n+1
(0)
. A timestep is taken, and starting with
this predicted value, the Newton-Raphson iterations are performed until a solution is reached. Each
iteration is indicated by incrementing the superscript, so that the first iteration is x
n+1
(0)
, the second
is x
n+1
(1)
, and so on. Once a solution is found, a new timestep is taken and the process repeated.
If the difference between the predicted and corrected values is very large, the timestep size may be
reduced; if the difference is very small, the timestep size may be increased. In this manner, the
simulator is able to increase efficiency by making simulation time and accuracy trade-offs.
Figure 2.6-2 illustrates the case where the predicted and corrected values were quite different,
resulting in a smaller timestep.
t
n-1
t
n
t
n+1
x
n-1
x
n
x
n+1
(0)
x
t
x
n+1
(1)
x
n+1
(2)
x
n+1
(k)
Iterations of the
the Newton-Raphson
algorithm
h
Predictor
Corrector
Figure 2.6-1. Graphical view of predictor/corrector functions.
t
n-1
t
n
t
n+1
(1)
x
n-1
x
n
x
n+1
(0)
x
t
x
n+1
(k)
h
t
n+1
(2)
LTE
if LTE > Max. Trunc. Error
.
.
.
Figure 2.6-2. Timestep adjustment due to large predictor/corrector difference.
Nonlinear Differential-Algebraic Equations 31


In this situation, a prediction is made at t
n
, resulting in timestep t
n+1
(1)
, where the superscript
implies the first timestep guess. The difference between predicted and corrected solution values is
greater than the user-specified local truncation error (LTE), so the simulator is instructed to take a
smaller timestep, t
n+1
(2)
. The process is then repeated at the new timestep.
B. Nonlinear DAE Example
We will use the network shown in Figure 2.6-3 to illustrate how a simple nonlinear DAE system
may be solved using computer simulation.
The general approach to solving nonlinear DAEs is presented below.
1. First, generate the standard equations representing the system to be solved. These equa-
tions will contain nonlinear algebraic terms, as well as differential terms.
2. Isolate derivatives and calculate the predicted value for the next timestep.
3. Convert the differential terms of the DAEs into discrete-time algebraic terms by
substituting in an integration formula for all time derivatives.
4. Employ the Newton-Raphson technique to iterate to a solution point (this step creates a set
of linear algebraic equations).
Generate System of Equations using KCL
The equations describing this system are as follows:
Figure 2.6-3. Nonlinear differential-algebraic network example.
R
1
C
1
I
src
gnd
v
1
R
2
v
2
R
3
C
2
i = v
2
G
1
v
1
G
2
+ v
1
v
2
( ) C
t d
d
v
1
v
2
( ) + i
src
=
G
2
v
1
v
2
( ) C
t d
d
v
1
v
2
( ) + G
3
v
2
v
2
( )
2
+ =
(2.6-1)
32 Chapter 2Time-Domain Simulation

The overall approach to solving these equations is:
Isolate and Solve for Derivatives to Get Predictor Values
Next, isolate the capacitance matrix (derivative terms):
Denote the capacitance matrix as C, the conductance matrix as G, and the matrix with the current
source and (v
2
)
2
term as w. Equation (2.6-3) can then be expressed as:
Solving (2.6-4) for v yields:
Substituting in numerical values and solving (2.6-5) yields the derivative value required for the
forward Euler formula:
In order to keep the nomenclature as clear as possible and to show that the forward Euler method is
being used as a predictor, (2.6-6) can be expressed as:
where the predicted (next) voltage, v
P
is equal to the current voltage, v
0
plus the product of the step
size, h, and the derivative of the current voltage.
The predictor solutions are needed to get numerical values into the Jacobian matrix, J, and also to
solve the function f(v). This was not necessary for the linear differential network of Section 2.4
because it is only the nonlinear term, (v
2
)
2
that is not converted to a constant upon being
differentiated. All conductance and capacitance terms are simply replaced with their coefficients
for which the numerical values are known.
v J
1
f v ( ) =
(2.6-2)
C
1
C +
2
C
2
C
2
C
2

t d
d
v
1
t d
d
v
2
G
1
G
2
+ ( ) G
2
G
2
G
2
G
3
+ ( )
v
1
v
2
i
src
v
2
( )
2
+ = (2.6-3)
Cv' Gv w + = (2.6-4)
v' C
1
Gv w + ( ) = (2.6-5)
Y t
n 1 +
( ) Y t
n
( ) stepsize
t d
d
Y t
n
( ) + = (2.6-6)
v
P
v
0
hv'
0
+ =
(2.6-7)
Nonlinear Differential-Algebraic Equations 33


Convert Differential into Algebraic Equations
Next, substitute the backward Euler formula in for the differential terms:
Simplify further by multiplying through by h and collecting all terms on the left-hand side:
Using the system coefficients, initial values, and predictor values, (2.6-9) can now be used to
generate the Jacobian matrix and calculate f(v).
Iterate Using the Newton-Raphson Method
With numerical values for J and f(v), (2.6-2) is then iterated on until a solution for the timestep is
achieved. The simulator then takes the next timestep, and the process is repeated.
The system of Figure 2.6-3 was simulated using the following component and simulation values:
G
1
=0.5, G
2
=1, G
3
=2, C
1
=1, C
2
=1, timestep (h) = 0.1. Initial v
1
=v
2
=0. Isrc=1A step. The results of
several iterations of this simulation are given in Table 2.6-1.
time iter v
1
v
2
v
1, n+1
v
2, n+1
0.1 0.00 -0.018243 -0.031112 0.081757 0.068888
1.00 -0.000066 -0.000129 0.081691 0.068759
2.00 0.000000 0.000000 0.081691 0.068759
3.00 0.000000 0.000000 0.081691 0.068759
0.2 0.00 -0.013626 -0.021745 0.149755 0.115774
1.00 -0.000032 -0.000062 0.149723 0.115712
2.00 0.000000 0.000000 0.149723 0.115712
3.00 0.000000 0.000000 0.149723 0.115712
Table 2.6-1. Nonlinear DAE network response to step input.
v
1 n 1 + ,
v
1 n ,

h
----------------------------------
v
2 n 1 + ,
v
2 n ,

h
----------------------------------
C
1
Gv w + ( ) =
(2.6-8)
v
1 n 1 + ,
v
1 n ,

v
2 n 1 + ,
v
2 n ,

h C
1
Gv w + ( ) ( ) 0 =
(2.6-9)
34 Chapter 2Time-Domain Simulation

Table 2.6-1 shows the timestep (time), the iterations per timestep (iter), the voltage changes (v
1
and v
2
), and the final solutions for the timestep. The values of the first iteration of each timestep
are the results obtained using the predictors guess; the remaining iterations show the corrections to
the prediction. When the correction is "close enough," the solution is complete, and the timestep is
advanced.
The voltage vs. time waveforms are graphed for several of these timesteps in Figure 2.6-4.
As can be seen from the figure, the abscissas of the measured points correspond to the timesteps,
and the ordinates correspond to the voltage values. These values correlate to those given in Table
2.6-1 (any differences between the data in the table and measured data is due to the measurement
approach).
A complete solution to this example is presented in Appendix A.
0.3 0.00 -0.010145 -0.014821 0.207610 0.147843
1.00 -0.000015 -0.000029 0.207596 0.147814
2.00 0.000000 0.000000 0.207596 0.147814
3.00 0.000000 0.000000 0.207596 0.147814
0.4 0.00 -0.007636 -0.009952 0.257832 0.169965
1.00 -0.000007 -0.000013 0.257826 0.169953
2.00 0.000000 0.000000 0.257826 0.169953
3.00 0.000000 0.000000 0.257826 0.169953
time iter v
1
v
2
v
1, n+1
v
2, n+1
Table 2.6-1. Nonlinear DAE network response to step input.
Figure 2.6-4. Voltage waveforms corresponding to Table 2.6-1.
v
1(n+1)
v
2(n+1)
Chapter Summary 35


2.7. Chapter Summary
The goal of this chapter was to acquaint simulation users with the various mathematical methods
used by digital computer simulators. Four basic types of systems were analyzed using time-domain
simulation techniques: linear algebraic systems, linear differential-algebraic systems, nonlinear
algebraic systems, and nonlinear differential-algebraic systems. This has not been a comprehensive
study, but has hopefully provided readers with a foundation that takes much of the mystery out of
digital computer simulation.
36 Chapter 2Time-Domain Simulation



chapter 3
VHDL-AMS Overview
This chapter presents a brief overview of VHDL 1076.1, or VHDL-AMS (Very High Speed
Integrated Circuit Hardware Description Language - Analog and Mixed-Signal). This overview is
intended to familiarize the reader with modeling terminology and concepts encountered throughout
the bookit is not intended as a general VHDL-AMS reference. Please see Appendix D for a list
of references.
The VHDL 1076.1 language intends to be to the analog and mixed-signal designer what the VHDL
1076 language is to the digital designer. VHDL 1076.1 is a superset of VHDL 1076-1993
supporting the description and simulation of digital, analog, and mixed analog/digital (often called
mixed-signal) systems in a single language. This approach sets VHDL-AMS apart from other
approaches where a special mixed-signal language is needed to describe the interaction between
models written in separate analog and digital languages.
3.1. VHDL-AMS Model Terminology
As a superset of a digital HDL, VHDL-AMS models are described with terminology which may be
unfamiliar to analog and mixed-signal designers. Model definitions which will be used throughout
this book are:
Structural Model - A structural model in VHDL-AMS is any model that is created by
connecting combinations of existing models together in such a way as to perform the
desired function. For MAST and SPICE users, a structural model is equivalent to a
macromodel.
Behavioral Model - A behavioral model in VHDL-AMS is considered to be a model
whose behavior is described using the features of the language itselfnot by simply
connecting pre-existing models together. A behavioral model may also include existing
models, but not to the exclusion of having language-based functionality directly
incorporated into the model description.
Test Bench - A test bench in VHDL-AMS is the final combination of either structural
and/or behavioral models which constitute the system to be simulated, along with source
stimulus and optionally, measurements. A test bench in VHDL-AMS would be referred to
as a test circuit (or netlist) in MAST or SPICE.
38 Chapter 3VHDL-AMS Overview

3.2. VHDL-AMS Modeling Options
When a designer is in need of a new model, VHDL-AMS offers several options to develop it. Three
primary options are discussed in this section: parameterizing existing models, developing structural
models, and developing behavioral models.
A. Parameterizing Existing Models
Model parameterization is possible when there is a generic solution available (i.e. an adequate base
model already exists). All the user has to do is supply model parameters to turn this generic model
into a specific solution.
For example, suppose we want a basic op amp model which accounts for input offset voltage, V
os
.
If input offset voltage is already part of the existing model as shown in Figure 3.2-1, then we would
parameterize the model by specifying the desired input offset voltage value.
Note that in parameterizing the model we have in no way changed the underlying topology of the
op amp. The general relationship between models and model parameters is shown below:
As an example, we will take a simple op amp template and parameterize it for use as an OP27. The
OP27 data sheet information that we are interested in is shown next:
OP27A/E Datasheet Specifications (Typical)
Input Offset Voltage (V
os
) = 10uV
Slew Rate (SR) = 2.8 V/us
Open Loop Output Resistance (R
o
) = 70 ohms
DC Supply Current (I
p
) = 3mA
Open Loop Gain (A) = 1.8 Million
Figure 3.2-1. Op amp model that includes input offset voltage.
V
OS
User speci fi es a value for V
OS
A Generic
Model
Model
Parameter
A Specific
Device
Values
VHDL-AMS Modeling Options 39


Unity Gain Bandwidth (f
1
) = p
1
* A = 9MHz (p
1
= 5Hz)
Second Break Frequency (p
2
) = 17.3Mhz
1
In VHDL-AMS, these parameters can easily be added to the op amp model using a generic map. A
generic map is used as part of a statement that creates an instance of a model that permits model
characteristics to be specified. For the OP27, the generic map declaration would be:
generic map (f1 => 9.0e+6,
p2 => 17.3e+6,
sr => 2.8,
A => 1.8e6,
vos => 10.0e-6,
ip => 3.0e-3,
rout => 70.0)
This declaration is made in the model entity (entities are discussed in Section C). The arguments are
passed directly into the op amp model, which then behaves as an OP27. The arrow notation (=>) in
the example associates a value on the right side with a parameter on the left side.
B. Structural Modeling (Macromodeling)
Structural modeling in VHDL-AMS is similar to macromodeling in MAST (and SPICE). A
structural model is a group of components connected together to make some new function. In
actuality, a structural model is just a circuit description that has been encapsulated for use as a
single component.
To understand structural modeling in VHDL-AMS, it may help to start with a simple circuit
description. Consider the following circuit:
1. Calculated using the formula () = -tan
-1
(f/p
1
) - tan
-1
(f/p
2
) and solving for p
2
.
p
m
capacitor.c1
inductor.l1 resistor.r1
x
m
m
p
p in out
1.0e-3
1.0e+3
1.0e-6
Figure 3.2-2. Resistor, capacitor, and inductor circuit description.
40 Chapter 3VHDL-AMS Overview

In Figure 3.2-2, squares represent component terminals (p and m are terminal names), and dots
represent connection pointscircuit nodes (in, out, and x are node names). The text-based
description of this symbolic circuit representation would be:
This structural description is interpreted as follows:
Resistor instance r1: The terminals p and m are connected to nodes x and out, respectively. A
nominal resistance value of 1k is passed into the template argument rnom. The shared node, x,
connects terminal p of the resistor to terminal m of the inductor.
Inductor instance l1: The p terminal is connected to node in; the m terminal connected to node x. An
inductance value of 1mH is assigned to the model argument lnom.
Capacitor instance c1: The terminals p and m are connected to nodes in and out, respectively. A
capacitance value of 1uF is passed into the template and assigned to the argument cnom.
Example: Structurally Modeled Op Amp
We will first explore structural modeling with the op amp we parameterized in the previous section.
In this case, let us assume we only have access to an op amp model that does not include input
Figure 3.2-3. Text-based description for resistor, capacitor, and inductor circuit.
r1 : entity work.resistor generic map (rnom => 1.0e+3)
port map ( p => x,
m => out);
l1 : entity work.inductor generic map (lnom => 1.0e-3)
port map ( p => in,
m => x);
c1 : entity work.capacitor generic map (cnom => 1.0e-6)
port map ( p => in,
m => out);
VHDL-AMS Modeling Options 41


offset voltage, V
os
. We will need to add this feature to the model ourselves. This structural
modeling approach is shown graphically in Figure 3.2-4.
In Figure 3.2-4, everything inside the dashed box represents the op amp without input offset
voltage capability. Connections outside the box show how we add the desired functionality (note
that the terminal names inside the box can be different from the node names outside the box). In
essence, we create a structural architecture which connects a voltage source in series with the
non-inverting terminal of the op amp, inp (architectures are discussed in Section C). This
architecture can then be used like any other model architecture. The resulting structural architecture
for this op amp is:
begin
op_no_vos1 : entity work.op_no_vos
port map (inp => n_offset,
inm => n_inm,
out => n_out,
vcc => vcc,
vee => vee );
v1 : entity work.Vsource_dc
generic map (dc_value => vos)
port map (p => n_input,
m => n_offset);
end architecture structural;
The node n_offset is used to connect the inp terminal of the op amp to the m terminal of the voltage
source. To use this structural architecture as a model, use the following entity:
use work.electrical_systems.all;
entity op_vos is
generic (
vos : real := 3.0E-6);
port ( terminal
V
OS
V
OS
i s not par t of the model
exi sti ng op amp model
We add V
OS
vcc
vee
vcc
vee
out n_out
i nm
i np n_offset
n_i nm
n_i nput
Figure 3.2-4. Op amp model without input offset voltage included
(voltage source added externally).
42 Chapter 3VHDL-AMS Overview

n_input, -- Input plus pin
n_inm, -- Input minus pin
n_out, -- Output pin
vcc, -- Plus voltage supply
vee : electrical); -- Minus voltage supply
end entity op_vos;
Note that the input offset voltage argument has been defined as V
os
, and how it appears in the
generic map of the architecture as well as in the entity. This way, the user can define a value for V
os
in the entity, and it will be passed down to the voltage source. Now, this structural model can be
used like any other VHDL-AMS model.
This type of model building is easily accomplished at the schematic-entry level. The purpose of this
example is to give some "behind the scenes" insight into the structural modeling process.
Example: Structurally Modeled VCVS with Input Resistance
Another structural modeling example would be a voltage-controlled voltage source (VCVS) with
input resistance. Figure 3.2-5 represents a standard VCVS model without input resistance. Figure
3.2-6 illustrates a structural model that combines the standard VCVS model with a resistor model
to achieve the new function.
To highlight the model changes, the terminal names of the modified VCVS of Figure 3.2-6 have the
added suffix, _r. The structural model is shown next.
VHDL-AMS Structural Model of VCVS
library ieee;
use ieee.electrical_systems.all;
entity Vsource_vc_r_s is
generic (
Figure 3.2-5. VCVS without input
resistance.
Figure 3.2-6. VCVS structural model with
resistance across input.
VCVS
vp
vm
p
m
vin vout VCVS
vp_r
vm_r
p_r
m_r
vin vout
VHDL-AMS Modeling Options 43


gain : real := 1.0;
rin : real := 1.0e+6);
port (
terminal vp_r : electrical;
terminal vm_r : electrical;
terminal p_r : electrical;
terminal m_r : electrical);
end entity Vsource_vc_r_s;
architecture structural of Vsource_vc_r_s is
begin
vcvs1 : entity work.Vsource_vc
generic map (gain => gain)
port map (vp => vp_r,
vm => vm_r,
p => p_r,
m => m_r);
r1 : entity work.resistor
generic map (rnom => rin)
port map (p => vp_r,
m => vm_r);
end architecture structural;
This model is fairly straightforward, but note how the structural model connections are made. In the
entity, four terminals are declared: vp_r, vm_r, p_r, and m_r (these terminals were renamed purely
for instructional purposes). These are the external terminals of the structural model. In the
architecture, these terminals correspond to node names. For example, node vp_r in the architecture
maps directly to terminal vp_r in the entity. This is how the connectivity between the architecture
definition and the outside world is established.
C. Behavioral Modeling
Now that we have discussed basic model parameterization and structural modeling approaches, we
will delve into the real power of VHDL-AMS: behavioral modeling. After looking at an example
model, we will discuss some important features regarding VHDL-AMS model conventions and
structure.
VHDL-AMS Behavioral Model of VCVS
use work.electrical_systems.all;
44 Chapter 3VHDL-AMS Overview

entity Vsource_vc_r is
generic (
rin : real := 1.0e+6;
gain : real := 1.0);
port (
terminal vp : electrical;
terminal vm : electrical;
terminal p : electrical;
terminal m : electrical);
end entity Vsource_vc_r;
architecture behavioral of Vsource_vc_r is
quantity vin across iin through vp to vm;
quantity vout across iout through p to m;
begin
iin == vin/rin;
vout == gain * vin;
end architecture behavioral;
VHDL-AMS models are organized into two main pieces: the entity and the architecture. The entity
is used to define the connection terminals (ports) of the model, as well as the user-supplied model
parameters. The structure of a VHDL-AMS entity is shown in Figure 3.2-7.
Figure 3.2-7. Behavioral model entity of VCVS with input resistance.
use work.electrical_systems.all;
entity Vsource_vc_r is
generic (
rin : real := 1.0e-6;
gain : real := 1.0);
port (
terminal vp : electrical;
terminal vm : electrical;
terminal p : electrical;
terminal m : electrical);
end entity Vsource_vc_r;
Parameter
declarations
Terminal
declarations
Entity
declaration
Initial
values
Terminal
type
Electrical
systems
package
definition
Entity
VHDL-AMS Modeling Options 45


The architecture defines the actual operation of the model. There may be multiple architectures for
a single entity, one of which is specified for use at compile time. The structure of a VHDL-AMS
architecture is shown in Figure 3.2-8
Modeling Utilities
VHDL-AMS models use information from several utility files. Among other things, utility files are
used to define packages for each energy domain. Different files will be required by a model
depending on what the model does. In Figure 3.2-7 for example, the electrical_systems package is
included in the model because the model has electrical terminals, and the quantities associated with
these terminals are defined in this package. Examples of some of the information contained in these
utility files are illustrated in Figure 3.2-9.
architecture behavioral of Vsource_vc_r is
quantity vin across iin through vp to vm;
quantity vout across iout through p to m;
begin
iin == vin/rin;
vout == gain * vin;
end architecture behavioral;
Architecture name Entity name
Across and
quantities
Simultaneous
statements
Architecture
through
Figure 3.2-8. Behavioral model architecture of VCVS with input resistance.
electrical_systems
mechanical_systems
math_real
nature electrical is
voltage across
current through
ground reference;
nature translational is
displacement across
force through
translational_ref reference;
constant MATH_E : REAL :=
2.71828_18284_59045_23536;
constant MATH_2_PI : REAL :=
6.28318_53071_79586_47692;
Figure 3.2-9. Example contents of various utility files (packages).
46 Chapter 3VHDL-AMS Overview

The electrical_systems and mechanical_systems packages define information regarding their
respective energy domains. The math_real package defines standard mathematical constants and
functions which can be used across all domains.
Packages are used in VHDL-AMS to group related declarations. The electrical_systems package,
for example, contains all declarations related to electrical type systems. The use clause is required
in order to be able to access declarations in packages. An example of including the use clause for
an electrical model would be:
use work.electrical_systems.all
The identifier work is the name of a predefined library into which all user models are entered by
default. The keyword all appearing after the package name means that all of the declarations in
the given package are to be imported into the model (as opposed to importing a restricted set of
declarations from the package).
D. VHDL-AMS Solvability Conditions
In order for a VHDL-AMS simulator to solve simultaneous equations, there must be one equation
for each through variable, free variable and out variable (to be discussed). In the example given in
Figure 3.2-8, there are two through variable declarations: one for iin, and the other for iout. This
means that there must be two simultaneous equations so that the simulator will have a matching
number of system equations and unknowns to solve.
As can be seen in Figure 3.2-8, the equations do not need to explicitly involve the through variable.
Since vout and iout are declared in the same branch (i.e. they are declared with respect to the same
terminals), an equation for vout is sufficient to give the simulator enough information with which to
solve for iout.
3.3. AMS-Extensions for VHDL
Now that we have seen the overall structure of a VHDL-AMS model, we will discuss many useful
Analog and Mixed-Signal (AMS) extensions to the VHDL language. The following extensions will
be covered:
1
Nature
Terminal
Quantity
Across
Through
Attributes and Implicit Quantities
Simultaneous Statements
1. Additional VHDL-AMS definitions can be found in the Glossary (Appendix C.)
AMS-Extensions for VHDL 47


Nature
A nature is a description of the types of values that are used to describe some physical domain. A
nature consists of an across aspect that represents the driving force in the domain (such as voltage,
temperature, or illuminance) and a through aspect that represents the force being driven in the
domain (such as current, heat flow, or optic flux). Additionally, each nature has a reference aspect
that names the reference node in the physical domain (such as ground for electrical systems).
For example, the nature declarations for electrical systems could be specified as:
nature electrical is
voltage across
current through
ground reference;
Terminal
A terminal is an analog connection point or pin that corresponds to a physical connection point in
some domain in the system. A terminal is defined to be of some nature that defines the properties of
the physical domain. In electrical terms, a terminal can be understood to be a physical connection
point at which voltage and current can be measured.
To declare four analog electrical connections for the VCVS model, we use the following:
port (
terminal vp : electrical;
terminal vm : electrical;
terminal p : electrical;
terminal m : electrical);
Which defines four analog pins, vp, vm, p, and m. These pins have an electrical nature specified, so
their across variable is voltage, and their through variable is current.
Optionally, like pin definitions can be given only once as follows:
port (
terminal vp, vm, p, m : electrical);
Each of these terminals have an electrical nature specified.
Quantity
A quantity is an unknown in a system of equations that describes the behavior of the analog aspects
of a model. The value of a quantity is determined by the simulator. The simulator solves the system
of equations formed by the simultaneous statements (equations) in the model and implicit equations
that result from conservation laws and the interconnection of the models.
For example, to declare a quantity of type real, the following entry could be used:
quantity v_tmp : real;
48 Chapter 3VHDL-AMS Overview

Across and Across Quantity
The keyword across follows an identifier in either a nature definition or a branch quantity
declaration. In the case of a nature definition, the identifier must name a floating point type that
represents the driving force of the nature; in electrical systems this represents voltage. In the case of
a branch quantity declaration, the identifier names a quantity that represents the driving force
between the two terminals named in the branch quantity declaration; in electrical systems an across
quantity represents the voltage between two terminals.
For example, to declare input and output across quantities, the following could be used:
quantity vin across vp to vm;
quantity vout across p to m;
Through and Through Quantity
The keyword through follows an identifier in either a nature definition or a branch quantity
declaration. In the case of a nature definition, the identifier must name a floating point type that
represents the driven force of the nature; in electrical systems this represents current. In the case of
a branch quantity declaration, the identifier names a quantity that represents the driven force
through that point in the system; in electrical systems a through quantity represents the current
through the connection point.
For example, to declare the through quantities for the VCVS model, we used the following:
quantity iin through vp to vm;
quantity iout through p to m;
Attributes and Implicit Quantities
VHDL-AMS includes several predefined attributes. Attributes allow properties to be assigned to
design objects. For example, the qdot attribute (read "q tick dot") can be used to determine the
derivative of quantity q. This derivative is itself a quantity. When attribute names denote quantities
which are not explicitly declared, they are often referred to as implicit quantities.
The following quantities are implicitly defined in VHDL-AMS:
qdot - The derivative of quantity q with respect to time
qinteg - The integral of quantity q over time from zero to current time
sslew(max_rising_slope, max_falling_slope) - A quantity that follows signal s, but its
derivative with respect to time is limited by the specified slopes. Default for
max_falling_slope is max_rising_slope; default for max_rising_slope is infinity
sramp(tr, tf) - A quantity that follows signal s, but with specified rise and fall times.
Default for tf is tr; default for tr is 0.0
Constants and Generics 49


qdelayed(T) - Quantity q delayed by T (ideal delay, T>=0)
qltf(num, den) - Laplace transfer function whose output is q
qztf(num, den, T, initial_delay) - Z-domain transfer function whose output is q
qzoh(T, initial_delay) - A sampled version of quantity q (zero-order hold)
There are also a number of attributes not used specifically for quantities. Attributes used in models
discussed in this book include:
ahigh(n) - Greatest value of the index range of dimension n
alow(n) - Least value of the index range of dimension n
arange(n) - Index range of dimension n
timage(x) - String representation of value x of type t
qabove(e) - Returns boolean FALSE when quantity q is below threshold e; returns
boolean TRUE when quantity q is above threshold e; an event occurs on signal qabove(e)
at the exact time of the threshold crossing
Simultaneous Statements
Simultaneous statements are used to express relationships between quantities in VHDL-AMS. In
Figure 3.2-8, simultaneous statements were used as follows:
iin == vin/rin;
vout == gain * vin;
The simulator must solve these equations simultaneously such that the stated relationships as well
as conservation laws are satisfied (subject to pre-defined tolerances). The expressions may involve
quantities, constants, literals, signals, and functions, but at least one quantity must appear in each
simultaneous statement. The order of the statements does not matter.
3.4. Constants and Generics
It is often necessary to declare constants in both VHDL and VHDL-AMS. Examples of how this is
done are given next.
50 Chapter 3VHDL-AMS Overview

Constant Declarations
Constants are typically declared using the following syntax:
constant identifier : subtype := expression;
For example, to declare a new constant t1, and initialize it to the reciprocal of frequency f1*2*, the
following model entry could be made:
constant t1 : real := 1.0 / (f1*math_2_pi);
Where t1 is the name of the constant; it is declared as subtype real; and its initial value is
1.0/(f1*math_2_pi).
Generic Declarations
Generics provide a method of passing parameters into the entity. The keyword generic occurs in
the definition of an entity and indicates that any instance of the model can be configured based on
the listed set of parameters. Typically, generic parameters are used to describe model
characteristics: in the case of an analog resistor model, resistance might be a generic model
characteristic that can be configured for each instance of the resistor. Generic parameters are
constants, and may not change during simulation; their values are determined when an instance is
created.
Take the behavioral VCVS model discussed previously. To declare the input resistance and gain
parameters as generics, we specify the following:
generic (
rin : real := 1.0e+6;
gain : real := 1.0);
Where rin and gain are both declared as type real. Note the similarity between the generic
declarations and constant declarations. The values for the generics can also be passed in from the
test bench which uses this model.
Test Benches 51


3.5. Test Benches
In this book, test benches are combinations of components which make up a circuit description, and
the stimulus that drives them
1
. Schematic test benches are generally referred to as the "top-level
schematics." Text test benches are simply referred to as test benches.
The top-level schematic of Figure 3.5-1 corresponds to the following text-based test bench:
use work.electrical_systems.all;
entity ex_opamp is
end ex_opamp;
architecture testbench of ex_opamp is
terminal vrt_gnd : electrical;
terminal ground : electrical;
terminal output : electrical;
terminal input : electrical;
begin
amp1 : entity work.opamp
port map ( inp => ground,
inm => vrt_gnd,
output => output,
ref => ground);
v1 : entity work.v_source
generic map (arguments and values)
port map ( p => input,
m => ground);
1. For digital designers, built-in measurements and tests are important aspects of test benches. In order to main-
tain parallel modeling development between VHDL-AMS and MAST, these aspects of test benches will not
be emphasized in this book.
0 - 5V periodic pulse
-
+
10k
10k
10meg
i nput
vrt_gnd
r1
r2
v1
p
m
p m
p m
p
m
i nm
i np
r3
Figure 3.5-1. Schematic-based test bench for an inverting op amp.
amp1
output
ref
output
52 Chapter 3VHDL-AMS Overview

r1 : entity work.resistor
generic map (rnom => 10.0e3)
port map ( p => input,
m => vrt_gnd);
r2 : entity work.resistor
generic map (rnom => 10.0e3)
port map ( p => output,
m => inm);
r3 : entity work.resistor
generic map (rnom => 10.0e6)
port map ( p => output,
m => ground);
end architecture testbench;
The test bench not only details the connectivity between the various models, it also allows generic
parameters to be specified which will be passed down to the individual models.
3.6. VHDL-AMS Model Listing Conventions
There are many VHDL-AMS models listed in this book. In order to make the models more
readable, certain keywords appear in bold. Keywords have predefined meaning in the
VHDL-AMS language. For example, the listing for the behavioral VCVS architecture was given
as:
architecture behavioral of Vsource_vc_r is
quantity vin across iin through vp to vm;
quantity vout across iout through p to m;
begin
iin == vin/rin;
vout == gain * vin;
end architecture behavioral;
In this listing, all of the words in bold are keywords.
3.7. Chapter Summary
This chapter has presented a brief overview of VHDL-AMS modeling options. Examples of
parameterizing existing models, creating structural models, and creating behavioral models were
presented. Limited discussions regarding VHDL-AMS language syntax and conventions have also
been presented (only as much as needed to illustrate some fundamentals of VHDL-AMS model
construction). References are given in Appendix D.


chapter 4
MAST Overview
This chapter presents a brief overview of MAST. As with the VHDL-AMS overview of the
previous chapter, this chapter is intended to familiarize the reader with MAST terminology and
concepts encountered throughout the bookit is not intended as a general MAST reference.
Appendix B offers supplemental MAST reference material and Appendix D lists MAST references.
To help make comparisons between MAST and VHDL-AMS easier, this chapter parallels the
previous chapter which introduced VHDL-AMS. Some of the material in these two chapters is
therefore repetitive.
Developed in 1985 for the Saber simulator, MAST has been the dominating mixed-sig-
nal/mixed-technology hardware description language for over a decade. It was created in an effort
to overcome the shortcomings of existing simulation tools, which offered little in the way of model-
ing options. MAST was introduced as the first mixed-signal modeling language, and remains a
leader in the field to this day. MAST is not an acronym.
4.1. MAST Model Terminology
MAST terminology is a little different from that of VHDL-AMS. The definitions which will be
used throughout this book for MAST-related discussions include:
Macromodel - A macromodel in MAST is any model that is created by connecting
combinations of existing models together in such a way as to perform the desired function.
For VHDL-AMS users, a macromodel is equivalent to a structural model.
Behavioral Model - A behavioral model in MAST is considered to be a model whose
behavior is described using the features of the language itselfnot by simply connecting
pre-existing models together. A behavioral model may also include existing models, but
not to the exclusion of having language-based functionality directly incorporated into the
model description.
Test Circuit - A test circuit in MAST (also referred to as a netlist) is the final combination
of macromodels and/or behavioral models which constitute the system to be simulated,
along with source stimulus. A test circuit or netlist in MAST may be referred to as a test
bench in VHDL-AMS.
54 Chapter 4MAST Overview

4.2. MAST Modeling Options
When a designer is in need of a new model, MAST offers several options to develop it. Three
primary options are discussed in this section: parameterizing existing models, developing
macromodels, and developing behavioral models.
A. Parameterizing Existing Models
Model parameterization is possible when there is a generic solution available (i.e. an adequate
model already exists). All the user has to do is supply model parameters to turn this generic model
into a specific solution.
Suppose we want a basic op amp with input offset voltage. If input offset voltage is already part of
the existing model as shown in Figure 4.2-1, then we would parameterize the model by specifying
the desired input offset voltage value.
Note that the underlying topology of the op amp has not been changed in any way.
The general relationship between models and model parameters is shown below:
As an example, we will take a simple op amp template and parameterize it for use as an OP27. The
OP27 data sheet information that we are interested in is specified as follows:
OP27A/E Datasheet Specifications (Typical)
Input Offset Voltage (V
os
) = 10uV
Slew Rate (SR) = 2.8 V/us
Open Loop Output Resistance (R
o
) = 70 ohms
DC Supply Current (I
p
) = 3mA
Open Loop Gain (A) = 1.8 Million
Figure 4.2-1. Op amp model that includes input offset voltage.
V
OS
User speci fi es a value for V
OS
A Generic
Model
Model
Parameter
A Specific
Device
Values
MAST Modeling Options 55


Unity Gain Bandwidth (f
1
) = p
1
* A = 9MHz (p
1
= 5Hz)
Second Break frequency (p
2
) = 17.3Mhz
1
There are several methods available to parameterize existing MAST models. One method that can
be used to include parameters is to specify arguments at the netlist level.
For the OP27, a netlist entry would look like:
op1.1 out:out inm:vrt_gnd inp:0 vcc:vcc vee:vee = \
a=1.8meg, f1=9meg, sr=2.8, p2=17.3meg, ip=3m, vos=10u, rout=70
In this case, the netlist arguments are passed directly into the op amp template. This method of
model parameterization does have a limitation: the parameters must be specified each time the
model is used in the design. For this reason, and for models that have a large number of arguments,
it is often more economical to use another approach for model parameterization.
Here we would first create a separate file with the desired parameters:
op1..model arg_vals = (a=1.8meg, \ # open-loop voltage gain
f1 = 9meg, \ # gain-bandwidth product
p2 = 17.3meg, \ # 2nd pole
sr = 2.8, \ # slew rate
vos = 10u, \ # offset voltage
ip = 3m, \ # dc supply current
rout = 70) # output resistance
The argument values are stored in the variable arg_vals.
We will call the file that defines these arguments op27_args.sin.
The op1..model operator is referred to as an argument definition, argdef.
2
Argdefs allow groups of
parameters to be passed between similar templates. For example, the arg_vals variable can be
passed to the op1 template because the op1 template has a model argument defined with the same
arguments. The argument values will be assigned to the corresponding arguments in the op1
template.
Actual netlist entries for this newly-parameterized OP27 might be as follows:
<op27_args.sin # Include the op27_args.sin file in the netlist
3
...
op1.1 out:out inm:vrt_gnd inp:0 vcc:vcc vee:vee = model = arg_vals
1. Calculated using the formula () = -tan
-1
(f/p
1
) - tan
-1
(f/p
2
) and solving for p
2
.
2. For in-depth coverage of argdefs, please reference the Guide to Writing Templates and MAST Reference
Manual.
3. Include files can be specified at the schematic entry level (no netlist editing is required).
56 Chapter 4MAST Overview

This netlist entry passes the desired parameters to the template, op1.sin using a variable called
model, which declares a group of related variables. In this case, the related variables include a, f
1
,
sr, p
2
, i
p
, v
os
, and r
out
.
A variable such as model, that declares a group of related variables, is referred to as a structure.
Structures are useful to help organize and simplify complex models.
B. Macromodeling (Structural Modeling)
Circuits and systems are described in MAST with netlists (net-work list-ings). A netlist is a
description of a design that lists each component in the design, its values and how it is
interconnected with other components. A macromodel is a group of components connected
together to make some new function. In actuality, a macromodel is just a netlist that has been
encapsulated to be used as a single component.
To understand macromodeling in MAST, it may help to start with a simple circuit description.
Consider the following circuit:
In Figure 4.2-2, squares represent component pins (p and m are pin names), and dots represent
connection pointscircuit nodes (in, out, and x are net names). The netlist, or description of this
symbolic circuit representation would be:
This is interpreted as follows:
Resistor instance r1: The pins p and m are connected to nodes x and out, respectively. A nominal
resistance value of 1k is passed into the template argument rnom. The shared node, x, connects
pin p of the resistor to pin m of the inductor.
Figure 4.2-2. Resistor, capacitor, and inductor circuit.
p
m
capacitor.c1
inductor.l1 resistor.r1
x
m
m
p
p in out
1m
1k
1u
Figure 4.2-3. Netlist for resistor, capacitor, and inductor circuit.
inductor.i1 p:in m:x = lnom = 1m
resistor.r1 p:x m:out = rnom = 1k
capacitor.c1 p:in m:out = cnom = 1u
MAST Modeling Options 57


Inductor instance l1: The p pin is connected to node in; the m pin connected to node x. An
inductance value of 1mH is assigned to the model argument lnom.
Capacitor instance c1: The pins p and m are connected to nodes in and out, respectively. A
capacitance value of 1uF is passed into the template and assigned to the argument cnom.
Netlist Statement Syntax
The general syntax for a MAST netlist line is as follows:
template_name.instance_name connection_points [=argument_assignments]
Using the inductor entry from Figure 4.2-3 as an example:
template_name is the name of the template (inductor).
instance_name (also known as refdes (reference designator)) is an identifier which for this
template is unique in this netlist (l1).
connection_point_assignments assign the templates connection points to the netlists
nodes (p:in m:x).
argument_assignments is a comma (,) separated list of expressions which assigns values
to the templates arguments. (lnom = 1m).
Any legal MAST expression of parameters and constants may be used as argument
assignments.

For example,
r.in p:vin m:vout = rnom = 100
r.load p:vout m:0 = rnom = res * sin(math_pi/3)
General Template Conventions
The basic unit of system description in MAST is the template. Templates are synonymous
to models. Templates may contain netlists, formulae, algorithms, or any combination of
these.
Typically, each template is contained in its own file that has the same name as the template
(as it appears in the header). However, the file name must be followed by a .sin extension
so that the simulator will automatically find and include the template whenever it finds a
reference to it in a netlist. For example, the file containing the resistor template should be
named resistor.sin.
When possible, it is a good idea to define connection points in the header of a template
such that the inputs (if any) to the model are specified first, followed by the outputs. This
is not absolutely necessary, but it helps make the templates more intuitive for most people.
MAST can be used to create continuous analog, event-driven, and data flow models.
Generally, you can look at the declaration of connection points in a template to determine
58 Chapter 4MAST Overview

which type of model it is. The units.sin file specifies units for several types of connection
points. For example, the word electrical preceding a connection point name means that it
is a pin-type connection with current and voltage as through and across variables,
respectively.
Prefix Abbreviations
A variety of prefix abbreviations are available to express multipliers, including the following:
a atto 10
-18
f femto 10
-15
p pico 10
-12
n nano 10
-9
u (or mu) micro 10
-6
m milli 10
-3
k kilo 10
3
meg (or me) mega 10
6
g giga 10
9
t tera 10
12

Numbers can also be expressed as a constant immediately followed by an appropriate abbreviation
(do not include units).
For example, the following are equivalent:
x = 4.2u x = 4.2e-6
The following are illegal specifications for numbers:
x = 4.2 u (space not allowed between number and abbreviation)
x = 4.2uA (units not allowed)
Example: Macromodeled Op Amp
We will first explore macromodeling with the op amp example we looked at for model parameter-
ization. In this case, let us assume we only have access to an op amp model that does not include
MAST Modeling Options 59


V
os
. We will need to add this feature to the model ourselves. This macromodeling approach is
shown graphically in Figure 4.2-4.
As shown in Figure 4.2-4, everything inside the dashed box represents the op amp without input
offset voltage capability. Connections outside the box show how we add the desired functionality
(note that the terminal names inside the box can be different from the node names outside the box).
In essence, we create a netlist which connects a voltage source in series with the non-inverting pin
of the op amp, inp. This netlist can then be used as a model itself.
Resulting netlist:
op_no_vos.1 inp:n_offset inm:n_inm out:n_out vcc:vcc vee:vee
v.1 p:n_input m:n_offset = dc = 3u
The node n_offset is used to connect the inp pin of the op amp to the m pin of the voltage source. To
transform this netlist into a reusable template, we convert it to the following form:
template op_vos n_input n_inm n_out vcc vee
1
= vos
number vos = 0 # default offset
{
op_no_vos.1 inp:n_offset inm:n_inm out:n_out vcc:vcc vee:vee
v.1 p:n_input m:n_offset = dc = vos
}
Note that the input offset voltage argument has been defined as V
os
, and how it appears in the
netlist portion of the macromodel as well as the header. This way, the user can define a value for
V
os
when using the macromodel (called op_vos), and it will be passed down into the voltage
source. Now, this macromodel template can be used like any other MAST template.
This type of model building is easily accomplished at the schematic-entry level. The purpose of this
example is to give some "behind the scenes" insight into the macromodeling process.
1. Note that pin names may be defined by the user.
Figure 4.2-4. Op amp model without input offset voltage
included (voltage source added externally).
V
OS
V
OS
i s not par t of the model
exi sti ng op amp model
We add V
OS
vcc
vee
vcc
vee
out n_out
i nm
i np n_offset
n_i nm
n_i nput
60 Chapter 4MAST Overview

Example: Macromodeled VCVS with Input Resistance
Another macromodel example would be a voltage-controlled voltage source (VCVS) with input
resistance. Figure 4.2-5 shows a standard VCVS symbol without input resistance. Figure 4.2-6
illustrates a macromodel that combines the standard VCVS template with a resistor template to
achieve the new function.
The macromodel MAST template is shown next.
MAST Macromodel of VCVS
# MacroModel VCVS implementation
# Use standard vcvs, with a resistor parallel to inputs
template vcvs_macro vp_r vm_r p_r m_r = gain, rin
electrical vp_r, vm_r, p_r, m_r
number gain, rin
# Define macromodel connections (internal to this template)
{
vcvs.1 vp:vp_r vm:vm_r p:p_r m:m_r = k = gain
r.in p:vp_r m:vm_r = rnom = rin
}
This model is fairly straightforward, but note how the macromodel connections are made. In the
template header, four pins are declared: vp_r, vm_r, p_r, and m_r (these pins were renamed purely
for instructional purposes). These are the external pins of the macromodel. In the netlist section
within the macromodel, these pins correspond to node names. For example, node vp_r in the
internal netlist maps directly to pin vp_r in the macromodel template heading. This is how the
connectivity between the internal macromodel definition and the outside world is established.
Figure 4.2-5. VCVS without input
resistance.
Figure 4.2-6. VCVS macromodel with
resistance across input.
VCVS
vp
vm
p
m
vin vout VCVS
vp_r
vm_r
p_r
m_r
vin vout
MAST Modeling Options 61


C. Behavioral Modeling
Now that we have discussed basic model parameterization and macromodeling approaches, we will
delve into the real power of MAST: behavioral modeling. After looking at an example model, we
will discuss some important features regarding MAST template conventions and structure.
MAST Behavioral VCVS
# VCVS behavioral template with input resistance
template vcvs_rin vp vm p m = gain, rin
electrical vp, vm, p, m
number gain, rin
{
branch vin=v(vp, vm), iin=i(vp->vm)
branch vout=v(p, m), iout=i(p->m)
equations {
iin = vin/rin # Add input resistance equation
vout = gain*vin
}
}
The structure of this model is shown in Figure 4.2-7.
62 Chapter 4MAST Overview

Anatomy of the VCVS Model:
MAST templates are divided into two main parts: template header and template body. The template
header encompasses the first three lines in Figure 4.2-7. The first line is called the header, which is
where the template name, pin names, and input arguments are defined. The second line is where the
template pin types are definedelectrical type pins imply that current is the through variable and
voltage is the across variable. The third line defines the type of the input arguments being passed
into the templatein this case, the input arguments can be simple numbers, but not arrays, strings,
or complex data structures.
The template body is enclosed in braces { }. The first two lines of the body of the template are
branch declarations, which assign variables to the voltage and current values at the templates pins.
In this example, vin is declared to be the voltage across pins vp and vm; iin is declared to be the
current flowing through pins vp and vm. Vout is declared to be the voltage across pins p and m; iout
is declared to be the current flowing through pins p and m.
The following line in the template body signifies the beginning of the Equations section. MAST
templates are often divided into various structured sections in order to help organize and debug
them, particularly when the templates are large and complex. The Equations section is where
conservation laws are enforced in MAST templates.
template vcvs_rin vp vm v m = gain, rin
electrical vp, vm, p, m
number gain, rin
{
branch vin=v(vp, vm), iin=(vp->vm)
branch vout=v(p, m), iout=(p->m)
equations {
iin = vin/rin
vout = gain*vin
}
}
vcvs_rin.sin
file name
template name connection points
arguments header
header
equations
template
declarations
section
body
branch variable
declarations
Figure 4.2-7. MAST model of a voltage-controlled voltage source.
MAST Structure and Conventions 63


Inside the Equations section, two equations appear: one equation specifies how much current the
VCVS should draw from whatever is sourcing itin this case, this current is defined by Ohms
law. The other equation specifies the relationship between input and output voltage. Together, these
two equations define the core operation of the model. The Equations section, as well as other
template sections will be discussed in further detail in later chapters.
D. MAST Solvability Conditions
In MAST, there must be one equation in the Equations section for each through variable, declared
var or output (vars and outputs will be discussed in later chapters). In the example given in Figure
4.2-7, there are two branch declarations: one for iin, and the other for iout. This means that there
must be two equations in the Equations section so that the simulator will have a matching number
of system unknowns and system equations to solve.
As can be seen in Figure 4.2-7, the equations in the Equations section do not need to explicitly
involve the through variable. Since vout and iout are declared in the same branch, an equation for
vout is sufficient to give the simulator enough information with which to solve for iout.
4.3. MAST Structure and Conventions
A. MAST Conventions and Syntax
Now that we have seen a MAST behavioral model, a few words about MAST are in order.
General Description
The MAST modeling language is a high level language that has syntax rules somewhat like the C
programming language. It is a block-structured language, which means that logical programming
blocks start with a left brace ({) and end with a right brace (}). The language is case-insensitive.
Unlike other high level languages such as C and Pascal, statements do not have to end with a
semicolon (;). However, the semicolon is a valid end-of-statement character.
There are several line-continuation characters, including the following:
\ + - / * & | < > ( [ { = ,
Any line ending with one of these characters is assumed to continue on the next line. Otherwise, the
line is assumed to terminate. Most often the backslash (\) is used as a line continuation character,
even though another legal continuation character may be already present. This convention makes it
clear that line continuation is intended.
64 Chapter 4MAST Overview

For example,
op1..model arg_vals = (a=1.8meg, \
f1 = 9meg, \
p2 = 17.3meg, \
sr = 2.8, \
vos = 10u, \
ip = 3m, \
rout = 70)
Note the use of the backslashes as continuation characters. Even though the commas separating the
parameters could have been used for this purpose, the intention may not be clear to the model
reader.
Comments
The MAST language ignores blank lines, the pound sign (#), and any characters following the
pound sign to the end of that line. Thus, any text preceded by a pound sign is ignored to the end of
the line, which is useful for inserting comments. A comment can start anywhere within a line.
For example,
# This is a comment, along with everything else
# located at the right of a pound sign.
op1..model arg_vals = (a=1.8meg, \ # open-loop voltage gain
f1 = 9meg, \ # gain-bandwidth product
p2 = 17.3meg, \ # 2nd pole
sr = 2.8, \ # slew rate
vos = 10u, \ # offset voltage
ip = 3m, \ # dc supply current
rout = 70) # output resistance
The comments appearing after the backslashes have no effect on the subsequent new lines.
Identifiers
Identifiers are names for variables, templates, netlist nodes, reference designators, etc. They must
start with an alphabetic character or an underscore (_), followed by any mixture of alphabetic
characters, digits, and underscores. An identifier may have any number of characters, all of which
are significant.
A name of an identifier for a connection point can be an unsigned integer, although this usage is not
recommended because it restricts you to use an integer pin name only in the netlist section of a
template.
Examples of typical identifiers would be:
f1 = 9meg
_p2 = 17.3meg
MAST Structure and Conventions 65


However, the following identifiers are not allowed because they start with numbers:
1f = 9meg
2_p = 17.3meg
B. General MAST Template Structure
MAST templates are often structured into various sections. Each section serves a specific purpose,
an overview of which is given in Figure 4.3-1. These sections will be explored thoroughly as they
are required for specific modeling tasks.
template header
unit and pin_type definitions
header declarations
{
local declarations
parameters {
parameter assignments
}
netlist statements
when {
state assignments
}
values {
value assignments
}
control_section {
simulator-dependent control
}
equations {
equations describing behavior
}
}
Input/Output
Internal constants
(e.g. number, enum, stri ng)
Digital Section
STATE = f(state, val , var, number)
Analog/Digital Section
VAL = f(state, val , var, number)
Simulator Section
Not defi ni ng behavi or i n system,
but i nfo to/from si mul ator
Analog Section
Through variable = f(val , var,
number)
Figure 4.3-1. Overview of MAST template sections.
66 Chapter 4MAST Overview

Header
The header for a template file defines the name of the template, the names of its connection points,
and the names of the templates arguments used in a netlist entry. The header must be included in
any template that will called from another template; that is, any template except a top level
template.
The header includes the name of the template, the names of the connection points, and any
arguments associated with it.
Declarations
There are two sections that contain declarations: header declarations and local declarations. All
names (identifiers) must be defined before they can be used. These definitions are called
declarations. Keywords (names that are a required part of MAST statements) are defined by the
language and require no further declaration. A declaration tells the system the type to be associated
with the name, thus defining how it is to be used. Some declarations can also include the
assignment of an initial value.
The purpose of header declarations is to define to the system the names used in the header. The
local declarations define the names used in the rest of the templateit contains declarations for all
identifiers used inside the template.
The name of the template does not require a separate declaration; in fact, the header itself is the
declaration of the template name. The other names use in the header (names of connection points
and arguments) must be declared in the header declarations.
Declarations of connection points must define their type (pin, ref, var, or state). Declarations of
arguments define the type of each argument. Argument types fall into one of three categories:
simple, composite, or arrays of simple/composite.
The Parameters Section
The Parameters section is used to manipulate parameters. It can be used to add error checking to
templates by testing the input values of arguments for validity and to model statistical distributions
for Monte Carlo analyses.
Parameters and arguments are similar. They can have the same types of declarations, but
parameters are declared locally in a template, while arguments are declared in the header
declarations section and their values can be passed into a template by using a netlist statement.
Only parameters may be changed in the Parameters section.
The statements in the Parameters section are evaluated as follows:
Once just after the input file is read
Each time the Saber alter command is used (causing a temporary alteration of a template
argument)
MAST Structure and Conventions 67


For each run of a Monte Carlo simulation
Parameters may depend only upon other parameters, arguments and constants.
Assignment statements, expressions, and conditional statements (if-else) are allowed in this section.
Mathematical expressions and intrinsic functions are allowed in this section with the exception of
d_by_dt (the derivative function) and the delay function. Calls to foreign subroutines (routines
written in a programming language such as Fortran or C, for example) are allowed.
The Netlist Section
The Netlist section consists of one ore more netlist statements that call other templates. These
statements define elements of the system that are instances of the template(s) being called. The
Netlist section is required only in templates that make reference to other templates; in fact, it is an
implementation of another level of hierarchy.
The form of a netlist statement is as follows:
templatename.refdes connection_pt_list [= argument_assignments]
The templatename is the name of the template being called, as identified in its header.
The refdes is the reference designator, a unique name for that element of the system.
The connection_pt_list is a list of the nodes in the system to which the connection points of the
template are connected. There is a direct correspondence between the number of connection points
and the number of nodes. A template for an element such as a resistor, with two connection points,
must be connected to two nodes of the system.
The argument_assignment is the assignment of values to the arguments of the template.
When Statements
When statements are used in discrete time simulation. You can use them in describing digital
behavior, in testing for analog waveforms crossing a threshold, and in scheduling events. When
statements also make it possible to construct state machines, which perform certain actions
depending upon preceding system states, or upon the values of digital gates.
Conditional statements are allowed in these sections, as well as mathematical expressions and
intrinsic functions, except for the d_by_dt, delay, and random intrinsic functions. Foreign
subroutines are also allowed. When statements are evaluated by the simulator as needed.
Values Section
The Values section of the template is used to define variables that are to be extracted during
post-processing. It also can be used to transform variables into a form needed in the Equations
section, including the use of foreign subroutines. The Values section is helpful in clarifying the
template and making it more maintainable.
68 Chapter 4MAST Overview

For example, we may wish to define a val that will allow us to extract the power (e.g.,
voltagecurrent) of a resistor when we are analyzing the results of the simulation. We would add the
following statement to the Values section of our resistor template:
power_res = v_res * i_res
If power_res is not needed for solution of the system matrix, it is evaluated but not used during the
simulation. This makes it available for post-processing, without increasing the simulation run time.
Conditional statements are allowed in this section, as well as mathematical expressions and
intrinsic functions, except for the d_by_dt, delay and random intrinsic functions. Foreign
subroutines are also allowed.
Control Section
The Control section declares specific information to the simulator that does not fit in other sections
of the templateit is not used in all models. The information that the Control section provides is
specific to the system being analyzed.
The Control section can contain the following types of statements:
Conditional statements that can collapse two nodes into a single node, thereby speeding up
the simulation. However, once nodes are collapsed during a simulation, they cannot be
uncollapsed without exiting and re-entering the simulator.
Statements that declare groupings of nonlinear values for the purpose of piecewise linear
evaluation, defining the independent variables for each group
Statements that declare the sample points for each independent variable used in the
piecewise linear set
Statements that declare Newton steps for the specified independent variables
Statements that describe small-signal noise sources
Equations Section
The Equations section describes the analog characteristics at the terminals of the element the
template is defining. In effect, this section defines the effect of the element on the rest of the
system.
Statements in the Equations section indicate the relationship of the analog characteristics of special
variables to variables in the rest of the system. Mathematical expressions and intrinsic functions are
allowed in this section. The intrinsic functions d_by_dt and delay are allowed as well, but may not
be nested. The random function is not allowed.
Test Circuits 69


4.4. Test Circuits
Test circuits are combinations of components which make up a circuit description, and the stimulus
that drives them. Schematic test circuits are generally referred to as the "top-level schematics."
Circuits in text form without graphical representation are generally referred to as netlists.
The following netlist corresponds to the top-level schematic of Figure 4.4-1:
v_source.v1 p:in m:0 = arguments and values
resistor.r1 p:in m:vrt_gnd = rnom = 10k
resistor.r2 p:vrt_gnd m:out = rnom = 10k
resistor.r3 p:out m:0 = rnom = 10meg
opamp.amp1 inm:vrt_gnd inp:0 out:out ref:0
4.5. Chapter Summary
This chapter has presented a brief overview of MAST modeling options. Examples of
parameterizing existing models, creating macromodels, and creating behavioral models were
presented. Limited discussions regarding MAST language syntax and conventions have also been
presented. Further information can be found in Appendix B; references are given in Appendix D.
0 - 5V periodic pulse
-
+
10k
10k
10meg
i n
vrt_gnd
r1
r2
v1
p
m
p m
p m
p
m
i nm
i np
r3
Figure 4.4-1. Schematic-based test circuit for inverting op amp.
amp1
out out
ref
70 Chapter 4MAST Overview



chapter 5
Introduction to Conserved System Modeling
This chapter focuses on analog conservation-based models that are electrical in nature.
Non-conserved models as well as mixed-signal and mixed-technology models will be discussed in
later chapters.
5.1. Simulation Models
Computer simulation is performed on models, or collections of models connected together in some
meaningful way. In this sense, a computer model can represent an entire system of interconnected
"component" models. It can also represent the individual components themselvesthe building
blocks of the system.
For our purposes, the final, interconnected groups of components loaded into the simulator will be
referred to as a system, network, or circuit. The components themselves, regardless of their level of
abstraction, will simply be referred to as models.
A. Across and Through Variables
To effectively use the general conservation laws which govern all technologies, two types of
variables have been standardized for use with VHDL-AMS and MAST: through variables and
across variables. Conservation laws are enforced on through variables, which can also be thought
of as dependent variables. Across variables can be thought of as independent variables, values
which the simulator somehow provides in order to calculate the through variables. In VHDL-AMS
and MAST, model equations can be expressed to solve for either the across or through variables
(Ohms law can be stated as v = i*r or i = v/r). Eventually, however, the simulator will structure any
relationship (like Ohms law) such that the through variable (current) is always conserved.
This convention is due to the use of nodal-like solution algorithms at the core of most simulators.
For nodal-like simulators, conservation laws are enforced by summing the through variables at
each node to zero (unlike mesh-like analysis, where the sum of the across variables around a loop
must equal zero).
VHDL-AMS and MAST are general purpose modeling languages that apply to both electrical and
non-electrical systems. For electrical systems, nodal-like analysis is used by the simulator with
voltage and current as the variables of interest. Other types of systems can also be solved using
nodal-like analysis, but their variables will differ to be suitable to the given technology.
72 Chapter 5Introduction to Conserved System Modeling

Table 5.1-1 lists various technologies and their respective through and across variables.
B. Conservation Laws
The laws governing the variables in Table 5.1-1 are enforced at each node of the system to be
simulated as follows:
current = 0 (Electrical)
torque = 0 (Rotational Mechanical)
force = 0 (Translational Mechanical)
flux = 0 (Magnetic)
flow rate = 0 (Hydraulic)
power = 0 (Thermal)
luminous flux = 0 (Light)
The next few chapters of the book will deal exclusively with electrical-based models.
Mixed-technology models are discussed in Chapter 11: Hydraulic and Mechanical Modeling.
5.2. Defining the Model
The first step to developing a new model is to explicitly define how the model is supposed to
behave, including all relevant parameters that will govern the models behavior. For example, if
you want to create a resistor model, what exactly do you mean by resistor model? Do you want a
model that simply enforces Ohms law, or does the model also need to account for temperature
differences in the environment? Would this temperature dependency need to be static, dynamic, or
both? What about self-heating? Does resistance tolerance need to be taken into account? What if
your model is used outside its Safe Operating Area (SOA)? Should it warn the user if a value of
Technology Through Variable Across Variable
Electrical current voltage
Rotational torque angular velocity
Mechanical force translational velocity
Magnetic flux magneto-motive force
Fluidic (Hydraulic) flow rate pressure
Thermal heat flow rate (power) temperature
Light luminous flux illuminance
Table 5.1-1. Technology-specific across and through variables.
Electrical Building BlocksIdeal 73


zero, or a negative number for resistance is entered? Should the user even enter a value for
resistance, or should this value be calculated by the model based on physical IC parameters?
What starts off as a very simple model can become very complex when these types of questions are
taken into account. The modelers first responsibility is to define the scope of the model and
determine what behaviors will and will not be modeled.
5.3. Electrical Building BlocksIdeal
For this section, we will confine our modeling efforts to simple models that only take into account
the basic characteristic equation(s) of the device. Several simple models will be discussed and
implemented in both VHDL-AMS and MAST.
A. Constant Current Source
VHDL-AMS DC Current Source
use work.electrical_systems.all;
entity Isource_dc is
generic (
dc_value : real); -- DC value
port (
terminal p, -- positive pin
m : electrical); -- minus pin
end entity Isource_dc;
architecture simple of Isource_dc is
quantity i through p to m;
begin
i == dc_value;
end architecture simple;
p m
cur
The voltage across this device is
determined by the simulator. The
current through it is explicitly defined
by the user:
cur cons t tan =
74 Chapter 5Introduction to Conserved System Modeling

This model is called Isource_dc.vhd. There are two electrical connections, p and m. The current i, is
declared as a quantity which is set equal to the value of the dc_value argument. The architecture is
called simple.
MAST DC Current Source
template Isource_dc p m = dc_value
electrical p, m
number dc_value
{
branch i = i(p->m)
equations {
i = dc_value
}
}
The MAST implementation of this current source is called Isource_dc.sin. There are two electrical
connection pins, p and m. The desired current is passed in through the argument dc_value to the
branch variable, i.
B. Constant Voltage Source
VHDL-AMS DC Voltage Source
use work.electrical_systems.all;
p m
i
pm
+ v
pm
-
The current through this device is
determined by the simulator. The voltage
across it is explicitly defined by the user:
v
pm
cons t tan =
Electrical Building BlocksIdeal 75


entity Vsource_dc is
generic (
dc_value : real); -- DC value
port (
terminal p, -- positive pin
m : electrical); -- minus pin
end entity Vsource_dc;
architecture simple of Vsource_dc is
quantity v across i through p to m;
begin
v == dc_value;
end architecture simple;
The voltage source model, Vsource_dc.vhd, is very similar to the current source model. Note that
unlike the current source model, this model also has a quantity declaration for the voltage across the
terminals. Since voltage is an across variable, an additional equation was not needed in the simple
architecture.
MAST DC Voltage Source
template Vsource_dc p m = dc_value
electrical p, m
number dc_value
{
branch v=v(p,m), i=i(p->m)
equations {
v = dc_value
}
}
Unlike the MAST current source model, the voltage source model has an additional branch
declaration for the voltage, v. Since voltage is an across variable, an additional equation was not
needed in the Equations section.
76 Chapter 5Introduction to Conserved System Modeling

C. Linear Resistor
VHDL-AMS Linear Resistor
use work.electrical_systems.all;
entity resistor is
generic (
rnom : real); -- resistance value
port (
terminal p, -- positive pin
m : electrical); -- minus pin
end entity resistor;
architecture simple of resistor is
quantity v across i through p to m;
begin
i == v / rnom;
end architecture simple;
The VHDL-AMS resistor model is called resistor.vhd. Both the voltage across the device (v) and
the current through it (i) are declared as quantities, and Ohms law is implemented with them.
MAST Linear Resistor
template resistor p m = rnom
electrical p, m
number rnom
{
The voltage across this device is determined
by the simulator. The current through it is
governed by the characteristic equation:
i
r
v
r
rnom
------------- =
p
m
i
r
rnom
+ v
r
-
Electrical Building BlocksIdeal 77


branch v=v(p, m), i=i(p->m)
equations {
i = v/rnom
}
}
The MAST resistor model is called resistor.sin. Again, both the voltage across the device (v) and
the current through it (i) are declared as branch variables, and Ohms law is implemented using
them.
D. Linear Capacitor
VHDL-AMS Linear Capacitor
use work.electrical_systems.all;
entity capacitor is
generic (
cnom : real); -- capacitance value
port (
terminal p, -- positive pin
m : electrical); -- minus pin
end entity capacitor;
architecture simple1 of capacitor is
quantity v across i through p to m;
begin
i == cnom * v'dot;
end architecture simple1;
The voltage across this device is determined
by the simulator. The current through it is
governed by the characteristic equation:
i
c
cnom
t d
dv
c
=
p
m
i
c
cnom
+ v
c
-
78 Chapter 5Introduction to Conserved System Modeling

The capacitor model is called capacitor.vhd. The simple1 architecture uses the implicit quantity,
vdot. vdot denotes differentiation on the quantity v.
MAST Linear Capacitor
template capacitor p m = cnom
electrical p, m
number cnom
{
branch v=v(p, m), i=i(p->m)
equations {
i = d_by_dt(cnom*v)
}
}
This model uses the MAST intrinsic mathematical function d_by_dt. The d_by_dt function
differentiates whatever is contained within the parentheses directly following it. Note that
multiplying anything by this function is prohibited, which is why the constant cnom is also inside
the parentheses.
E. Linear Inductor
VHDL-AMS Linear Inductor
use work.electrical_systems.all;
The current through this device is
determined by the simulator. The
voltage across it is governed by the
characteristic equation:
v
L
ind
t d
di
L
=
p m
i
L
ind
+ v
L
-
Electrical Building BlocksIdeal 79


entity inductor is
generic (
lnom : real); -- inductance value
port (
terminal p, -- positive pin
m : electrical); -- minus pin
end entity inductor;
architecture simple of inductor is
quantity v across i through p to m;
begin
v == lnom * i'dot;
end architecture simple;
The VHDL-AMS inductor model, inductor.vhd is very similar to the capacitor model. Note how the
voltage is solved in the model by taking the derivative of the current; whereas in the capacitor
model, this was reversed. It is the job of the VHDL-AMS simulator to ensure that the through
variable is conserved, regardless of how the relationships are expressed in the model.
MAST Linear Inductor
template inductor p m = lnom
electrical p, m
number lnom
{
branch v=v(p, m), i=i(p->m)
equations {
v = d_by_dt(lnom*i)
}
}
The MAST inductor model, inductor.sin is also similar to the capacitor model. Again note how the
voltage is solved for in the model by taking the derivative of the current; whereas in the capacitor
model, this was reversed. It is the job of the MAST simulator to ensure that the through variable is
conserved, regardless of how the relationships are expressed in the model.
80 Chapter 5Introduction to Conserved System Modeling

F. Voltage-Controlled Current Source (VCCS)
VHDL-AMS Voltage-Controlled Current Source
use work.electrical_systems.all;
entity Isource_vc is
generic (
gain : real := 1.0); -- gain of Isource_vc
port (
terminal inp : electrical; -- positive input terminal
terminal inm : electrical; -- negative input terminal
terminal outp : electrical; -- positive output terminal
terminal outm : electrical); -- negative output terminal
end entity Isource_vc;
architecture simple of Isource_vc is
quantity vin across inp to inm;
quantity vout across iout through outp to outm;
begin
iout == gain * vin;
end architecture simple;
The VHDL-AMS implementation of the VCCS is a four terminal model called Isource_vc.vhd. The
device operation is straightforward, but the output current, and not the input current, is declared as
a quantity. This implies that the VCCS will draw no current from whatever its input is connected to
(it acts as an ideal load).
The output voltage across this device is
determined by the simulator. The
output current through it is governed
by the characteristic equation:
iout gain vin =
VCCS
i np
i nm
outp
outm
vin
iout
Electrical Building BlocksIdeal 81


MAST Voltage-Controlled Current Source
template Isource_vc inp inm outp outm = gain
electrical inp, inm, outp, outm
number gain
{
branch vin=v(inp, inm)
branch vout=v(outp, outm), iout=i(outp->outm)
equations {
iout = gain*vin
}
}
The MAST implementation of the VCCS is a four pin model called Isource_vc.sin. The device
operation is straightforward, but the output current and not the input current is declared as a branch
variable. This implies that the VCCS will draw no current from whatever its input is connected to
(it acts as an ideal load).
G. Behavioral Op AmpIdeal
So far we have concentrated on simple components. We will now take the next step in behavioral
modeling with VHDL-AMS and MAST, and build an operational amplifier (op amp), a slightly
more complicated model.
We will use a more formal approach to developing this model than in the previous, simpler cases.
This is typical for model development: as models become more sophisticated, so must be our
techniques for developing them. The overall steps for model development include:
The output current through this device
is determined by the simulator. The
output voltage across it is governed by
the characteristic equation:
vout
vin A
1
s

1
----- +


1
s

2
----- +


------------------------------------------ =
vout
i nm
i np
gnd
82 Chapter 5Introduction to Conserved System Modeling

1. Determine model specifications (what aspects of op amp behavior will be modeled,
and what user inputs are required?)
2. Develop characteristic equations defining the behavior of the op amp
3. Code the equations in VHDL-AMS or MAST
4. Add appropriate bullet-proofing
5. Test the model
6. Document the model (in the model file itself)
For the purposes of this section we will concentrate on the first three steps only. Steps 4 - 6 will be
explored in Chapter 6: Developing User-Friendly Models.
Determine Model Specifications
Suppose that for our current design only the following op amp characteristics are important to us:
Open loop gain (A)
First break (pole) frequency (f
1
)
Second break (pole) frequency (f
2
)
As shown in Figure 5.3-1, at DC and very low frequencies, the open-loop op amp gain is simply A.
When the first break frequency, f
1
, is reached, the gain starts dropping off at 20dB/decade. This
Electrical Building BlocksIdeal 83


continues until break frequency f
2
is reached, at which point the gain begins dropping off at an
additional 20dB/decade, or 40dB/decade in all.
Develop Characteristic Equations
The next step is to develop appropriate equations for the op amp. As previously noted, the basic
s-domain transfer function is:
where
1
is the first break frequency, and
2
is the second break frequency (in radians).
Code the Equations
First, restate the basic equation in terms of (tau) rather than frequency (since we will be using the
derivative function, which is time-based). Knowing that =1/:
Gai n (dB)
f (Hz)
f
1
f
2
f
uni ty
40dB
decade
------------------
20dB
decade
------------------
0 dB
A
As illustrated in Figure 5.3-1 The open
loop transfer function for an op amp
has the following characteristics:
DC and low frequencies are amplified
by the open-loop gain, A.
At the first break frequency f
1
, the gain
rolls off at -20dB/decade.
At break frequency f
2
, the gain rolls
off at -40dB/decade.
At any point on the curve, the
gain-bandwidth product (GBW) is
constant.
Figure 5.3-1. Op amp s-domain transfer function.
TF
vout
vin
-----------
A
1
s

1
------ +


1
s

2
------ +


-------------------------------------------- = =
(5.3-1)
TF
A
1 s
1
+ ( ) 1 s
2
+ ( )
-------------------------------------------- =
(5.3-2)
84 Chapter 5Introduction to Conserved System Modeling

which is another way of stating:
Expanding the denominator:
Next, eliminate fractions by cross-multiplying the denominators:
Now we solve for vin on the left-hand side. The basic output equation for the transfer function is:
VHDL-AMS and MAST op amp model implementations will be given next.
VHDL-AMS Op Amp
use work.electrical_systems.all;
entity opamp is
generic (
f1 : real := 1.0; -- First pole
f2 : real := 2.0e6; -- Second pole
A : real := 1.8e6); -- Open loop gain
port (
terminal inp : electrical;
terminal inm : electrical;
terminal output : electrical;
terminal ref : electrical);
end entity opamp;
library ieee;
use ieee.math_real.all;
vout
vin
-----------
A
1 s
1
+ ( ) 1 s
2
+ ( )
-------------------------------------------- =
(5.3-3)
vout
vin
-----------
A
s
2

2
s
1

2
+ ( ) 1 + +
-------------------------------------------------------- =
(5.3-4)
vout s
2

2
s
1

2
+ ( ) 1 + + ( ) A vin = (5.3-5)
vin

2
A
----------
t
2
d
d
vout

2
+ ( )
A
---------------------
t d
d
vout
vout
A
----------- + + = (5.3-6)
Electrical Building BlocksIdeal 85


architecture simple1 of opamp is
constant t1 : real := 1.0 / (f1*math_2_pi);
constant t2 : real := 1.0 / (f2*math_2_pi);
quantity vin across inp to inm;
quantity vout across iout through output to ref;
begin
vin == (t1*t2)*vout'dot'dot/A + (t1+t2)*vout'dot/A + vout/A;
end architecture simple1;
For the op amp, we transform input arguments for the first time. We convert the first and second
pole frequencies into the time domain, using the familiar relation = 1/(2**f). We use the
ieee.math_real.all package so that the math_2_pi operator will be available. This is a one-time
conversion, so the new variables t
1
and t
2
are declared as constants. By declaring these constants
inside the architecture, they are local to the architecture.
MAST Op Amp
template opamp1 inp inm out gnd = f1, f2, A
electrical inp, inm, out, gnd
number f1,
f2,
A
{
branch vin=v(inp, inm)
branch vout=v(out, gnd), iout=i(out->gnd)
<consts.sin
number t1, t2
var nu deriv1
parameters {
t1 = 1 / (f1*2*math_pi)
t2 = 1 / (f2*2*math_pi)
}
equations {
vin = d_by_dt(deriv1/A) + d_by_dt(vout*(t1+t2)/A) + vout/A
deriv1 = d_by_dt(vout*t1*t2)
}
}
86 Chapter 5Introduction to Conserved System Modeling

Here we illustrate the Parameters section. This section is typically used for one-time numerical
conversions or calculations (as in this case), and input argument bullet-proofing which will be
discussed in the next chapter. The t
1
and t
2
time constant values are calculated when the model is
loaded into the simulator, but remain unchanged from that point throughout the simulation. The
time constants are calculated using the familiar relation = 1/(2**f), which is calculated using the
pre-defined constant declaration math_pi (located along with several other such constants in the
consts.sin file). Consts.sin is included in the model definition with the <consts.sin statement. When
encountered in a template, the contents of the consts.sin file will replace the <consts.sin statement.
As far as implementing the characteristic equation, there is no multiple derivative function in
MAST, so the second-order differential equation must be broken up into two first-order differential
equations. This is accomplished by introducing the intermediate variable, deriv. Deriv is set equal to
the derivative of vout_res*t
1
*t
2
, and then the derivative of deriv is taken to achieve the second-order
differential.
The intermediate variable, deriv, is declared as type var. In MAST, vars are system variables which
must be solved by the simulator just as implicitly defined system variables (like those declared in
branch statements). Vars are used in models whenever a branch variable cannot be declared (i.e. for
some 3 pin devices), or any other time when a new system variable needs to be introduced in the
model. Vars can only be assigned values in the Equations section.
5.4. Electrical Building BlocksNon-Ideal
Now that we have discussed some important ideal models, we will further develop a few of them to
make them more realistic. We will work on the resistor, capacitor, and op amp models.
A. Resistor with Temperature Dependency
Real models are often dependent on temperature. The ideal resistor model discussed earlier can be
modified to include such a dependence using the following second order equation:
reff_th = rnom*(1+tc1*(temp-tnom)+tc2*(temp-tnom)**2)
Where the effective temperature-dependent resistance reff_th, is equal to the actual resistance,
rnom, times a temperature expression. For this temperature expression, there are two temperature
coefficients tc1 and tc2 which the user can supply.
VHDL-AMS Linear Resistor with Temperature Dependency
use work.electrical_systems.all;
use work.ai_standard.all;
Electrical Building BlocksNon-Ideal 87


entity res_tmp is
generic (rnom : real := 0.0; --Nominal resistance
tc1 : real := 0.0; -- linear temperature coefficient
tc2 : real := 0.0; -- second order TC
temp : real := ambient_temperature;-- global temperature
tnom : real := 27.0); -- Nominal temp.
port (terminal p, m : electrical);
end entity res_tmp;
architecture behavioral of res_tmp is
constant delta_t : real := temp - tnom;
constant reff_th : real := rnom * (1.0 + tc1*delta_t + tc2*delta_t**2);
quantity v across i through p to m;
begin
i == v / reff_th;
end architecture behavioral;
The value for temp comes from a global variable, ambient_temperature, which is defined in the
ai_standard.vhd package. Declaring reff_th as a constant instructs the VHDL-AMS simulator
to only calculate its value once prior to simulation.
MAST Linear Resistor with Temperature Dependency
template res_tmp p m = rnom, tc1, tc2, tnom
electrical p, m
number rnom, tc1=0, tc2=0, tnom=27
external number temp
{
branch v=v(p, m), i=i(p->m)
number reff_th
parameters {
reff_th = rnom*(1+tc1*(temp-tnom)+tc2*(temp-tnom)**2)
}
equations {
i = v/reff_th
}
}
88 Chapter 5Introduction to Conserved System Modeling

In the MAST implementation, tnom is the nominal temperature; temp is a global temperature
variable defined in the file header.sin (which is a file where global variables are pre-defined). The
temp variable is made available to the model by declaring it as externalwhich tells the simulator
to go up the design hierarchy and look for the variable.
A value for temp can also be assigned when the template is instantiated in a netlist. This allows
users to change the ambient temperature of that particular instance (and everything hierarchically
below that instance), without affecting its global value in the rest of the system.
Putting the equation for reff_th in the Parameters section clearly identifies it as a parameter whose
value is calculated before the simulation, and then remains constant during the simulation.
B. Capacitor with ESR and Leakage
We will now add realistic effects to the ideal capacitor model discussed previously.
Equivalent-series-resistance and leakage current are real capacitor effects required for many circuit
simulations. These effects are implemented next.
VHDL-AMS Capacitor with ESR and Leakage
use work.electrical_systems.all;
entity capacitor2 is
generic (
cnom : real; -- capacitance value
esr : real; -- equivalent series resistance
rleak : real); -- leakage resistance
port (
terminal p, -- positive pin
m : electrical); -- minus pin
esr
cap
rleak
rleak is the leakage resistance, and
esr is calculated from:
where:
= dissipation factor
f = frequency where dissipation
factor is specified
C = capacitance
esr
tan
2fC
------------- =
p
m pm
Electrical Building BlocksNon-Ideal 89


end entity capacitor2;
architecture simple2 of capacitor2 is
terminal pm : electrical;
quantity vesr across iesr through p to pm;
quantity vcap across i through pm to m;
begin
iesr == vesr/esr;
i == cnom * vcap'dot + vcap/rleak;
end architecture simple2;
For this model an internal terminal, pm has been declared. This will be used as a standard terminal,
but is defined and used locally in this model architecture only. The quantities vesr, iesr, vcap, and i
are then declared with a combination of external terminals and pm.
MAST Capacitor with ESR and Leakage
template capacitor2 p m = cnom, esr, rleak
electrical p, m
number cnom, esr, rleak
{
electrical pm
branch vesr=v(p, pm), iesr=i(p->pm)
branch vcap=v(pm, m), i=i(pm->m)
equations {
iesr = vesr/esr
i = d_by_dt(cnom*vcap) + vcap/rleak
}
}
For the MAST implementation of the capacitor model, an internal pin, pm is declared. It will be
used just like any other pin, but its use is confined locally to this model (it cant be used to connect
to other models). The branch variables vesr, iesr, vcap, and i are then declared with a combination
of external pins and pm.
C. Behavioral Op Amp with Input/Output Characteristics
The op amp model previously developed takes into account open-loop gain and major break
frequency characteristics of op amp devices. In this section, we will extend the op amp model to
90 Chapter 5Introduction to Conserved System Modeling

include input and output characteristics. To begin, we will revisit the modeling steps discussed
earlier:
1. Determine model specifications
2. Develop characteristic equations defining the behavior of the op amp
3. Code the equations in VHDL-AMS or MAST
Determine Model Specifications
To account for op amp input and output characteristics, the model specifications must be extended
to include all of the following:
Open loop gain (A)
First break (pole) frequency (f
1
)
Second break (pole) frequency (f
2
)
Input offset voltage (v
os
)
Input resistance (r
in
)
Output resistance (r
out
)
Develop Characteristic Equations
For a basic op amp, we defined the characteristic equation for the transfer function as:
To add input and output effects, we add input resistance (r
in
), and output resistance (r
out
), as well as
input offset voltage (v
os
). Thus, the completed equations are:
Op amp output equation:
Op amp input equation:
TF
vout
vin
-----------
A
1
s

1
------ +


1
s

2
------ +


-------------------------------------------- = =
(5.4-1)
vout iout rout + TF vin vos + ( ) =
(5.4-2)
iin
vin
rin
-------- =
(5.4-3)
Electrical Building BlocksNon-Ideal 91


Code the Equations
The new equations are coded as follows:
VHDL-AMS Op Amp
use work.electrical_systems.all;
entity opamp2 is
generic (
f1 : real := 1.0; -- First pole
f2 : real := 2.0e6; -- Second pole
A : real := 1.8e6; -- Open loop gain
vos : real := 10.0e-6; -- Input offset voltage
rin : real := 100.0e6; -- Input resistance
rout : real := 70.0); -- output resistance
port (
terminal inp : electrical;
terminal inm : electrical;
terminal output : electrical;
terminal ref : electrical);
end entity opamp2;
library ieee;
use ieee.math_real.all;
architecture simple2 of opamp2 is
constant t1 : real := 1.0 / (f1*math_2_pi);
constant t2 : real := 1.0 / (f2*math_2_pi);
quantity vin across iin through inp to inm;
quantity vout across iout through output to ref;
quantity vin_os : real;
quantity vout_r : real;
begin
-- input stage
vin_os == vin + vos;
iin == vin_os / rin;
-- output stage
vout_r == vout + iout*rout;
vin == (t1*t2)*vout_r'dot'dot/A + (t1+t2)*vout_r'dot/A + vout_r/A;
end architecture simple2;
92 Chapter 5Introduction to Conserved System Modeling

For this model we declared an input current quantity, iin, since the op amp no longer acts like an
ideal load. Along with this added through variable we added an equation which tells the simulator
how to solve for it. Quantity iin is calculated with Ohms law using the sum of the input voltage
(vin) and the offset voltage (vos) for the overall input voltage (vin_os) across the input resistance
(rin).
To account for the output resistance, the output voltage drop due to rout is added to the ideal output
voltage vout, and assigned to a new variable vout_r (vout_r = vout + iout*rout). The new voltage,
vout_r, is then used in the characteristic op amp equations. The reason the product iout*rout is
added to vout rather than subtracted, is due to the way current flow is defined for positive output
voltage. For example, when vout is +5V, the quantity declaration iout through output to ref implies
that the current will be negative (flowing from output to ref). In general, this will cause the sign of
the current to be opposite of the sign of the voltage at that pin.
Note how it is possible to compose attributes in VHDL_AMS. In this case, the second derivative
term can be created using dotdot.
MAST Op Amp
template opamp2 inp inm out gnd = f1, f2, A, vos, rin, rout
electrical inp, inm, out, gnd
number f1,
f2,
A,
vos,
rin,
rout
{
branch vin=v(inp, inm), iin=i(inp->inm)
branch vout=v(out, gnd), iout=i(out->gnd)
<consts.sin
number t1, t2
var nu deriv1
val v vout_res
parameters {
t1 = 1 / (f1*2*math_pi)
t2 = 1 / (f2*2*math_pi)
}
Chapter Summary 93


values {
vout_res = vout + iout*rout
}
equations {
iin = (vin+vos)/rin
vin = d_by_dt(deriv1/A) + d_by_dt(vout_res*(t1+t2)/A) + vout_res/A
deriv1 = d_by_dt(vout_res*t1*t2)
}
}
As with the VHDL-AMS model implementation, we also declared a branch variable for the input
current, iin, since this device no longer acts as an ideal load. Along with this new through variable
we also needed to add a corresponding equation in the Equations section. Iin is calculated with
Ohms law using the sum of the input voltage (vin) and the offset voltage (vos) for the overall input
voltage across the input resistance (rin).
In this version of the op amp, the Values section is used for the first time. In this case, the Values
section defines an intermediate variable, vout_res, which is not a system variable. It is declared as
type val. Vals can only be assigned values in the Values section, but once assigned, they can be used
in other sections. In this example, vout_res is used in the right-hand side of the Equations section.
The Values section often helps to simplify the amount of work done in the Equations section, which
usually makes templates easier to read and understand.
For both the VHDL-AMS and MAST model implementations, the output voltage drop due to rout
is added to the ideal output voltage vout, and assigned to a new variable vout_res (vout_res = vout +
iout*rout). The new voltage, vout_res, is then used in the characteristic op amp equations. The
reason the product iout*rout is added to vout rather than subtracted, is due to the way current flow is
defined for positive output voltage. For example, when vout is +5V, the branch declaration iout =
i(out -> gnd) implies that the current will be negative (flowing from out to gnd). In general, this will
cause the sign of the current to be opposite of the sign of the voltage at that pin.
5.5. Chapter Summary
This chapter began by introducing several ideal models in both VHDL-AMS and MAST. These
were conservation-based models so that when simulated, Kirchoffs current law is applied to each
node in the design. Later in the chapter some non-ideal characteristics were added to some models
to illustrate some of the complicating factors designers must concern themselves with in making
models which behave more like real devices.
94 Chapter 5Introduction to Conserved System Modeling



chapter 6
Developing User-Friendly Models
This chapter discusses how to make models user-friendly so they work properly with diverse
applications and under a variety of test conditions. We will discuss bullet-proofing techniques,
overcoming numerical limitations, making models characterizable, and making models easier to
read by using functions.
6.1. Bullet-Proofing Techniques
When a new model is developed for general use, it is incumbent upon the model developer to
ensure the model is used as intended. Even with guidance, a user of a model may fail to understand
the model limitations, and inadvertently use it in an inappropriate or incorrect manner.
"Bullet-proofing" is a phrase used to describe making a model robust, or effective at handling
possible unintended usage. Without proper bullet-proofing added to the model, erroneous
simulation results can be generated, and the user may never be aware that the model is not
functioning correctly.
There are several standard bullet-proofing techniques that modelers should employ. To make
models as user-friendly as possible, we will concentrate on the one thing model users alter,
sometimes incorrectly: input arguments. Some of the more common things to check for include:
Divide by Zero - Many models perform division on input arguments. The model
developer should inspect any variable or argument involved in such an operation, and
bullet-proof it accordingly.

A resistor model, for example, may implement Ohms law in the following form: i = v/r.
The resistance value (r) will typically be specified by the user. So the resistor model
should verify that the input resistance value will not produce an illegal operation such as
divide by zero.
Negative Values - Some models may produce accurate results regardless of the sign of the
input argument value. A resistor, for example, may work properly with a negative input
resistance value. The only change in model behavior would be the direction of the current
flow through the device.

In other models the sign of the input arguments is critical. For example, an incorrect sign
96 Chapter 6Developing User-Friendly Models

for the nominal temperature tnom of a device would totally invalidate the
temperature-dependency expression discussed in the last chapter (since tnom is subtracted
from the global temperature, temp).
Range of Operation - Sometimes the range of operation of a model is limited. When
arguments are supplied that take the model out of its intended operational range, a model
can behave incorrectly.

For example, if a user of an op amp model inadvertently adds a voltage offset value of
20V, the actual input voltage will likely get swamped out and prevent the device from
operating in the linear region. Adding a simple input offset voltage range check to the
model would prevent this from happening.
There are many bullet-proofing checks like these that can easily be incorporated into both
VHDL-AMS and MAST models. Some actual examples will be given next.
1

A. Example: Linear Resistor
In this example, we will take the linear resistor model discussed earlier and add simple checks for
the following:
Rnom can not be equal to 0
Rnom can not be negative
VHDL-AMS Resistor With Bullet-Proofing
use work.electrical_systems.all;
entity resistor3 is
generic (
rnom : real); -- resistance value
port (
terminal p, -- positive pin
m : electrical); -- minus pin
end entity resistor3;
architecture simple3 of resistor3 is
quantity v across i through p to m;
begin
1. Proper bullet-proofing can make model files rather large. It is for this reason that these techniques will not be
used extensively for model examples in future chapters. However, use of bullet-proofing techniques is
strongly recommended for most models.
Bullet-Proofing Techniques 97


assert rnom /= 0.0
report "rnom can not be 0!"
severity error;
assert rnom >= 0.0
report "rnom is negative. Use with caution"
severity warning;
i == v / rnom;
end architecture simple3;
Bullet-proofing arguments with VHDL-AMS is typically accomplished with a combination of
assertion and report statements. The general syntax of the statements is as follows:
assert expression
[report expression]
[severity expression];
The assert statement is followed by a condition expression we expect to be true. If the assertion test
is found to be false, an assertion violation occurs, and report and severity expressions are reported
as part of the violation. If both report and severity clauses are present, the report clause must appear
first, and it must return a string. Normally, the string is a message stating the problem, and it is sent
to the application (simulator) to act upon. Often, the application uses the string to report a problem
to the designer using it.
There are four severity levels: note, which allows an informational message to be passed preceded
by NOTE; warning, which allows an informational message to be passed preceded by WARNING;
error which allows an informational message to be passed preceded by ERROR; and failure, which
allows an informational message to be passed preceded by FAILURE. For example, if the
bullet-proofed resistor has a value of 0.0 assigned to it, the following message would appear:
ASSERTION (ERROR) [Simple3]: rnom can not be 0!
For more specific information regarding the model which is issuing the violation, the following
attribute could be added to the report statement:
assert rnom >= 0.0
report "rnom is negative: "& realimage(rnom) & ".Use with caution"
severity warning;
Which, if violated by supplying a -8 Ohm rnom value for example, would give the following
message:
ASSERTION (WARNING) [Simple3]: rnom is negative: -8. Use with caution
The realimage predefined attribute returns a textual representation of the value of rnom. This
attribute is inserted into the report statement with the concatenation operator (&).
Whether or not a failure or error severity level will actually prevent the simulator from running a
simulation depends on the simulator.
98 Chapter 6Developing User-Friendly Models

MAST Resistor With Bullet-Proofing
template resistor3 p m = rnom
electrical p, m
number rnom
{
branch v=v(p, m), i=i(p->m)
parameters {
if (rnom == 0) {
error("(%) rnom must be > 0", instance())
}
else if (rnom < 0) {
warning("(%) rnom < 0. Use caution", instance())
}
}
equations {
i = v/rnom
}
}
There are four message functions available in MAST: message, warning, error, and instance().
Message, warning and error comprise a group of three built-in functions that can be used in the
Parameters section and in the bodies of When statements (reference Appendix B). Their format is
as follows:
message (format_string [, substitution_entities])
warning (format_string [, substitution_entities])
error (format_string [, substitution_entities])
where format_string is usually a string constant (but may be a string variable or expression). The
format string may include ordinary text, substitution tokens, or escape sequences (\t for tab; \n for
new line; \any for taking characters literally (\\, \%)).
A substitution token is a percent sign (%). It is replaced by the next available argument in the
substitution_entities list.
the message function - prints format_string with substitutions to screen. This is useful for
model debugging and general informational purposes.
Bullet-Proofing Techniques 99


the warning function - prints the annunciator line
*** WARNING "TEMPLATE WARNING" ***
followed by format_string with substitutions.
This is used mainly for parameter checking.
the error function - prints the annunciator line
*** ERROR "TEMPLATE ERROR" ***
followed by format_string with substitutions. This function is used mainly for critical
parameter checking. It ends the analysis when encountered, and can exit the simulation
in some situations.
the instance function - returns the name of the template instance, including the full
pathname. For example, given a template instantiated as mytemplate.m1, this message
message("You are now using %", instance())
in the Parameters section, would produce the following message:
You are now using /mytemplate.m1
each time the Parameters section is evaluated.
This is also our first encounter with MAST if statements. Their general syntax and usage rules are
given below. Further examples are given in Appendix B.
if ( expression ) statement
[else if ( expression ) statement ]
[else statement]
statement can be:
any statement that is legal for the sections in which it appears (sections have their own
restrictions governing statements)
another if statement
a compound statement:
{
one or more statements which would be legal in this section
}
expression is any expression which would be legal in this section.
If expression 0, then the following statement is evaluated
If expression = 0, then the following statement is skipped
100 Chapter 6Developing User-Friendly Models

B. Example: Behavioral Op Amp
Recall the behavioral op amp model discussed in Chapter 5: Introduction to Conserved System
Modeling. In this section, bullet-proofing will be added, and the remaining steps for finishing the
model for use will be discussed.
The first three steps below were covered during the previous op amp development. We will now
complete the op amp model by continuing with steps 4-6.
1. Determine model specifications (what aspects of op amp behavior will be modeled,
and what user inputs are required?)
2. Develop appropriate equations defining the behavior of the op amp
3. Code the equations in VHDL-AMS or MAST
4. Add appropriate bullet-proofing
5. Test the model
6. Document the model (in the model file itself)
Bullet-Proofing the Model
Now that we have a basic op amp model, it is time to look at some of the ways in which the new
model is intended to be usedand how users may fail to correctly use it.
The input arguments again are:
Open loop gain (A)
First break (pole) frequency (f
1
)
Second break (pole) frequency (f
2
)
Input Offset Voltage (V
os
)
Input Resistance (r
in
)
Output Resistance (r
out
)
The output current through this device is
determined by the simulator. The output
voltage across it is governed by the
characteristic equation:
vout
vin A
1
s

1
----- +


1
s

2
----- +


------------------------------------------ =
vout
i nm
i np
gnd
Bullet-Proofing Techniques 101


To determine what bullet-proofing is necessary, evaluate how each argument is used in the model.
If an inappropriate entry by a user can cause the model to behave improperly, provide a check for
that argument. Following are some examples:
If the open loop gain is not specified by a user, should it automatically be set to infinity? If
so, what effect will this have on the break frequencies?
Regarding the break frequencies: should there be a provision that f
2
be greater than f
1
?
What should happen if this is not the case?
What about input offset voltage? Should the default be 0? Should users be warned that this
is the case?
Input and output resistance: what should the defaults be? How should the model behave if
a user specifies zero for input resistance? Remember, iin = vin/rin, so zero is an illegal
value.
For this op amp model, the following bullet-proofing will be added. This is just a first pass
attempt at bullet-proofing, but should give an idea of how to approach it.
The following checks will be performed:
Divide by zero checks on the break frequencies
Divide by zero check on input resistance
Non-negative checks on break frequencies
Non-negative checks on input and output resistances
Undefined break frequency checks. If f
1
or f
2
is undefined, set the corresponding t
1
or t
2
to
zero. Also, alert the user with a warning.
The bullet-proofed VHDL-AMS model implementation is given next.
VHDL-AMS Op Amp With Bullet-Proofing
use work.electrical_systems.all;
entity opamp is
generic (
f1 : real := 1.0;
f2 : real := 2.0e6;
A : real := 1.8e6;
vos : real := 10.0e-6;
rin : real := 100.0e6;
rout : real := 70.0);
port (
terminal inp : electrical;
terminal inm : electrical;
terminal output : electrical;
102 Chapter 6Developing User-Friendly Models

terminal ref : electrical);
end entity opamp;
library ieee;
use ieee.math_real.all;
architecture simple3 of opamp is
constant t1 : real := op_bp_chk(f1); -- Check pole1 specification
constant t2 : real := op_bp_chk(f2); -- Check pole2 specification
quantity vin across iin through inp to inm;
quantity vout across iout through output to ref;
quantity vin_os : real;
quantity vout_r : real;
begin
assert rin > 0.0
report "rin must be > 0"
severity error;
assert rout >= 0.0
report "rout must be >= 0"
severity error;
-- input stage
vin_os == vin + vos;
iin == vin_os / rin;
-- output stage
vout_r == vout + iout*rout;
vin == (t1*t2)*vout_r'dot'dot/A + (t1+t2)*vout_r'dot/A + vout_r/A;
end architecture simple3;
In this model, the pole frequency checks are made with a user-defined function called op_bp_chk.
The purpose of the function is to check the input argument f1, and assign a corresponding value of
t1 based on that check. The same is true for f2 and t2. The function listing is:
use work.ai_standard.all;
library ieee;
use ieee.math_real.all;
package body opamp_bp_funcs is
function op_bp_chk(freq : real)
return real is
variable tau : real;
begin
if (freq = undef) then
report "freq undefined. Auto set to infinity";
tau := 0.0;
elsif (freq <= 0.0) then
report "freq must be > 0. Sign changed";
tau := -1.0 / (freq*math_2_pi);
Bullet-Proofing Techniques 103


else
tau := 1.0 / (freq*math_2_pi);
end if;
return (tau);
end function op_bp_chk;
end package body opamp_bp_funcs;
The op_bp_chk function is located in a user-defined package called opamp_bp_funcs_body. This is
the "body" of the opamp_bp_funcs package, shown in the following listing:
use work.ai_standard.all;
library ieee;
use ieee.math_real.all;
package opamp_bp_funcs is
function op_bp_chk(freq : real) return real;
end package opamp_bp_funcs;
These packages are compiled at run time, and the functions will be available for use then. Multiple
functions can be included in these packages.
The op_bp_chk function itself is fairly straightforward. The function first checks to see if the input
pole frequency is undefined using the predefined constant, undef. If it is undefined, a message is
reported to the user, and the corresponding value of tau is set to zero (infinite frequency implies a
zero time constant). The function next checks for a negative pole frequency. If the frequency is
negative, a message is issued and tau is calculated with its sign changed. If the frequency is defined
and non-negative, tau is calculated as normal. Functions are discussed further in Section 6.4:
Making Models Readable with Functions.
This is also our first encounter with if statements. Here are some examples of if statements for
non-simultaneous and simultaneous value assignments, so you can become familiar with the
syntax.
For non-simultaneous assignments:
if (condition1) then
x := a;
elsif (condition2) then
x := b;
else
x := c;
end if;
If x is simultaneous (declared as a quantity), the following syntax is used:
if (condition1) use
x == a;
104 Chapter 6Developing User-Friendly Models

elsif (condition2) use
x == b;
else
x == c;
end use;
The bullet-proofed MAST model implementation is given next.
MAST Op Amp With Bullet-Proofing
template opamp3 inp inm out gnd = f1, f2, A, vos, rin, rout
electrical inp, inm, out, gnd
number f1 = undef,
f2 = undef,
A = 100meg,
vos = 0,
rin = 100meg,
rout = 0
{
branch vin=v(inp, inm), iin=i(inp->inm)
branch vout=v(out, gnd), iout=i(out->gnd)
<consts.sin
number t1, t2
var nu deriv1
val v vout_res
parameters {
if (f1 == undef) {
warning("(%) f1 undefined. Auto set to infinity",instance())
t1 = 0
}
else if (f1 <= 0 ) {
error("(%) f1 must be > 0",instance())
}
else {
t1 = 1 / (f1*2*math_pi)
}
if (f2 == undef) {
warning("(%) f2 undefined. Auto set to infinity",instance())
t2 = 0
}
Bullet-Proofing Techniques 105


else if (f2 <= 0 ) {
error("(%) f2 must be > 0",instance())
}
else {
t2 = 1 / (f2*2*math_pi)
}
if (rin <= 0) {
error("(%) rin must be > 0",instance())
}
if (rout < 0) {
error("(%) rout must be >= 0",instance())
}
}
values {
vout_res = vout + iout*rout
}
equations {
iin = (vin+vos)/rin
vin = d_by_dt(deriv1/A) + d_by_dt(vout_res*(t1+t2)/A) + vout_res/A
deriv1 = d_by_dt(vout_res*t1*t2)
}
}
In MAST, the Parameters section is not only used to test the input parameters and issue messages, it
is also used to assign values to t1 and t2 as appropriate based on those checks. The end result is
similar to that achieved in the VHDL-AMS implementation.
Note also the use of the intrinsic number undef. Undef is used to test in a template whether
parameters and arguments are undefined. It should be used for conditional testing only (i.e. it
should not appear in any numerical calculation).
Testing the Model
Once a model has been developed, here are some useful guidelines for thoroughly testing it:
To test basic functioning, create and simulate a simple test bench that instantiates the new
model with as few supporting models as possible.
To test a model for robustness and speed, create and simulate a large circuit with many
instantiations of the new model.
Reality-check the model by creating and simulating a test bench that uses the
newly-created model in a typical application of moderate to large size.
Test parameter value boundaries by applying the full range of values for all model input
arguments.
Automate the test process as much as possible. This is useful for accuracy, and duplication
of results. It also allows for one-to-one performance comparisons between model
revisions.
106 Chapter 6Developing User-Friendly Models

Documenting the Model
Properly documented models are extremely important, yet rare. At a minimum, the model file
should be thoroughly documented with a detailed header and liberal comments throughout the
code. Comments should introduce all functions, major blocks and important or difficult statements
or groups of statementsstatements that implement key model behavior, for example.
The following full listing of the op amp model shows how this might be done. The model is written
in MAST, but models written in VHDL-AMS could also benefit from this documentation approach.
Fully-Documented Op Amp Model (in MAST)
# Version :
# Date modified :
# Author :
#*****************************************************************
template opamp4 inp inm out gnd = f1, f2, A, vos, rin, rout
#*****************************************************************
#*****************************************************************
# This template is a behavioral model for an opamp.
# called by opamp4
#
# i(inp->inm)
# --------------------------------------
# inp o-------| |
# rin | A |
# | -------------------------- |-------o out
# vos | (1+s/w1)(1+s/w2) | rout
# inm o-------| |
# --------------------------------------
#
#
# where:
# A is the open-loop gain
# f1 is the first break (pole) frequency (in Hz)
# f2 is the second break (pole) frequency (in Hz)
# rin is the input resistance
# rout is the output resistance
# vos is the input offset voltage (positive vos
# adds to vin).
# Equations:
Bullet-Proofing Techniques 107


# vout + iout*rout = TF*(vin + vos)
# i(inp->inm) = vin/rin
# where:
# branch vout=v(out, gnd), iout=i(out->gnd)
# branch vin=v(inp, inm)
#
# Warning Messages will occur if:
# f1 or f2 is undefined. Default values set to infinity
#
# Error Messages will occur if:
# f1 or f2 is zero or negative
# rin is zero or negative
# rout is negative
#
# Default values:
# A = 100meg, f1 = undefined, vos = 0,
# rin = 100meg, rout = 0, f2 = undefined
#
# Meanings:
# 1. A: Default is 100meg; no warning given if not specified
#
# 2. f1 or f2: If not specified, f1 and f2 will default to infinity
# and a warning is given
#
# 3. rin not specified means that rin will default to infinity
#
# 4. rout not specified means that rout will default to zero
#
#*****************************************************************
electrical inp, inm, out, gnd

number f1 = undef, # Pole1 frequency (Hz)
f2 = undef, # Pole2 frequency (Hz)
A = 100meg, # DC gain (V/V)
vos = 0, # Input offset voltage
rin = 100meg, # Input resistance
rout = 0 # Output resistance
{
branch vin=v(inp, inm), iin=i(inp->inm)
branch vout=v(out, gnd), iout=i(out->gnd)
<consts.sin # Bring in mathematical constants for math_pi
# For conversion from Hz to rad/sec
number t1, t2 # Used to convert to tau from freq. domain

var nu deriv1 # Intermediate var for second order differentiation
val v vout_res # Val for output voltage minus rout drop
108 Chapter 6Developing User-Friendly Models


parameters {
# Check for undefined first break frequency
if (f1 == undef) {
warning("(%) f1 undefined. Auto set to infinity",instance())
t1 = 0
}
# Check for zero or negative first break frequency
else if (f1 <= 0 ) {
error("(%) f1 must be > 0",instance())
}
# If no problems, compute tau1
else {
t1 = 1 / (f1*2*math_pi)
}
# Check for undefined second break frequency
if (f2 == undef) {
warning("(%) f2 undefined. Auto set to infinity",instance())
t2 = 0
}
# Check for zero or negative second break frequency
else if (f2 <= 0 ) {
error("(%) f2 must be > 0",instance())
}
# If no problems, compute tau2
else {
t2 = 1 / (f2*2*math_pi)
}
# Check for negative or zero input resistance
if (rin <= 0) {
error("(%) rin must be > 0",instance())
}
# Check for negative output resistance
if (rout < 0) {
error("(%) rout must be >= 0",instance())
}
}
values {
vout_res = vout + iout*rout # Output voltage less drop due to rout
}
equations {
iin = (vin+vos)/rin # Current is input plus offset voltage / rin
# Basic transfer function for op amp
vin = d_by_dt(deriv1/A) + d_by_dt(vout_res*(t1+t2)/A) + vout_res/A
Overcoming Numerical Limitations 109


# Intermediate derivative
deriv1 = d_by_dt(vout_res*t1*t2)
}
}
6.2. Overcoming Numerical Limitations
Another way to make models user-friendly is to develop them such that they minimize the effects
of numerical limitations of computer simulators. All computer simulators use finite precision
arithmetic. Most commercial simulators use double precision arithmetic in their calculations but are
subject to rounding errors which are the ratio of any pair of numbers used in an arithmetic
operation. For example, for many computers 10
237
+ 10
243
will work and 10
-300
+ 10
-289
will
work, but 10
237
+10
-289
will round-off. In many cases, the round-off does not cause a problem
because the smaller number is not significant. If you attempt to simulate a design that requires an
arithmetic operation that exceeds the rounding limit and the smaller numbers are significant, the
results will be unpredictable. This rounding limit problem is known as the "big number-small
number problem," and will manifest itself in different ways for each type of analysis of every
commercial simulator.
In general, a problem potentially exists whenever the ratio of two numbers involved in an
arithmetic computation (addition, subtraction, multiplication, and division), is taken. For some
simulators, certain matrix operations have a rounding limit of 10
16
. Following is an example of
how such a rounding limit could affect simulation accuracy.
For Figure 6.2-1, let I
src
=1A, R
1
=1e-18, and R
2
=100Meg.
To solve this circuit, conductance values G
1
(10
18
) and G
2
(10
-8
) will be added together in matrix
element a
22
.
This requires a dynamic range of 10
18+8
= 10
26
which exceeds the rounding limit of 10
16
. This
would result in what is called an "ill-conditioned matrix." The rounding limit does not mean that we
cannot use extremely small or large values, rather the restriction is on the range of numbers for
R
2
=1/G
2
R
1
=1/G
1
I
src
gnd
G
1
G
1
G
1
G
1
G
2
+ ( )
v
1
v
2
i
src
0
=
Figure 6.2-1. Simple resistor divider circuit and corresponding matrix.
v
1
v
2
110 Chapter 6Developing User-Friendly Models

related elements (i.e. elements which combine to make an entry in the system matrix) used in a
particular design.
Possible modeling solutions to these types of numerical problems are presented next.
A. Solution 1 - Create "Design-Dependent" Components
One way to avoid the big-small number problem is to have specialized components that can be used
in situations likely to have large component value differences. Take a resistor for example. We can
specify two types of modelsone for large resistance applications, and one for small resistance
applications. We can also allow the resistor for small resistance applications to be specified as zero.
"Big Resistance" Resistor Implementation
To implement the standard "large valued resistance" model, we can code Ohms law as we have in
the past:
i = v/rnom
We assume that all values will not exceed the boundary conditions of any computer the model is
likely to be simulated on, but we have just seen that this is not always true.
"Small Resistance" Resistor Implementation
To implement a special "small valued resistance" model, we can use the following approach:
if (rnom = 0) xi = 0
else xi = rnom
v = xi*i
Unlike the "big resistor" model we developed earlier, this calculation of resistance does two things:
1. If the specified resistance is zero, xi = 0, which results in 0V across the resistor. There is no
divide by zero because resistance never appears in the denominator (as it normally would
using the i = v/r version of Ohms law).
2. For very small values of resistance, the voltage is again calculated without using the
resistance value in the denominator. This allows the resistor to bypass big-small number
issues since its value will be closer in magnitude to the other resistors in the circuit (whose
resistance values are used in the denominator of the defining equations).
To solve the big-small number problem in Figure 6.2-1, we could use our "big resistor" model for
R
2
(since it is a large value), and our new "small resistor" model for R
1
(since it is a small
resistance value).
B. Solution 2 - Normalize Argument Values
In some situations the modeler can apply normalization or scaling techniques to model arguments
in order to avoid the numerical limitations of the simulator. This method artificially moves values
Overcoming Numerical Limitations 111


safely within range, performs the operations, and rescales or normalizes the result. Take a simple
low-pass filter model for example.
As illustrated in Figure 6.2-2, R and C are multiplied together to form the time constant, . If we let
R = 20*10
6
Ohms and C = 15*10
-12
Farads, the ratio of these two numbers is 10
18
, which would
again exceed a rounding limit of 10
16
. In this model, however, we know before-hand that these two
arguments will be multiplied together. Knowing this, we can avoid any potential rounding errors by
scaling the input arguments prior to this multiplication operation, and then rescaling the
pseudo-product after the operation. Two scaling examples are given next:
Let R = 20*10
6
, C = 15*10
-12
Let R
1
= R*10
-6
, C
1
= C*10
6

1
= R
1
*C
1
and,
= k*
1
(where k is 1/(10
-6
*10
6
) = 1)
In this example, = 300*10
-6
, which is the same result we would get multiplying the original R and
C arguments together (assuming no rounding errors). This scaling needs to occur before the actual
simulation ( should be declared as a constant or number). Once is calculated, it can be used just
like any other model argument or parameter.
The time constant scale factor k is used when the input arguments are scaled unequally. Using the
same example with C
1
= C*10
9
:
Let R = 20*10
6
, C = 15*10
-12
Let R
1
= R*10
-6
, C
1
= C*10
9

1
= R
1
*C
1
and,
= k*
1
(where k is 1/(10
-6
*10
9
) = 10
-3
)
Again, = 300*10
-6
. The scale factor k rescales the time constant in order to make up for the
imbalance caused by the unequal scaling of the input arguments.
C
R
V
src
gnd
v
1
v
2
Figure 6.2-2. Simple low-pass filter circuit and corresponding nodal equations.
The nodal equation for node v
2
is:
v
1
v
2

R
----------------- C
t d
dv
2
=
v
1
v
2
RC
t d
dv
2
+ =
v
1
v
2

t d
dv
2
+ =
Written as:
or:
112 Chapter 6Developing User-Friendly Models

6.3. Making Models Characterizable
Many theoretically sound models have been created that are nearly useless from a practical
standpoint because the models are not characterizable.
A characterizable model is one in which real-world parameters can be added to it in a meaningful
way. Using the op amp we developed earlier as an example, if the data book (or other source of data
from which we wish to characterize the device) specifies gain-bandwidth product (GBW), break
frequencies (f
1
and f
2
), open loop gain (A
ol
), slew rate (SR), and input voltage offset (v
os
), then a
characterizable model will allow the user to specify these parameters directly, rather than having to
manipulate them into some other form.
This is one of the advantages to hardware description languages: users can write meaningful
models with meaningful input parameters.
A. Characterization Approaches
Following are two ways model developers can make characterizable models: argument conversions
and units selection and conversion.
Argument Conversions
We have already seen argument conversions when developing the op amp model. If you recall, the
op amps characteristic equations are written using time-based operations (such as differentiation).
Yet the model design allowed the model user to input break frequencies in Hertz, and let the model
handle the conversion from Hertz to .
Units Selection and Conversion
Selection of appropriate working units is extremely important, particularly when it comes to
non-electrical models. A user-friendly model allows the user to input units for arguments which are
convenient for the given application. Here is an example of units checking and conversion for a
moment of inertia model. For this model fragment, assume that the user selects a value for the
moment of inertia, j. The user can specify j in either mks (meter, kilogram, second), cgs (centime-
ter, gram, second), fps (foot, pound, second), or ios (inch, ounce, second) units. The model, using
mks for the default units, will automatically convert any of the described units into mks:
if (units == mks) j_eff = j
# No conversion necessary. Units are N*m/(rad/sec**2).
else if (units == cgs) j_eff = j * 1e-7
# Convert dyne*cm/(rad/sec**2) to N*m/(rad/sec**2).
else if (units == fps) j_eff = j * 1.3558
# Convert ft*lb/(rad/sec**2) to N*m/(rad/sec**2).
Making Models Readable with Functions 113


else if (units == ios) j_eff = j * 7.06155e-3
# Convert in*oz/(rad/sec**2) to N*m/(rad/sec**2).
The conditional statements check to see which units were specified by the user for the model
argument, j. The actual model calculations are performed in mks units, and the conversions insure
that no matter what the user specifies, the proper units are used in the model calculations. To
differentiate the value the user inputs from the unit conversion the model performs, a new variable,
j_eff is declared and used in subsequent operations involving the moment of inertia.
6.4. Making Models Readable with Functions
Another way to develop user-friendly models is to structure them so they can be easily understood
by users. An effective way to so thisparticularly for complex modelsis to break them down
into several "functional modules." In both VHDL-AMS and MAST, this is accomplished with
functions.
Functions with VHDL-AMS and MAST are similar in both form and operation to subroutines in
other programming languages. Functions are useful in streamlining a model by moving reusable
modules out of the main model. We saw this earlier in the chapter with the VHDL-AMS version of
the bullet-proofed op amp model.
Take the resistor model with temperature dependency discussed in Chapter 5: Introduction to
Conserved System Modeling. Instead of incorporating the temperature-dependence code directly in
the resistor model, we can off-load it into a function, and call the function when needed.
VHDL-AMS and MAST model implementations are given next.
VHDL-AMS Resistor with Function
use work.electrical_systems.all;
use work.ai_standard.all;
entity resistor4 is
generic ( rnom : real := 0.0; --Nominal resistance
temp : real := ambient_temperature); -- Global temp.
tnom : real := 0.0; -- Nominal temperature
tc1 : real := 0.0; -- linear temperature coefficient
tc2 : real := 0.0); -- second order temp. coeff.
port (terminal p, m : electrical);
end entity resistor4;
114 Chapter 6Developing User-Friendly Models

architecture simple4 of resistor4 is
constant reff_th : real := Thermal_par_value(rnom,tc1,tc2,tnom,temp);
quantity v across i through p to m;
begin
i == v / reff_th;
end architecture simple4;
In this VHDL-AMS model, the temperature information is obtained using the following function
call:
constant reff_th : real := Thermal_par_value(rnom, tc1, tc2, tnom, temp);
The VHDL-AMS function is called Thermal_par_value, and it is listed next:
function Thermal_par_value(
value : real;
tc1 : real;
tc2 : real;
tnom : real;
temp : real)
return real is
variable result, delta_t : real;
begin
delta_t := temp - tnom;
result := value * (1.0 + tc1*delta_t + tc2*delta_t**2);
return (result);
end function Thermal_par_value;
You can see that the basic temperature calculation discussed earlier is now implemented in the
function, where values for value, tc1, tc2, tnom, and temp are passed to the function. After the new
resistance calculation is made, it is returned to the calling model as result.
Also note that the names of the parameters passed to/from the function do not need to match (in this
case, rnom is called value in the function); what does need to match between the model and the
function is the position of the parameters being passed. The Thermal_par_value function can be
collected with other useful functions in a package such as ai_standard_body.vhd.
VHDL-AMS variables are used in the Therm_par_value function. Variables are common in
functions because all functions can work with are numbersthey have no concept, for example, of
quantities. Variables are similar to constants, but their values can change after they have been
declared. Once a constant is declared and initialized, its value must remain unchanged.
Making Models Readable with Functions 115


MAST Resistor with Function
template resistor4 p m = rnom, tc1, tc2, tnom
electrical p, m
number rnom, tc1=0, tc2=0, tnom=27
external number temp
{
branch v=v(p, m), i=i(p->m)
number reff_th
parameters {
reff_th = Thermal_par_value(rnom, tc1, tc2, tnom, temp)
}
equations {
i = v/reff_th
}
}
In this MAST model, the temperature information is obtained using a function named
Thermal_par_value called this way:
reff_th = Thermal_par_value(rnom, tc1, tc2, tnom, temp)
The Thermal_par_value function is listed here:
function reff_th = Thermal_par_value(rnom, tc1, tc2, tnom, temp)
number rnom, # nominal resistance
tnom, # nominal temperature
tc1, # coefficient for temperature expression
tc2, # coefficient for temperature expression
reff_th, # results of temperature calculation
temp # Global temperature
{
reff_th = rnom*(1+tc1*(temp-tnom)+tc2*(temp-tnom)**2)
}
With the temperature calculations removed from the resistor model, the model becomes less
cluttered and easier to read and understand. This has the added advantage of allowing the function
to be used in other models too.
116 Chapter 6Developing User-Friendly Models

Numbers, vals, vars, etc. can be declared and used in MAST functions. However, what actually gets
passed will always be numbers. Data types are assigned and maintained in the main template, not in
the MAST function. For example, assume a template calls a function from the Values section. Since
it is called from the Values section, the variable which accepts the returned value must be of type
val. The function itself knows nothing about which section it was called from, and just processes
the passed data and returns a number. Once this number is returned from the function, it is treated
as a val, since it was declared as a val in the main template.
When it comes to creating user-friendly models, bullet-proofing the models helps; making models
characterizable makes the models more useful; and segmenting complex models into functions
makes them more readable, and allows the functions to be used in other models. However, the best
way to create user-friendly models is for the modeler to understand how the model will typically be
used. The modeler must ask "Who is the intended user of the model?" With this attitude and a little
common-sense, model developers can succeed in developing user-friendly models.
6.5. Chapter Summary
In this chapter we explored several ways to make user-friendly models users will appreciate.
Bullet-proofing techniques were discussed which can help keep a model from being used outside of
its intended region of operation. Two methods by which numerical simulation limitations may be
overcome were also presented. The importance of producing models that are characterizable was
emphasized, and an example was given. The chapter concluded with an example of using functions
to streamline models and keep them readable.


chapter 7
Advanced Modeling Concepts
This chapter deals with advanced modeling concepts. Although there really is no well defined line
that distinguishes basic and advanced models, an advanced model is defined here as one that
requires specific interaction or control of the simulator, or interaction with other programming
languages (such as C).
Two general classes of models require specific interaction of the simulator. They are piecewise
linear (PWL) modeling, and time-dependent modeling.
7.1. Piecewise Linear Modeling
Piecewise linear (PWL) modeling techniques provide a very convenient way to develop models by
simply specifying model transfer functions in terms of data points. PWL modeling is commonly
used when:
No standard equation exists
Measured data is to be used for the model definition
Equation exists, but PWL approach may be faster and easier
PWL modeling techniques are introduced with two examples, a voltage limiter and ideal diode.
A. Voltage Limiter
Take the simple voltage limiter transfer function shown in Figure 7.1-1.
This shows that the characteristic transfer function for the voltage limiter consists of three distinct
operating regions: when v
in
is more negative than low_lim, v
out
is limited to low_lim. When v
in
is
inp
inm
outp
outm
vin vout
v
out
up_lim
low_lim
v
in
Figure 7.1-1. Voltage limiter symbol and transfer function.
118 Chapter 7Advanced Modeling Concepts

greater than up_lim, v
out
is limited to up_lim. And when v
in
is in-between low_lim and up_lim, v
out
varies linearly with v
in
.
VHDL-AMS and MAST model implementations are given next.
VHDL-AMS Voltage Limiter
use work.electrical_systems.all;
entity v_limit is
generic (
up_lim : real := 10.0; -- upper limit
low_lim : real := -12.0); -- lower limit
port (
terminal ip, im, op, om : electrical);
end entity v_limit;
architecture simple of v_limit is
quantity vin across ip to im;
quantity vout across iout through op to om;
begin
if vinabove(up_lim) use
vout == up_lim;
elsif not vinabove(low_lim) use
vout == low_lim;
else
vout == vin;
end use;
break on vinabove(up_lim), vinabove(low_lim);
end architecture simple;
There are several points to note in this model. First, in the quantity definitions, even though the
output current is specified, the input current is not defined. This implies that the input current is
zero, and this voltage limiter will not load down whatever is driving it.
The actual characteristics of the limiter function are implemented using if statements. The first if
statement checks if v
in
is greater than the upper limit, up_lim; the second if statement checks if v
in
is
less than the lower limit, low_lim; if neither of these conditions are satisfied, v
out
is set to the current
value of v
in
.
The actual limit crossing detection is made with the vinabove attribute.
Piecewise Linear Modeling 119


The break on statement at the end of the definition serves an important purpose: whenever the
up_lim or low_lim threshold is crossed, the simulator is notified that a discontinuous first derivative
is present, and that it needs to restart the analog solver. Break on statements must always be
specified whenever a first-derivative discontinuity exists in the model equations.
MAST Voltage Limiter
template limit inp inm outp outm = up_lim, low_lim
electrical inp, inm, outp, outm
number up_lim, low_lim
{
branch vin=v(inp, inm)
branch vout=v(outp, outm), iout=i(outp->outm)
equations {
vout = if vin < low_lim then low_lim \
else if vin > up_lim then up_lim \
else vin
}
}
There are several points to note in the MAST model. First, in the branch definitions, again the input
current is not defined, however the output current is specified. This implies that the input current is
assumed to be zero, and this voltage limiter will not load down whatever is driving it.
The actual characteristics of the limiter function are implemented using if statements in the
Equations section. The first if statement checks if v
in
is less than low_lim; the second if statement
checks if v
in
is greater than up_lim; if neither of these conditions are satisfied, v
out
is set to the
current value of v
in
.
120 Chapter 7Advanced Modeling Concepts

B. Ideal Diode
Another simple example of creating a transfer function by connecting two or more linear segments
is an ideal diode model. The symbol and transfer function for such a model are shown in Figure
7.1-2.
The ideal diode is modeled as a "binary conductance." The transfer function of this model works as
follows: when the voltage level across the diode is negative, the diode is "off," and the current
flowing through it (from cathode to anode) is defined linearly by the Roff segment. When the
voltage across the diode is positive, the current flowing through it is defined by the Ron segment,
which has a much steeper slope and results in forward biased (anode to cathode) current flow.
Model implementations are given next.
VHDL-AMS Ideal Diode
use work.electrical_systems.all;
entity id1 is
generic (
ron : real; -- equivalent series resistance
roff : real); -- leakage resistance
port (
terminal p, -- positive pin
m : electrical); -- minus pin
end entity id1;
architecture simple of id1 is
quantity v across i through p to m;
begin
if vabove(0.0) use
anode cathode anode cathode
+ v -
i = v/ron
+ v -
i = v/roff
I
V 0
Ron
Roff
Figure 7.1-2. Ideal diode symbol and transfer function.
Time-Dependent Modeling 121


i == v/ron;
elsif not vabove(0.0) use
i == v/roff;
else
i == 0.0;
end use;
break on vabove(0.0);
end architecture simple;
In this model implementation, the current through the device is defined by three operating regions:
when the voltage is greater than zero (i = v/ron); when the voltage is less than zero (i = v/roff); and
when the voltage is zero (i = 0). Because a first derivative discontinuity exists at v = 0, a break on
statement for that voltage value has been included in the model.
MAST Piecewise Linear Diode
template id1 p m = ron, roff
electrical p, m
number ron=1e-6, roff=1e6
{
branch v=v(p, m), i=i(p->m)
equations {
i = if (v>0) then v/ron \
else if (v<0) then v/roff \
else 0
}
}
As with the VHDL-AMS model implementation, the current through the MAST model is defined
by three operating regions: when the voltage is greater than zero (i = v/ron); when the voltage is less
than zero (i = v/roff); and when the voltage is zero (i = 0).
7.2. Time-Dependent Modeling
In most of the models we have discussed so far, we have been assuming that the across quantity
(voltage for electrical systems) represents the independent variable, and the through quantity
(current for electrical systems) represents the dependent variable. But this is just a typical way in
122 Chapter 7Advanced Modeling Concepts

which to use these variables, and is not always the case. For example, the ideal voltage limiter,
discussed previously, uses voltage as both the independent and dependent variable.
Time-dependent modeling represents a special case where the independent variable is time, rather
than an across or through variable. It is most often (but not exclusively) used for defining source
stimulus behavior.
Time-dependent modeling requires a different approach than standard modeling. This is because
the timestep, usually chosen by the simulator, must be specifically controlled in some
time-dependent models to precisely define the waveforms the model will produce.
In this section, three voltage source models will be discussed: an exponential waveform source, a
pulse waveform source, and a sinusoidal waveform source.
A. Exponential Waveform Source
An exponential waveform source delivers a waveform of the type shown in Figure 7.2-1.
Possible VHDL-AMS and MAST implementations for this source are given next.
VHDL-AMS Exponential Source
use work.electrical_systems.all;
entity Vsource_exp is
generic (
v1 : real := 1.0; -- beginning voltage, [Volt]
v2 : real := 10.0; -- final voltage, [Volt]
tau : real := 0.0); -- time constant, [Seconds]
port (terminal p, -- positive pin
m : electrical); -- minus pin
end entity Vsource_exp;
voltage
time

V
2
V
1
V1 + (V2 - V1)(1 - e
(-time/)
)
Figure 7.2-1. Exponential waveform.
Starting voltage is v
1
.
Final voltage is v
2
.
Time constant is .
Characteristic Equation:
vout v
1
v
2
v
1
( ) 1 e
t
( ) + =
Time-Dependent Modeling 123


library ieee;
use ieee.math_real.all;
use work.ai_standard.all;
architecture simple of Vsource_exp is
quantity vout across iout through p to m;
begin
vout == v1 + (v2-v1)*(1.0-exp(-(NOW/tau)));
end architecture simple;
In this model, vout is explicitly dependent on time. In VHDL-AMS, the predefined function NOW
is used to return the current simulation time.
MAST Exponential Source
template Vsource_exp p m = v1, v2, tau
electrical p, m
number v1, v2, tau
{
branch vout=v(p, m), iout=i(p->m)
equations {
vout = v1 + (v2-v1)*(1-exp(-(time/tau)))
}
}
This MAST template is also explicitly dependent on time. The MAST simulator variable time is
used to return the current simulation time.
124 Chapter 7Advanced Modeling Concepts

B. Pulse Waveform Source
As the name implies, a pulse waveform source delivers a pulse to stimulate a circuit or system. The
main characteristics of a typical voltage pulse source are illustrated in Figure 7.2-2.
The general description of this voltage pulse source also applies to current pulse sources, as well as
mechanical, hydraulic, thermal, and pulse sources in all other technology domains.
Timestep Control
In the case of a pulse waveform, it is critical that the model control the choice of timesteps rather
than leave it to the simulator to choose. If the model does not control the timestep specifically, the
simulator may choose steps that result in an undesirable waveform definition. For example,
inadequate timestep control could vary the rise time of the pulse depending on the simulators
Figure 7.2-2. Describing a pulse waveform.
voltage
time
V
2
V
1
tr tf
width
delay
period
Voltage starts out at level v
1
.
After delay, voltage starts ramping from
v
1
to v
2
.
After tr, voltage levels off at v
2
.
Voltage stays at v
2
for time defined by
width.
After duration width passes, voltage
starts ramping down from v
2
to v
1
.
After time tf elapses, voltage levels off at
v
1
.
Cycle repeats itself after time period.
Time-Dependent Modeling 125


selection of the timestep. This problem is shown by the contrasting waveforms in Figures 7.2-3 and
7.2-4.
As can be seen from Figure 7.2-3, the simulator chose timesteps (indicated with xs on the function)
that did not exactly correspond to the desired waveform rise start and stop times. Since the
simulator simply connects the region between the two timesteps with a straight line, a pulse rise
time does occur, but its duration is incorrect.
Not only is the duration incorrect, it is not even repeatable with different simulation settings such as
those controlling simulation error (since step size is typically chosen as a function of allowable
error). This situation is exasperated further when the circuit itself is in any way changed because
automatic timestep selection will vary with each new topology.
With timestep control, the model "tells" the simulator that a timestep needs to be performed at a
specific instant in time. Figure 7.2-4 illustrates the pulse waveform with the timestep controlled
from within the model. As can be seen, this pulse waveform has the desired rise time because
timesteps occur at the exact moments in time when the waveform changes need to occur.
VHDL-AMS and MAST pulse waveform model implementations will be given next.
Figure 7.2-3. Pulse waveform without
model-controlled timestep.
Figure 7.2-4. Pulse waveform with
model-controlled timestep.
voltage
time
V
2
V
1
rise time
desired
rise time
actual
timestep
timestep
voltage
time
V
2
V
1
rise time
desired
rise time
actual
timestep
timestep
126 Chapter 7Advanced Modeling Concepts

VHDL-AMS Pulse Source
use work.electrical_systems.all;
use work.ai_standard.all;
entity Vsource_pulse is
generic (
initial : real := 0.0; -- initial value
amplitude : real := 1.0; -- amplitude of the pulse
-- if amplitude is negative,
-- pulse is inverted.
delay : real := 0.0; -- delay time
tr : real := 1.0e-9; -- rise time
tf : real := 1.0e-9; -- fall time
width : real := 1.0e-6; -- width of pulse
period : real := 2.0e-6); -- period of time of the pulse
port ( terminal p,
m : electrical);
end entity Vsource_pulse;
library ieee;
use ieee.std_logic_1164.all;
use ieee.math_real.all;
architecture simple of Vsource_pulse is
constant time_unit : time := 1.0 sec;
constant top_width : real := width+tr;
constant bot_width : real := period-width-tr;
constant top_level : real := amplitude + initial;
signal pulse_tran : real := initial;
quantity vout across iout through p to m;
begin
-- The rising time is considered as part of width
-- tr must be < width.
-- Similarly, tf must be < low_width which is equal to period - width
vout == pulse_tran'ramp(tr, tf);
p1 : process
begin
wait for delay*1.0 sec;
loop
pulse_tran <= top_level;
wait for top_width*1.0 sec;
pulse_tran <= initial;
Time-Dependent Modeling 127


wait for bot_width*1.0 sec;
end loop;
end process;
end architecture simple;
This model operates as follows (with initial values v
1
= 0V and v
2
= 5V):
The model waits until time delay, at which point loop is executed. At that time, pulse_tran takes on
the pulse amplitude, 5V. V
out
, with the new value of pulse_tran, begins ramping from v
1
(0V) to 5V.
When time t
r
has passed from that point, vout will level off at 5V. Once the pulse width is reached,
pulse_tran is assigned the value 0V again, and v
out
begins the ramp down from 5V to 0V.
The ramp function will ensure that a timestep occurs right after the delay time has elapsed, and
whenever a transition from one level to another is made. As a result, this source will perform
correctly regardless of simulation settings or circuit topology.
This is also our first encounter with a VHDL-AMS process. A process allows for the execution of
one or more statements, and can include a sensitivity list. When an event occurs on any of the
signals in the sensitivity list, the process statements will be sequentially executed. Process
execution is suspended when the last statement in the process is reached, or when a statement
appears such as wait on (wait for some event to occur), or wait for (wait for some period of time to
elapse), which conditionally suspends the process. Statements such as if, case, and loop can all
appear within processes. The process as a whole is concurrent with other processes.
In the pulse source model, the process p1 is executed (since there is no sensitivity list, it will be
automatically executed). After waiting for a user-defined delay time to elapse, loop is entered. After
loop is executed, the process ends, and then repeats indefinitely. Processes will be illustrated further
in later chapters.
MAST Pulse Source
template vsource_pulse p m = initial, amplitude, tr, tf, width, \
period, delay
electrical p, m
number initial=0, amplitude, tr, tf, width, period, delay=0
{
branch vout=v(p,m), iout=i(p->m)
state time next_step=0, tr_begin=-1, tr_end=-1, tf_begin=-1, tf_end=-1
val v v
number outdif
128 Chapter 7Advanced Modeling Concepts

parameters{
if (initial == amplitude) {
error("%: initial (%) must not equal amplitude (%)",
instance(), initial, amplitude)
}
outdif = amplitude - initial
}
# Initialization
when (time_init) {
# "Kick off" the pulse
schedule_event(time+delay,next_step,time+delay)
schedule_next_time(time+delay)
}
# During the Transient analysis, each period sets up the next waveform
when (event_on(next_step)) {
# Set the "corners" of the output waveform in Time
tr_begin = time
tr_end = tr_begin + tr
tf_begin = tr_end + width
tf_end = tf_begin + tf
# Start the next period
schedule_event(time+period,next_step,time+period)
# Informing the Analog simulator when these times are
schedule_next_time(time+tr)
schedule_next_time(time+tr+width)
schedule_next_time(time+tr+width+tf)
schedule_next_time(time+period)
}
values {
# Not in transition
if ((time < tr_begin) | (time > tf_end)) v = initial
# Transitioning from initial to amplitude
else if (time < tr_end) v = initial + outdif * (time-tr_begin)/tr
# At amplitude
else if (time < tf_begin) v = amplitude
# Transitioning from amplitude to initial
else if (time < tf_end) v = amplitude - outdif * (time-tf_begin)/tf
# Ending at initial (at tf_end)
else v = initial
}
Time-Dependent Modeling 129


equations {
vout = v
}
}
This template works as follows:
In MAST, timestep control at specific points along a waveform can be accomplished with the
schedue_next_time function. This function instructs the simulator to evaluate the analog matrix
whenever it is encountered. In the case of a pulse source definition, each time a new waveform
segment is defined, the schedule_next_time function is called.
To make this a repetitive waveform, When statements are introduced such that at the end of each
period, the cycle repeats itself. This is a standard method for creating repetitive waveforms as
MAST does not have an intrinsic looping function. When statements are discussed in Appendix B.
Note also the use of the Values section. In this model, all of the waveform construction statements
are in this section. The Equations section is just used to satisfy the branch variable, vout.
C. Sinusoidal Waveform Source
Description
A sinusoidal waveform source delivers a sine or cosine waveform to stimulate a circuit or system.
The main characteristics of a typical sinusoidal source are illustrated in Figure 7.2-5.
Timestep Control
A sinusoidal source poses a slightly different problem than a pulse source when in comes to
timestep control. For this type of source, the model must control the maximum step size that can be
vo
t = 0
va
td td + 1/f
vo
T = 1/f
voltage
time
Figure 7.2-5. Describing a sinusoidal waveform.
Amplitude is v
a
.
Period is the reciprocal of
the frequency: 1/f.
Offset from zero is
specified as v
o
.
Delay is defined as t
d
.
Characteristic Equation:
vout v
o
v
a
2ft ( ) + =
130 Chapter 7Advanced Modeling Concepts

taken. If there are not enough timesteps taken during a period of the sinewave, the waveform will
become distorted. Therefore a mechanism to limit the step size is required. Figure 7.2-6 shows a
sinewave in which there are twenty equally-spaced timesteps in a period. This timestep control will
ensure a smooth, accurate sinewave.
In VHDL-AMS, the code for the sinewave model with timestep control illustrated in Figure 7.2-6 is
implemented as follows:
VHDL-AMS Sinusoidal Source
use work.electrical_systems.all;
entity Vsource_sine is
generic (
amplitude : real := 1.0; -- amplitude, [Volt]
freq : real := 1.0e6; -- frequency, [Hertz]
phase : real := 0.0; -- initial phase, [Degree]
offset : real := 0.0; -- DC value, [Volt]
delay : real := 0.0); -- Delay time, [Sec]
port (terminal p, -- positive pin
m : electrical); -- minus pin
end entity Vsource_sine;
library ieee;
use ieee.math_real.all;
use work.ai_standard.all;
vo
t = 0 td td + 1/f
T = 1/f
voltage
time
Figure 7.2-6. Sinewave with 20 equally-spaced timesteps.
Waveform accuracy is achieved
by limiting the maximum
timestep as follows:
step size = 1/(20*f)
Time-Dependent Modeling 131


architecture simple of Vsource_sine is
quantity v across i through p to m;
limit v : voltage with 1.0/(20.0*freq);
begin
if (NOW <= delay) use
v == offset;
else
v == offset + amplitude * sin(math_2_pi*freq*(NOW-delay)+phase);
end use;
end architecture simple;
The sinusoidal output voltage is generated with the sine function, sin. The frequency of the
sinewave is determined by the input argument freq (and is converted into radians by the math_2_pi
multiplier). The instantaneous amplitude is calculated by taking the sine of the radian frequency
times the current time (represented in VHDL-AMS with the simulator variable NOW). Optionally, a
DC offset is added to the waveform by assigning a non-zero value to offset.
The timestep control is achieved with the limit specification. Timesteps taken for v are limited in
size to no greater than 5% of the frequency by limiting v to 1.0/(20.0*freq). This ensures that no
matter what the frequency of the sinewave is, at least twenty timesteps per period will be taken by
the simulator.
The step size limit check only controls the maximum step size taken. If the step size is chosen by
the simulator to be smaller than that specified in the model, it will just give more resolution to the
sinewave. The extra resolution should be unnecessary if limit is properly specified.
Small-signal AC analysis can also be performed with this source if the following model additions
are made. First, add the following generics to the entity:
ac_mag : real := 1.0; -- AC magnitude, [Volt]
ac_phase : real := 0.0; -- AC phase, [Degree]
Next, modify the architecture as follows:
-- Declaration of signal in frequency domain for AC analysis
quantity ac : real spectrum ac_mag, math_2_pi*ac_phase/360.0;
-- The item "ac" will be active only in AC analysis.
v == offset + amplitude * sin(math_2_pi*freq*(NOW-delay)+phase) + ac;
Similar statements can be added to the pulse waveform source or any other source model to provide
small-signal AC analysis capability.
132 Chapter 7Advanced Modeling Concepts

MAST Sinusoidal Source
template Vsource_sine p, m = f, mag, ph, vos, td
electrical p, m
number f, # frequency (Hz)
mag = 0, # magnitude (peak voltage)
ph = 0, # phase (degrees)
vos = 0, # offset voltage
td = 0 # delay time (seconds)
{
branch v_sin=v(p, m), i_sin=i(p->m)
<consts.sin
number w, rad, step
val v v
parameters {
w = 2 * math_pi * f
rad = ph * math_pi / 180
step = 1 / (f * 20)
}
values {
if (time <= td) {
v = vos
next_time = td
}
else {
v = vos + mag * sin(w * (time - td) + rad)
step_size = step
}
}
equations {
v_sin = v
}
}
The sinusoidal output voltage is generated with the sine function, sin. The frequency of the
sinewave is determined by the input argument f before it is converted into radians by the math_pi
multiplier. The instantaneous amplitude is calculated by taking the sine of the radian frequency
times the current time, represented in MAST with the simulator variable time. Optionally, an offset
is added to the waveform by assigning a non-zero value to offset.
The timestep control is achieved with the step_size specification. Timesteps taken for v are limited
in size to no greater than 5% of the frequency by setting step_size to step, which is calculated as
Time-Dependent Modeling 133


1/(f*20). This ensures that no matter what the sinewave frequency is, at least twenty timesteps per
period will be taken by the simulator.
As with VHDL-AMS, the step size limit check only controls the maximum step size taken. If the
step size is chosen by the simulator to be smaller than that specified in the model, it will just give
more resolution to the sinewave. The extra resolution should be unnecessary if step_size is
properly specified.
Also, a special timestep is added for the instant the delay time (td) elapses. The next_time simvar is
used to instruct the simulator to solve the system at time td. Next_time is similar to the
schedule_next_time function, but next_time can be used in the Values section.
To add small-signal analysis capability to this source, the following modifications could be made to
the MAST model (additions are shown in bold):
template vsin_ac p, m = f, mag, ph, vos, td, ac
electrical p, m
number f, # frequency (Hz)
mag = 0, # magnitude (peak voltage)
ph = 0, # phase (degrees)
vos = 0, # offset voltage
td = 0 # delay time (seconds)
struc {
number ac_mag = 1,
ac_phase = 0
} ac=(1,0)
values {
if (dc_domain | time_domain) {
...
v = vos + mag * sin(w * (time - td) + rad)
step_size = step
}
else if (freq_mag) {
v = ac->ac_mag
}
else if (freq_phase) {
v = ac->ac_phase
}
}
...
In this example, we have declared two new arguments, ac_mag and ac_phase as part of a structure,
called ac. Structures are used to group model parameters that are somehow related. A structure
parameter is an ordered list of member parameters (in this case ac_mag and ac_phase). Structure
members may be a number, an enum, or any other parameter type. Another structure can also be
declared inside a structure.
134 Chapter 7Advanced Modeling Concepts

Although it is not necessary to declare a structure in this case, structures can generally help simplify
complex models by limiting the number of model arguments individually specified in the template
header. Once declared as part of a structure, a member of that structure may be accessed by the
model as follows:
v = ac -> ac_mag
In this case, the value of v is set to the value of ac_mag, which is a member of the ac structure.
Structure members can be initialized inside the structure declaration like this
number ac_mag = 1,
ac_phase = 0
or immediately following the declaration (order-dependent) like this
} ac = (1,0)
In either case, ac_mag will be initialized to 1, and ac_phase will be initialized to 0.
This example also illustrates how MAST can directly interact with the simulator. The model
determines which type of analysis is being performed, and adjusts the source output accordingly.
There are a group of simulator variables (simvars) which MAST models can test to determine
which type of analysis is being performed. For example, this model tests the dc_domain,
time_domain, freq_mag, and freq_phase simvars in order to know which type of voltage equation
to use for which type of simulation. A full list of simvars is given in Appendix B.
Similar statements can be added to any other MAST source model to provide small-signal AC
analysis capability.
7.3. Foreign Subroutines
There are situations when it is necessary or an advantage to step outside of VHDL-AMS or MAST
to use conventional programming languages like C or Fortran. possible reasons for doing this
include:
Reuse of existing code
Compiled code runs faster than interpreted code
Encryption of Intellectual Property (IP)
Overcome modeling language limitations
Sharing of models in a MSHDL language-independent format
Making models modular (as with standard functions)
When other languages are incorporated into a model, the code is confined to functions that are
referred to as foreign subroutines since it is not written in the native modeling language.
We will next discuss examples of coupling foreign code to VHDL-AMS and MAST models. In all
of the examples, the foreign routines are written and compiled in the C programming language.
Foreign Subroutines 135


A. Foreign Subroutines with VHDL-AMS
Passing data to/from foreign subroutines is not specified as part of the VHDL-AMS language itself.
Therefore, how foreign subroutines are implemented will depend on the individual simulator. The
following discussion is based on the SaberHDL simulator from Synopsys Corporation.
The following syntax is used to declare a pass-by-value C foreign subroutine in a VHDL-AMS
model:
function function_name( argument1:type;
argument2:type;
argument3:type;
... )
return type;
attribute foreign of function_name : function is
"saber libai_TheHDLforeign function_filename";
It is used to assign values to variables this way:
(result1, result2, ...) := function_name(argument1, argument2 ...)
Here is what a modeler must do to include a foreign subroutine in a model: first, a function is
defined using the syntax above, then the attribute, foreign, is assigned to that function. The keyword
saber is used to define the interface for the function call, and the libai_theHDLforeign library is
where the compiled function code must reside. So, the function, function_name is coded in a file
called function_filename (this name must be different than function_name), and compiled into the
libai_theHDLforeign library. It is then referenced as function_name in actual usage.
The parentheses on the left-hand side may be omitted if only a single value is returned.
An example is now given, where a quantity, p is returned from the function_filename, pwr_calc,
which is identified by the function_name, pwr, and has two arguments, v and i:
function pwr( v :real;
i :real)
return real;
attribute foreign of pwr : function is
"saber libai_TheHDLforeign pwr_calc";
...
begin
p == pwr(v, i);
...
The C subroutine that performs the calculation is:
void pwr_calc( double*in, long*nin, long*ifl, long*nifl,
double*outi, long*nout, long*ofl, long*nofl,
double*aundef, long*ier)
double vin, iin, p;
136 Chapter 7Advanced Modeling Concepts

vin = in[0]; /* input voltage */
iin = in[1]; /* input current */
p = v*i; /* calculate the power */
outi[0] = p; /* send calculated power back to the simulator */
Information is passed to the foreign function via an input array, in. The first value passed to the
routine will be stored in array element zero, which is accessed using: in[0]; the next value passed to
the routine is stored in array element one, which can be accessed using: in[1]; and so on for the rest
of the inputs.
Information is passed from the foreign routine to the model via an output array, outi. Values are
passed with this array in the same way as the input array: the first value passed from the routine to
the model will be stored in array element zero, which is accessed using: outi[0], and so on for the
rest of the outputs.
The position of the information being passed is important. For example, the model passes two
variables to the subroutine, v and i. The fact that they are listed in the order (v, i) means that v will
occupy element 0 of the input array, and i will occupy element 1 of the input arrayso in the
routine itself, element 0 of the input array can be assigned any name (vin in this case), but it will
still represent the voltage, v, being passed over. The same holds true for the current.
B. Foreign Subroutines with MAST
1
In MAST, illustrations will be given for passing numbers as well as passing strings.
Returning a Single Number
To declare a foreign subroutine to return a single number, use the following MAST declaration (for
FORTRAN or C):
foreign number subroutine_name()
It is used the following way:
result = routine_name(argument1, argument2, ...)
An example is shown below, where the routine called power_calc takes two arguments, v and i, and
returns the instantaneous power to a value called p.
p = power_calc(v,i)
The foreign routine itself would then include the following calculation:
vin = in[0]; /* voltage */
iin = in[1]; /* current */
p = v*i; /* power calculation */
out[0] = p; /* send power back to the simulator */
1. All examples shown here use UNIX syntax. The foreign routine header syntax varies somewhat for
non-UNIX systems.
Foreign Subroutines 137


As with the VHDL-AMS foreign subroutine interface, information is passed from a MAST
template to the foreign function via an input array, in. The first value passed to the foreign
subroutine will be stored in array element zero, which is accessed using: in[0]; the next value passed
to the foreign subroutine is stored in array element one, which can be accessed using: in[1]; and so
on.
Information is passed from the foreign subroutine to the MAST template via an output array, out.
Values are passed with this array in the same way as the input array: the first value passed from the
subroutine to the model will be stored in array element zero, which is accessed using: out[0], etc.
Foreign subroutines that return a single value can be used anywhere in templates to define numbers,
values, or states, and are the only types allowed in the Equations section. Also, the parameters
passed between template and subroutine do not need to have the same name. The position of the
information being passed is important. For example, the template passes two variables to the
subroutine, v and i. The fact that they are listed in the order (v, i) means that v will occupy element 0
of the input array, and i will occupy element 1 of the input arrayso in the subroutine itself,
element 0 of the input array can be assigned to any name (vin in this case), but it will still represent
the voltage, v, being passed over.
Returning Multiple Numbers
To declare a foreign subroutine to return a list of numbers, arrays, or structures requires a slightly
different declaration using the form:
foreign subroutine_name
and is used in the following way:
(result1, result2, ...) = routine_name(argument1, argument2 ...)
An example is shown, where two values, v2 and i2 are returned from the function transform, which
has three arguments, v1, i1, ratio:
(v2,i2) = transform(v1, i1, ratio)
Passing Structures
Information from MAST structures can also be passed to foreign subroutines.
The key to passing information contained in structures to a foreign subroutine lies in the order, or
position of the data in the structure.
For example, if you have the following structure:
struc {
A, B, C
} alphabet = ()
Then, in the foreign routine, A = in[0], B = in[1], and C = in[2] (assuming there was no other data
being passed before the structure).
138 Chapter 7Advanced Modeling Concepts

The following partial template shows a diode that uses a structure called model in a foreign
subroutine call.
element template diode p n = model
electrical p, n
struc {
number is = 1e-14, # saturation current default value
n = 1, # emission coefficient
cjo = 1p, # Junction cap, default value
vj = 1 # barrier potential w/ default value
} model = ()
{
foreign diode # declare sub diode as foreign
values{
(id,qd) = diode(vd, model, temp, math_charge,\ # use foreign
math_boltz, math_ctok) # routine
}
...
<Foreign routine...header info, etc. goes here>
/* unpack input array */
vd = in[0]; /* applied voltage */
is = in[1]; /* saturation current */
n = in[2]; /* emission coefficient */
cjo = in[3]; /* junction capacitance */
vj = in[4]; /* barrier potential */
temp = in[5]; /* ambient temperature, in Celsius */
q = in[6]; /* electron charge, coulombs */
k = in[7]; /* Boltzmann's constant */
ctok = in[8]; /* Celsius to kelvin constant */
tempk = ctok + temp; /* convert temp to kelvin */
vt = bc_thermv(k,tempk,q); /* calculate thermal voltage */
id = is * (exp(vd/vt) - 1); /* calculate DC current */
qd = vd*cj/(sqrt(1 - (vd/vj)));
out[0] = id; /* send back to the simulator */
out[1] = qd; /* send back to the simulator */
Passing Strings
As the arrays to and from foreign subroutines are defined as real numbers, we need to have some
special functions to pass and return strings. There are two functions to do this:
Foreign Subroutines 139


cgetstr - used in C to get a string from the input array
csetstr - used in C to set an element in the output array to a string
Both routines are declared as functions returning a char* pointer as shown here:
char *csetstr();
char *cgetstr();
How to use the cgetstr function is illustrated in the following example:
char *instring;
char *cgetstr();
strcpy(instring,cgetstr(in[0]));
and to use csetstr:
char *outstring = "test";
char *csetstr();
strcpy(csetstr(out[0],outstring));
String Handling: C Example
The following example illustrates a MAST model, call.sin, which prints a message to the screen
from a string variable called msg. MAST originally defines msg as: "This is the initial message
before calling sub." It then calls a foreign subroutine, stringpass.c. This routine prints its own
message: "stringpass received: This is the message being returned from the sub." The last part of
this message, "This is the message being returned from the sub" is also returned to the MAST
template (to the string variable, msg), and printed from the template. This shows how the string
contained in msg is modified by the C routine.
C Routinefile name stringpass.c
#include <stdio.h>
void stringpass_(in, nin, ifl, nifl, out, nout, ofl, nofl, aundef, ier)
int *nin, *ifl, *nifl, *nout, *ofl, *nofl, *ier;
double *in, *out, *aundef;
{
char *cgetstr();
double csetstr();
char *instr, outstr[128];
instr=cgetstr(in[0]);
fprintf(stderr, "From C - stringpass received: %s\n", instr);
strcpy(outstr, "This is the message being returned from the sub");
out[0]=csetstr(outstr);
}
140 Chapter 7Advanced Modeling Concepts

MAST Templatefile name call.sin
template call
{
foreign stringpass # Declare the foreign routine
string msg="This is the initial message before calling sub"
parameters {
message("From MAST: %",msg)
msg = stringpass("This is the message passed to the sub")
message("From MAST: %", msg)
}
}
call.1 # Instantiation of the template (test circuit)
Upon invoking the simulator, the following messages should appear:
From MAST: This is the initial message before calling sub
From C - stringpass received: This is the message passed to the sub
From MAST: This is the message being returned from the sub
7.4. Chapter Summary
This chapter discussed several models which interact with the simulator in some special manner. In
the case of piecewise linear (PWL) models, break on statements were required in VHDL-AMS to
tell the simulator that first derivative discontinuities were present in the model; for time-dependent
modeling, mechanisms were required to insure adequate timestep selections were made by the
simulator. Foreign subroutines were also discussed, and examples were given for passing numbers
and strings.


chapter 8
Signal Flow (Non-Conserved) Modeling
This chapter discusses non-conserved signal flow modelsalso referred to as control system or
data flow models. Signal flow models are useful in many contexts, but are especially convenient for
the systems designer who uses a top-down design approach, which is discussed next.
8.1. The Top-Down Design Approach
With MSHDLs at the designers disposal, true top-down design (and bottom-up verification) is
possible. Taking a top-down approach means that a system is first developed at a high level of
abstraction, where interfaces and overall system performance criteria are specified and verified
first. After this level of the design is complete, it can be partitioned into more detailed functional
blocks, and the process repeated.
For example, say you wanted to design a CD-ROM controller. At an abstract level, this is a
closed-loop control system which must satisfy at least two criteria: accuracy and stability. Assume
that the specifications for the CD-ROM controller are as follows:
Accuracy: error <= 2%
Stability: phase margin >= 40 degrees
A closed-loop control system can be designed to these specifications without using physics-based
components. Let the system shown in Figure 8.1-1 represent the overall topology of the CD-ROM
controller:
+
1 + s/f
1
1 + s/f
2
_
Figure 8.1-1. S-domain CD-ROM controller topology.
b2s
2
+b1s + b0
a2s
2
+a1s + a0
K
1 + s/f
1
K
K
Lag Compensator
Lead/Lag
Compensator Motor Transfer Function
Feedback Gain
142 Chapter 8Signal Flow (Non-Conserved) Modeling

By selecting values for the various signal flow components in Figure 8.1-1, the accuracy can be
determined using DC (operating point) analysis. Once the accuracy specification is met,
small-signal AC analysis can be used to measure the phase margin (after the loop is opened).
To verify our design, we will model it and apply actual values to try and meet the system
specifications. Our first attempt results in the system shown in Figure 8.1-2:
In our design, the motor characteristics are modeled using the Motor Transfer Function block,
which implements the motor as a two-pole device. The pole locations are derived from the
electrical and mechanical time constants given as part of the motor specifications; the Lag
Compensator block models a single pole at 3mHz; and the Lead-Lag Compensator is the block we
will tune to achieve the overall system performance mandated by the specifications. The initial lead
(zero) value is 0.3Hz, the initial lag (pole) value is 3Hz.
A DC analysis reveals the error measured at the output of the summing junction to be 1%, which
meets the 2% accuracy specificationthe Lag Compensator gain was set to 100 so this
specification could be met. However, when the loop is opened and the phase margin is measured, it
is only 27 degrees, as shown in Figure 8.1-3.
+
1 + s/0.3
1 + s/3
_
Figure 8.1-2. S-domain CD-ROM controller with values.
130
s
2
+1250s + 130
K
1 + s/0.003
100
1
Lag Compensator
Lead/Lag
Compensator Motor Transfer Function
Feedback Gain
Figure 8.1-3. Inadequate phase margin measurement.
The Top-Down Design Approach 143


The next step is to figure out what lead-lag compensator values will give us 40 degrees of phase
margin. There are many possible approaches we may take. In this case, we will sweep the zero
frequency of the lead-lag compensator, and generate a phase margin versus zero frequency
waveform. We will then determine which frequency corresponds to a 40 degree phase margin
measurement. Using this approach, it looks like a zero frequency of 0.95 rad/s (0.15 Hz) yields 40
degrees of phase margin. The results of this analysis are illustrated in Figure 8.1-4.
The system with the new lead-lag zero value (0.95 rad/s) is then simulated for final verification, as
shown in Figure 8.1-5.
As can be seen from the figure, the CD-ROM design specifications have been met.
With the closed-loop control system working, various blocks can be exchanged with more detailed
models. For example, the compensators may be realized using electronic models developed in
previous chapters; a pulsewidth modulated motor drive may be added (we will develop a
pulsewidth modulator model in Chapter 9: Mixed-Signal Modeling); and the s-domain motor block
may be replaced with a true mixed-technology motor model which we will develop in Chapter 11:
Hydraulic and Mechanical Modeling.
What makes this type of analysis so appealing is that the signal flow models are developed at an
abstract, mathematical level. This allows the models to be rapidly developed and easily used.
Figure 8.1-4. Lead-lag zero frequency versus phase margin.
Figure 8.1-5. Adequate phase margin measurement.
144 Chapter 8Signal Flow (Non-Conserved) Modeling

Signal flow model development is discussed next, and all of the models used in the CD-ROM
example plus several more will be developed.
8.2. Characteristics of Signal Flow Models
Signal flow models are different from physics-based models in the following respects:
Signals are directional, outputs are not loaded
Conservation laws (e.g. KCL) do not apply
Signals have no units
Signals have no reference point
Signal flow models are used because:
Model development is usually quicker
Differentiation and integration is replaced with multiplication and division
Simulation run times are quicker
8.3. Signal Flow Modeling in the Time Domain
There are two basic methods to develop signal flow models. One is to use time-based (derivative
and integration) operators to create appropriate equations. The other is to use s-domain syntax
directly. Examples of time-based model development will be presented in this section.
To implement any arbitrary transfer function in VHDL-AMS,
1. Break it down into the form: IN(s) = OUT(s)
2. Replace the s operators with dot.
3. Rather than declaring pins as type terminal, declare them as quantities of type in or
out.
To implement any arbitrary transfer function in MAST,
1. Break it down into the form: IN(s) = OUT(s)
2. Create intermediate system variables to reduce n
th
order derivatives into n 1
st
order
derivatives.
3. Replace the s operators with d_by_dt().
4. Rather than declaring pins as type electrical (or other technology), declare them as
type input or output.
Signal Flow Modeling in the Time Domain 145


A. Gain Block
VHDL-AMS Gain Block
entity gain is
generic (
k: real := 1.0); -- Gain multiplier
port ( quantity input: in real;
quantity output: out real);
end entity gain;
architecture simple of gain is
begin
output == k*input;
end architecture simple;
The main feature of this model which distinguishes it from previous implementations is that the
port declarations are quantities rather than terminals. Quantity pins will have a direction specified
using the keywords in or out. They do not have across and through variables associated with them,
and conservation laws will not be enforced.
MAST Gain Block
template gain in out = k
input nu in
output nu out
number k = 1
{
K
input output
This model takes the signal at the input,
and multiplies it by a gain factor, k. The
characteristic equation is:
output k input =
146 Chapter 8Signal Flow (Non-Conserved) Modeling

equations {
out = k*in
}
}
By declaring the MAST pins as type input and output, conservation laws will not be applied to
them. An input pin refers to the var in another template; an output pin makes a var available to
another template. Input and output can be replaced with ref and var, respectively. For example, the
gain block header could be written as:
template gain in out = k
ref nu in
var nu out
number k = 1
...
Note that branch declarations are not necessary for signal flow pins.
B. Two-Input Summer
VHDL-AMS 2-Input Summer
entity sum2 is
generic (k1, k2: real := 1.0); -- Gain multipliers
port ( quantity in1, in2: in real;
quantity output: out real);
end entity sum2;
architecture simple of sum2 is
begin
output == k1*in1 + k2*in2;
end architecture simple;

output
in
2
in
1
This model takes the sum of the two
inputs, optionally multiplied by a gain
factor. The characteristic equation is:
output k
1
in
1
k
2
in
2
+ =
Signal Flow Modeling in the Time Domain 147


MAST 2-Input Summer
template sum2 in1 in2 out = k1, k2
input nu in1, in2
output nu out
number k1=1, k2=1
{
equations {
out = k1*in1 + k2*in2
}
}
C. Differentiator
VHDL-AMS Differentiator
entity deriv is
port (quantity input: in real;
quantity output: out real);
end entity deriv;
architecture simple of deriv is
begin
output == input'dot;
end architecture simple;
s input output
This model differentiates the signal at
the input. The characteristic equation is:
output
t d
d
input =
148 Chapter 8Signal Flow (Non-Conserved) Modeling

MAST Differentiator
template diff in out
input nu in
output nu out
{
equations {
out = d_by_dt(in)
}
}
D. Double Differentiator
VHDL-AMS Double Differentiator
entity diff2 is
port ( quantity input: in real;
quantity output: out real);
end entity diff2;
architecture simple of diff2 is
begin
output == inputdotdot;
end architecture simple;
The diff2 model shows how attributes can be composed. In this model, double-differentiation is
achieved by composing the dot attribute as dotdot.
s
2
input
output
This model differentiates the signal at
the input twice. The characteristic
equation is:
output
t
2
d
d
input =
Signal Flow Modeling in the Time Domain 149


MAST Double Differentiator
template diff2 in out
input nu in
output nu out
{
var nu sin
equations {
sin = d_by_dt(in)
out = d_by_dt(sin)
}
}
In MAST, there is no way to perform double-differentiation directly, so the intermediate variable,
sin is introduced. This is the same approach used for the op amp model discussed previously.
E. Integrator
VHDL-AMS Integrator
entity integ is
generic (
init: real := 1.0); -- Initial value of output
port ( quantity input: in real;
quantity output: out real := init);
end entity integ;
1
in out
s
This model integrates the signal at the
input. The characteristic equation is:
output input

=
150 Chapter 8Signal Flow (Non-Conserved) Modeling

architecture simple of integ is
begin
output == input'integ;
end architecture simple;
The intrinsic quantity integ integrates the input signal.
MAST Integrator
template integ in out = init
input nu in
output nu out
number init = 0
{
control_section {
initial_condition(out,init)
}
equations {
in = d_by_dt(out)
}
}
As MAST does not have an integration operator, the equation must be expressed in differential
terms. To do this, the input is defined in terms of the output, rather than the other way around. Also
note how the integrator is initialized in the Control section.
F. Lead-Lag Compensator
1 + s
z
input output
1 + s
p
K*
This model performs a lead-lag
function. The characteristic equation is:
output input k
1 s
z
+
1 s
p
+
----------------- =
Signal Flow Modeling in the Time Domain 151


The time-domain development of the equations governing this transfer function block are as
follows:
and isolating out:
Removing factors:
Multiplying through to remove parentheses:
which in terms of derivatives would be:
The general form given in (8.3-5) will be used for the VHDL-AMS and MAST model
implementations.
VHDL-AMS Lead-Lag Compensator
entity lead_lag is
generic (
K: real := 1.0; -- Gain multiplier
fz: real := 10.0; -- Lead break frequency (zero)
fp: real := 100.0); -- Lag break frequency (pole)
port ( quantity input: in real;
quantity output: out real);
end entity lead_lag;
library ieee;
use ieee.math_real.all;
out
in
-------- K
1 s
z
+
1 s
p
+
----------------- =
(8.3-1)
out in K
1 s
z
+
1 s
p
+
----------------- = (8.3-2)
out 1 s
p
+ ( ) in K 1 s
z
+ ( ) = (8.3-3)
out s out
p
+ K in s K in
z
+ =
(8.3-4)
out
t d
d
out
p
( ) + K in
t d
d
K in
z
( ) + = (8.3-5)
152 Chapter 8Signal Flow (Non-Conserved) Modeling

architecture simple of lead_lag is
constant tz : real := 1.0/(fz*math_2_pi);
constant tp : real := 1.0/(fp*math_2_pi);
begin
output == inputdot*K*tz + input*K - outputdot*tp;
end architecture simple;
MAST Lead-Lag Compensator
template lead_lag in out = fz, fp, k
input nu in
output nu out
number fz = 10, # zero frequency (Hz)
fp = 100, # pole frequency (Hz)
k = 1 # DC gain (V/V)
{
<consts.sin
number tz, tp # for conversion from Hz to rad/sec
parameters {
tz = 1 / (fz*2*math_pi)
tp = 1 / (fp*2*math_pi)
}
equations {
out = k*in + d_by_dt(k*in*tz) - d_by_dt(out*tp)
}
}
G. Limiter Function
input output
output
up_lim
low_lim
input
Signal Flow Modeling in the Time Domain 153


This model is similar in function to the electrical limiter discussed in the previous chapter.
However, the pins of this model do not need to obey conservation laws. Because of this, the input
and output reference pins required for the electrical limiter are unnecessary for this implementation.
VHDL-AMS Limiter
entity limiter is
generic (
lim : real; -- Limit value
k : real; -- Non-limiting gain
softk : real); -- Local gain (slope) in the limit region
port (
quantity input: in real;
quantity output: out real);
end entity limiter;
library ieee;
use ieee.math_real.all;
architecture simple of limiter is
quantity in_gain : real;
begin
assert(k /= 0.0)
report "Gain k should not be set to 0!"
severity error;
assert(k * softk >= 0.0)
report "k and softk should have the same sign!"
severity error;
in_gain == input * k;
if in_gain > lim use
output == lim + ((input * k - lim) / ABS(k)) * softk;
elsif in_gain < -lim use
output == -lim + ((input * k + lim) / ABS(k)) * softk;
else
output == in_gain;
end use;
end architecture simple;
The softk term is used to prevent the limiter from having a zero-slope in the limiting regions. This
concept is discussed further in Chapter 12: Simulator Convergence.
154 Chapter 8Signal Flow (Non-Conserved) Modeling

MAST Limiter
template limiter in out = k, softk, lim
input nu in
output nu out
number k=1, # Non-limited gain
softk, # Non-zero slope of limited region
lim # Symmetrical limit value
{
val nu in_gain # Intermediate variable for input times gain
parameters {
if (k == 0 | softk == 0) {
error("(%) Neither k nor softk can be 0", instance())
}
else if (k*softk < 0) {
error("(%) k and softk should have the same sign", instance())
}
}
values {
in_gain == in * k;
}
equations {
out = if in_gain > lim then lim + ((in * k - lim) / ABS(k)) * softk \
else if in_gain < -lim then -lim + ((in * k + lim) / ABS(k)) * softk \
else in_gain
}
}
As with the VHDL-AMS limiter model, the softk term is used in MAST to prevent the limiter from
having a slope of zero in the limiting regions. This concept is discussed further in Chapter 12:
Simulator Convergence.
8.4. Signal Flow Modeling in the Frequency Domain
An alternate approach to modeling transfer functions is by using specialized operators provided in
both VHDL-AMS and MAST. These operators allow s-domain transfer functions to be specified in
descending powers of s, which make it possible for them to be implemented without using
derivative or integration functions.
Signal Flow Modeling in the Frequency Domain 155


A. Two Pole Filter
The input format for the s-domain transfer function operators are in descending powers of s:
which can now be directly coded.
VHDL-AMS S-Domain Two Pole Filter
entity twopole is
generic (
k: real := 1.0; -- Gain multiplier
f1: real := 10; -- First break frequency (pole)
f2: real := 100); -- Second break frequency (pole)
port ( quantity input: in real;
quantity output: out real);
end entity twopole;
library ieee;
use ieee.math_real.all;
architecture simple of twopole is
constant w1 : real := f1*math_2_pi;
constant w2 : real := f2*math_2_pi;
constant num : real := k;
constant den : real_vector := (w1*w2, w1+w2, 1.0);
begin
output == k*inputltf(num, den);
end architecture simple;
k
input output
(1 +
1
s)(1 +
2
s)
2-pole general purpose second order
filter. The characteristic equation is:
output input
k
1 s
1
+ ( ) 1 s
2
+ ( )
--------------------------------------------- =
output
k input
s
2

2
s
1

2
+ ( ) 1 + +
-------------------------------------------------------- =
(8.4-1)
156 Chapter 8Signal Flow (Non-Conserved) Modeling

The implicit quantity ltf is used to implement the s-domain transfer function as the ratio of
numerator and denominator terms. In this case, the numerator is simply the gain, k. Since the
denominator consists of three terms, it is declared as a type real_vector, which denotes it as an array
of real number entries.
MAST S-Domain Two Pole Filter
template twopole in out = k, f1, f2
input nu in
output nu out
number f1,# first cutoff frequency
f2,# second cutoff frequency
k # Gain factor
{
<consts.sin
number tau1, tau2 # for conversion from Hz to rad/sec
parameters {
tau1 = 1 / (f1*2*math_pi)
tau2 = 1 / (f2*2*math_pi)
}
equations {
out = transfer_function(in, [k], [tau1*tau2, tau1+tau2, 1])
}
}
The MAST two pole filter uses the MAST function, transfer_function. It is used as follows:
output = transfer_function(input_expression, numerator, denominator)
Where:
output is the output variable (output, or var)
input_expression is an expression containing the input variable (input, val, or ref)
numerator is an array of coefficients of the numerator polynomial (highest order coeffi-
cients listed first)
denominator is an array of coefficients of the denominator polynomial (highest order coef-
ficients listed first)
Signal Flow Modeling in the Frequency Domain 157


B. General Purpose 2nd Order Filter
We will next develop a general purpose filter that models a second-order function in both the
numerator and denominator.
As with the twopole model, this transfer function can be realized using the following form:
Where the z subscripts imply time constants in the numerator (zeros), and p subscripts imply time
constants in the denominator (poles).
Model implementations will now be presented.
VHDL-AMS 2nd Order Filter
entity second_order is
generic (
k: real := 1.0; -- Gain multiplier
fz1: real := 10; -- First zero (numerator) frequency
fz2: real := 100); -- Second zero (numerator) frequency
fp1: real := 10; -- First pole (denominator) frequency
fp2: real := 100); -- Second pole (denominator) frequency
port ( quantity input: in real;
quantity output: out real);
end entity second_order;
library ieee;
use ieee.math_real.all;
architecture simple of second_order is
constant wz1 : real := fz1*math_2_pi;
constant wz2 : real := fz2*math_2_pi;
constant wp1 : real := fp1*math_2_pi;
constant wp2 : real := fp2*math_2_pi;
b2s
2
+b1s + b0
input output
a2s
2
+a1s + a0
2-zero, 2-pole general purpose second
order filter. The characteristic
equation is:
output input
b2s
2
b1s b0 + +
a2s
2
a1s a0 + +
--------------------------------------- =
output k input
s
2

z1

z2
s
z1

z2
+ ( ) 1 + +
s
2

p1

p2
s
p1

p2
+ ( ) 1 + +
------------------------------------------------------------------- =
(8.4-2)
158 Chapter 8Signal Flow (Non-Conserved) Modeling

constant num : real_vector := (wz1*wz2, wz1+wz2, 1.0);
constant den : real_vector := (wp1*wp2, wp1+wp2, 1.0);
begin
output == k*inputltf(num, den);
end architecture simple;
This implementation is similar to that of the two pole filter, with the numerator specified as a
collection of descending-power coefficients as well as the denominator. Both num and den are
declared as type real_vector.
MAST 2nd Order Filter
template second_order in out = k, fz2, fz1, fp2, fp1
input nu in
output nu out
number fz2, # First zero (numerator) frequency
fz1, # Second zero (numerator) frequency
fp2, # First pole (denominator) frequency
fp1, # Second zero (denominator) frequency
k # Gain factor
{
<consts.sin
number tz2, tz1, tp2, tp1 # for conversion from freq to time
parameters {
tz2 = 1 / (fz2*2*math_pi)
tz1 = 1 / (fz1*2*math_pi)
tp1 = 1 / (fp2*2*math_pi)
tp2 = 1 / (fp1*2*math_pi)
}
equations {
out = transfer_function(k*in, [tz2*tz1,tz2+tz1,1],[tp2*tp1,tp2+tp1,1])
}
}
The MAST second order model is similar to the lowpass filter model, with the additional terms
specified for the numerator entry.
Chapter Summary 159


8.5. Chapter Summary
This chapter introduced non-conserved analog modeling. For these models, pins were not defined
with across and through variables, and conservation laws were not applied to them. Several simple
models were discussed, followed by more involved models. Time-based and frequency-based
approaches to model development were explained.
160 Chapter 8Signal Flow (Non-Conserved) Modeling



chapter 9
Mixed-Signal Modeling
In the real world, there is no such thing as digital circuitry. All circuits and components are analog
elements that respond to things like charge, Kirchoff's voltage and current laws, and other rules of
nature. However, analyzing circuits in their native analog form would take such an enormous
amount of time that, practically speaking, it could not be done. The solution? We make certain
assumptions to simplify the way we characterize devices. One such assumption is that some device
types can have categorized drive and load characteristics that allow us to generalize the turn-on and
turn-off times as fixed relationships. Actual waveforms and exponential behavior then become
irrelevant and the number of calculations required to simulate and analyze these devices is
significantly reduced. This is the essence of digital simulation.
Unfortunately, not all aspects of a circuit and not all types of devices can be dealt with in this
manner. As a result, at some boundary, the approximations of digital must be dropped and the
reality of analog forces must be considered. This is the essence of mixed-signal modeling.
Mixed-signal simulators must incorporate two distinct fundamental approaches to simulation. The
following figure shows a design that includes both digital and analog components.
In this simple example, one might ask why are two approaches to simulation required, when there
are no fundamental distinctions between analog or digital parts? After all, they are all simply
electronic circuits bound by the same laws of physics. So why the need for two different
simulators?
The answer comes down to simulator performance. If analog simulators had virtually unlimited
speed and capacity, digital simulators would be unnecessary (with the exception of those used for
design synthesis). Unfortunately, this is not the case. Consequently, logic simulators and models are
developed to approximate logic functions, rather than their precise operational characteristics.
P P
N N
D i g i t a l A n a l o g
C l o c k
Simple mixed-signal circuit.
162 Chapter 9Mixed-Signal Modeling

Thus, logic parts are represented by simple Boolean descriptions of states and bear no resemblance
to the analog circuitry that comprises them.
The advantage of this approach is that these models can be simulated thousands of times faster with
digital simulators than they could be with analog simulators, and the accuracy levels are acceptable
for verifying logical circuit functions.
9.1. Solving Continuous and Discrete Systems
Using an analog simulator for circuits that have digital behavior provides precise detail for each
waveform but at a severe penalty in simulation time. The mixed-signal challenge is to develop a
simulator that allows interactions between models represented as digital (with states and timing
delays) and those represented as analog (with algebraic or differential equations).
Mixed-signal simulation means handling analog and digital technologies on several fronts. A
simulators internal programming must include digital and analog algorithms that communicate the
interaction between the two types of circuits. The simulator must also determine the different types
of data produced by each algorithm within one user display. It must be able to express analog and
digital circuits through supported modeling language(s). Finally, it must provide the analysis
mechanisms that answer the designers questions about circuit behavior.
Sample analog components along with their respective waveform types are shown in Figure 9.1-1.
Sample digital components along with their respective waveform types are shown in Figure 9.1-2.
For electrical circuits, analog simulators solve for voltage and current. These voltage and current
values are continuous. In other words, there are an infinite number of possible values. Analog
Figure 9.1-1. Analog circuit with example waveforms.
Figure 9.1-2. Digital circuit with example waveforms.
Solving Continuous and Discrete Systems 163


signals are also continuous in time, which means they cannot instantaneously change to different
values.
As discussed in Chapter 2, matrices are normally created inside the analog simulator for relating
these signals. Most analog simulators use an integrating algorithm that takes variable steps in time
(referred to as timesteps) and solves the matrix for all voltages and currents for each timestep.
Digital simulators, on the other hand, understand only a finite number of discrete values, called
states. States change only at specified times, called events. In a digital simulator, the digital
circuit is defined in functions that operate on or store states. When a function generates a state, it
places that event into an event queue, so that other signals attached to that function can evaluate the
effect of the new state. By limiting the range of state values, solving the circuit at discrete times,
and solving for only the functions affected by a changed state, a digital simulator can solve for
circuit function faster than an analog simulator could evaluate an equivalent analog circuit
description.
Mixed-signal simulators must perform a wide range of analyses. Analyses generally start with an
initial solution for all states, voltages and currents, from which the behavior of the circuit can be
observed in response to stimuli. Other analyses expand on the basic ones to determine
manufacturing information such as testability, expected yield, and fault tolerance.
The starting point is the Time 0 solution. In analog simulation, the concept of DC
operationbefore a dynamic stimulus is appliedis well understood. It is a static operating point
that exists when the voltage sources, VCC, VEE, and so on are applied to the circuit. A simplified
DC initialization flowchart follows.
In digital simulation, the analogous concept is initialization (Time 0 solution), though some digital
simulators do not have this concept at all and consider the initial setup as part of the time domain
simulation. In mixed analog-digital simulation, the concept of DC operation is important since the
analog portion of the simulator requires it.
Does
digital impact
analog
?
Set analog
matrix = 0
Y
N
Set gates = X
Run digital
until no events
Solve analog
matrix
Any
thresholds
crossed
?
System
solved
Run digital
events
N
Y
Figure 9.1-3. Mixed-signal DC initialization flowchart.
Y
N
N
Y
164 Chapter 9Mixed-Signal Modeling

For digital circuits, initialization means scheduling all stimulus values at Time 0 and evolving the
system until all events have expired. A simple maximum event count can be used to control
oscillations. For those digital simulators that do not understand initialization, the control
mechanism must understand how to correlate the digital time that represents Time 0 and the analog
DC operating point. Also, all feedback loops between analog and digital circuits must be reconciled
before a DC analysis is complete.
For time-domain analysis, mixed-signal simulators must have methods for synchronizing digital
events and analog timesteps. This concept is illustrated graphically in Figure 9.1-4.
9.2. Analog to Digital Modeling Techniques
When it comes to modeling, the process of going from analog to digital boils down to two basic
functions: detecting analog thresholds and scheduling digital events.
A. Detect Analog Thresholds
The most important capability on the analog side of analog-to-digital (A/D) mixed-signal models is
that of detecting the analog signal. This is typically accomplished through some sort of threshold
check. Both VHDL-AMS and MAST use similar techniques in this regard.
An important aspect of A/D modeling is that thresholds must be detected independently of the
timestep. In this way, threshold crossings can be detected with great accuracy.
t
n-1
t
n
t
n+1
(1)
t
event
x
n-1
x
n
x
n+1
(1)
x
n+1
(2)
2
Analog
1
3
Variable
t
Digital Event
Analog Time Point
Figure 9.1-4. Timestep control example for mixed-signal simulation.
The following explanations correspond
to the numbers shown in the figure.
Starting from t
n
(time "now"):
1. The integration algorithm first
calculates a solution for the system at
the next time point t
n+1
without
considering the digital events. So x
n

changes to x
n+1
(1)
.
2. The simulator then checks to see if any
event occurred between t
n
and t
n+1
.
3. An event affecting the analog
subsystem is detected at time t
event
.
The simulator rolls back and evaluates
the system at time t
event
. The point
x
n+1
(2)
is used, and x
n+1
(1)
is
discarded.
Analog to Digital Modeling Techniques 165


VHDL-AMS Threshold Detection
The primary mechanism for detecting analog thresholds in VHDL-AMS is the attribute qabove.
This attribute detects a threshold crossing independently of the timestep, and returns a boolean
signal as follows:
d0 <= qabove(lim_high)
Where q is a quantity that is compared against the threshold, lim_high. If q is below lim_high, d0 is
false; if q is above lim_high, d0 is true. An event occurs on d0 at the exact time of the threshold
crossing.
A negative-going threshold can be detected as follows:
d0 <= not qabove(lim_low)
Also, since qabove(thresh) returns a boolean signal, it can be used in the sensitivity list of a
process:
wait on qabove(thresh)
MAST Threshold Detection
In MAST, the threshold function is used to detect threshold crossings. The threshold function is
evaluated independently of the timestep. It is used this way:
threshold(expression1, expression2 [, beforestate [, afterstate ]])
Where:
expression1 is compared to expression2 continuously to see if a threshold condition has
been met.
Beforestate and afterstate are output variables of type state that can be used to determine how
the threshold condition was met. Beforestate and afterstate are assigned values by the
threshold function as follows:
Beforestate equals:
1 if expression1 > expression2 before the threshold
-1 if expression1 < expression2 before the threshold
0 if expression1 = expression2 before the threshold
Afterstate equals:
1 if expression1 > expression2 after the threshold
-1 if expression1 < expression2 after the threshold
0 if expression1 = expression2 after the threshold
MAST threshold examples will be illustrated in model listings. Additional information is presented
in Appendix B.
166 Chapter 9Mixed-Signal Modeling

B. Schedule Digital Events
Once the threshold crossings are detected, the effects of those crossings can be evaluated and
digitally scheduled. In both VHDL-AMS and MAST, scheduling events means assigning a logic
value to a digital pin or variable.
VHDL-AMS Event Scheduling
An example of scheduling an event in VHDL-AMS is:
dout <= vinabove(thresh)
When vin reaches the threshold thresh, a logic 1 is assigned to dout.
MAST Event Scheduling
To schedule an event in MAST, the following syntax is used:
[scheduling_id =] schedule_event (time, statevariable, expression)
Where:
scheduling_id (optional) is an array of two state variables. This array is assigned a unique
identifier when the event is scheduled, and can be used for descheduling the event.
time is an expression whose value indicates the time at which the assignment is to occur.
statevariable is the state variable that is to receive expression as its new value at time: time.
expression is evaluated when schedule_event is called, the resulting value is assigned to
statevariable at time: time.
Here is an example:
when(threshold(vin, thresh)) {
schedule_event(time+td, out, l4_0)
schedule_event(11.3n, next, 12 + previous)
}
In this example, when vin crosses the threshold, thresh, a logic 0 (l4_0) is scheduled on pin out at
time+td, and a real state value of 12 plus its previous value is scheduled on pin next at 11.3 ns
(previous is just the name of a variable which holds the old value. It can have any name).
C. Analog to Digital Model Examples
To illustrate analog to digital modeling, three devices will be presented: a comparator, a pulsewidth
modulator, and an 8-bit A/D converter.
Analog to Digital Modeling Techniques 167


Comparator
The comparator shown in Figure 9.2-1 accepts continuous analog signals at the input, and produces
a digital logic signal at the output. With the comparator enabled, if the signal on pin p is more
positive than the signal on pin m, then a logic 1 appears on the output pin, out. If p is less than m,
then a logic zero appears on the output. If the comparator is disabled, the output is set to a high
impedance state.
VHDL-AMS Comparator
library ieee;
use ieee.std_logic_1164.all;
use work.energy_systems.all;
use work.electrical_systems.all;
entity comparator is
generic(
td : time := 10 ns; -- propagation delay
p_offset : real := 0.0; -- Offset to positive input
m_offset : real := 0.0; -- Offset to negative input
hys : real := 1.0e-6; -- Input hysteresis
disable_state : std_logic := 'Z'); -- When enbl inactive
port(
terminal p : electrical;
terminal m : electrical;
enbl : in std_logic;
output : out std_logic := '0');
end entity comparator;
library ieee;
use ieee.math_real.all;
out
p
m
analog inputs
digital output
Figure 9.2-1. Mixed-signal comparator.
Digital output out is logic 1
when value at p > m.
Digital output is logic 0 when
value at p < m.
enbl
168 Chapter 9Mixed-Signal Modeling

architecture behavioral of comparator is
quantity vin across p to m; -- differential input of comparator_logic
begin
p1 : process
-- vh and vl are two threshold voltages and vh > vl.
-- output is high if vin > vh;
-- output is low if vin < vl;
-- Otherwise, output remains unchanged.
constant vh : real := p_offset - m_offset + ABS(hys)/2.0;
constant vl : real := p_offset - m_offset - ABS(hys)/2.0;
variable out_tmp : std_logic := '0';
begin
if vin'above(vh) then
out_tmp := '1';
elsif not vin'above(vl) then
out_tmp := '0';
end if;
if enbl = '1' or enbl = 'H' then
output <= out_tmp after td;
else
output <= disable_state after td;
end if;
wait on enbl, vin'above(vh), vin'above(vl);
end process;
end architecture behavioral;
The basic comparator function is achieved using the attribute vinabove(v1) in a process to detect a
threshold crossing on the analog input pins. In order to prevent oscillations about the threshold
level, a small hysteresis is also included in the definitions of the constants vh and vl.
The process is suspended after its body statements have been executed. It remains suspended until a
threshold crossing again occurs on either vh or vl.
Also, no simultaneous equation statements are needed because the digital side of the model is not
conserved. Lack of simultaneous equations for the analog input make this an ideal load to whatever
is driving it.
In this model, the analog input pins are defined as terminals, and will have across (voltage) and
through (current) variables associated with them. There are also two digital pins in this model, enbl
and output. As with signal flow pins, digital pins are not conserved, and will have a direction
associated with them. For example, the enbl pin receives a signal from somewhere outside the
model, and is therefore declared as type in; the output pin drives a signal to somewhere outside the
model and is declared as type out.
Both of these pins are also declared as subtype std_logic, which means their values will be confined
to whatever the std_logic subtype definition dictates. For example, if the std_logic X01Z subtype is
Analog to Digital Modeling Techniques 169


specified, the enbl and output pins will be restricted to one of the following values: X, 0, 1, or
Z.
MAST Comparator
template comparator p m out = td
electrical p, m # pin declarations
state logic_4 out # pin declaration
number td=0 # argument declaration
{
state nu before, after # local variables
when (dc_init) { # DC initialization
schedule_event(time, out, l4_0)
}
when (threshold(v(p), v(m), before, after)) {
if (after >= 0) schedule_event(time+td, out, l4_1)
else schedule_event(time+td, out, l4_0)
}
}
The when(threshold) statement is active whenever v(p) crosses v(m). If v(p) was less then v(m) and
then crossed it and became greater than v(m), the after simvar will be set high. So a test is
performed on after. If after is >= 0 (i.e. 1), v(p) must now be greater then v(m), and the output pin,
out, is set to a logic 1. For any conditions other than after >= 0, pin out is set to a logic 0.
Note the lack of an Equations section. This is for the same reason that the VHDL-AMS model does
not have any simultaneous equation statements: the digital side of the model is not conserved, and
the analog side presents an ideal load to whatever is driving it.
In a similar way, the analog input pins of the MAST comparator model are defined as electrical,
and will have across (voltage) and through (current) variables associated with them. There is also
one digital pin in this model, out, which is declared as type state. As with signal flow pins, state
pins are not conserved.
State pins in MAST have their values scheduled onto them at discrete instants in time, rather than
continuously as with analog pins. If the state pins are also defined as type logic_4, then the values
the pins can take is restricted to whatever the logic_4 definition in the units.sin file dictates. For
example, since the units.sin file specifies X01Z as permissible logic_4 values, the out pin will be
restricted to one of the following values: l4_X, l4_0, l4_1, or l4_Z.
170 Chapter 9Mixed-Signal Modeling

Pulsewidth Modulator
Pulsewidth Modulation (PWM) is a technique for transferring energy in high frequency discrete
bundles. The main reason PWM is used is because it is efficient. By operating semiconductor
devices in either an on of off mode, the power losses associated with running the devices in
their linear regions can be largely avoided. PWM is commonly used in motion control and power
supply designs.
A general idea of how PWM works is shown in Figure 9.2-2:
For pulsewidth modulation, an input signal is summed with a high frequency triangle waveform
which modulates the input signal. This modulated signal is fed to comparators, and when it crosses
an upper comparator threshold, a pulse is produced that is proportional in length to the amount of
time the modulated signal stays above the threshold. The same occurs when the modulated signal
crosses a lower threshold.
In the following model implementations, a simple PWM with a digital output will be illustrated.
VHDL-AMS Pulsewidth Modulator
library ieee;
use ieee.std_logic_1164.all;
use work.electrical_systems.all;
entity pwm is
generic (
init : std_logic := '0';-- initial state of the clock generator
delay : time := 0.0 us; -- delay time of the first event
Positive Input PWM
Negative Input PWM
Summer and Comparator
Input Signal
Modulation Signal
(high frequency)
Figure 9.2-2. Pulsewidth modulator operation.
(low frequency)
Analog to Digital Modeling Techniques 171


freq : real := 10.0e3;
vhigh : real := 5.0;
vlow : real := 0.0);
port (
terminal p,
m : electrical;
output : out std_logic);
end entity pwm;
architecture simple of pwm is
signal clk_int : std_logic;
constant half_period : time := (1.0/(2.0*freq))*1.0 sec;
quantity vin across p to m;
quantity dutycycle : real;
begin
p1 : process
begin
-- The output is initialized to the value of the init argument.
output <= init;
clk_int <= init;
wait on clk_int;
clk_int <= not clk_int after delay;
loop
wait on clk_int;
if clk_int = '1' then
clk_int <= not clk_int after dutycycle*half_period;
elsif clk_int = '0' then
clk_int <= not clk_int after (1.0-dutycycle)*half_period;
end if;
output <= clk_int;
end loop;
end process;
dutycycle == (vin - vlow) / (vhigh - vlow);
end architecture simple;
The key elements of this model are the loop that generates the clocking action, and the use of the
dutycycle quantity. The loop is activated when the clk_int signal changes state. Once in the loop, the
following lines control the duty cycle of the output signal:
if clk_int = '1' then
clk_int <= not clk_int after dutycycle*half_period;
elsif clk_int = '0' then
clk_int <= not clk_int after (1.0-dutycycle)*half_period;
end if;
172 Chapter 9Mixed-Signal Modeling

The duty cycle itself is a quantity whose value changes in proportion to the input voltage. This
relationship is established with the following:
dutycycle == (vin - vlow) / (vhigh - vlow);
Where vlow and vhigh set the input voltage limits within which normal PWM operation occurs.
MAST Pulsewidth Modulator
template pwm p m out = half_cycle, vlow, vhigh
electrical p, m
state logic_4 out
number half_cycle,
vlow=0,
vhigh=1
{
branch v = v(p, m)
state nu wake_up=0, dutycycle
when(dc_init) {
schedule_event(time, out, l4_0)
}
when(time_init) {
schedule_event(time, wake_up, ~wake_up)
}
when(event_on(wake_up)) {
if (v < vlow)schedule_event(time, out, l4_0)
else if (v > vhigh)schedule_event(time, out, l4_1)
else {
dutycycle = (v - vlow) / (vhigh - vlow)
schedule_event(time, out, l4_1)
schedule_event(time+half_cycle*dutycycle, out, l4_0)
}
schedule_event(time+half_cycle, wake_up, ~wake_up)
}
}
This is a slightly different PWM implementation than the VHDL-AMS version. The main
difference is that additional voltage level checks are added with this if statement:
if (v < vlow)schedule_event(time, out, l4_0)
else if (v > vhigh)schedule_event(time, out, l4_1)
Analog to Digital Modeling Techniques 173


These checks take the PWM out of normal operational mode when the input voltage falls outside
the range set by vlow and vhigh. This makes the template efficient since unnecessary events are not
scheduled. The clock of the MAST PWM occurs with the following statement:
schedule_event(time+half_cycle, wake_up, ~wake_up)
Where after a half-cycle of time elapses, the state variable wake_up toggles state, thereby creating a
clock. This sets the overall PWM switching frequency.
Each time the wake_up state variable changes state, the when statement when(event_on(wake_up))
is executed. If the input voltage vin is less than the vlow threshold, out is assigned a logic 0. If vin is
higher than the vhigh threshold, out is assigned a logic 1. If vin is between vlow and vhigh, PWM
action takes place.
The output of the PWM is set high by default. Then the desired dutycycle signal is calculated as a
fraction of the input signal to the total input signal range, and is used as a multiplier to half_period
to determine when to reset the output to 0. This is done by setting the output to 0 at the current
simulation time, time, plus dutycycle*half_period.
8-bit A/D Converter
One of the more popular uses for mixed-signal modeling is to develop A/D converters. Although
the implementation of the 8-bit A/D converter is more lengthy than previous models, the overall
concept is relatively straightforward. For example, given an input ramp waveform as shown in
Figure 9.2-3:
Figure 9.2-3. Example linear ramp voltage to ADC.
174 Chapter 9Mixed-Signal Modeling

The digitized output shown in Figure 9.2-4 would be expected:
As can be seen in Figure 9.2-4, the digital output starts with all bits set to zero, then counts up until
all bits are set to one (when the ramp input voltage reaches 5V at 0.1s). At 0.05s, the bit count
corresponds to a 2.5V input from the ramp (which changes linearly from 0V to 5V in 0.1s). From
the MSB, the bit count is: 01111111, which is halfway through the digital range.
VHDL-AMS and MAST model implementations of an ADC will now be given.
VHDL-AMS 8-bit A/D Converter
library ieee;
use ieee.std_logic_1164.all;
use work.electrical_systems.all;
use work.dsp_systems.all;
entity adc is
generic ( vmin : real; -- min voltage at input
vmax : real; -- max voltage at input
delay : time := 0 ns); -- per-bit delay
port ( start : in std_logic; -- start conversion
clock : in std_logic; -- per-bit conversion clock
eoc : out std_logic := '0'; -- End OF Conversion Output
d : out std_logic_byte := ('1','0','0','0','0','0','0','0');
terminal input, -- Electrical input
ref : electrical) ;
end entity adc;
Figure 9.2-4. Digitized output in response to ramp input.
Analog to Digital Modeling Techniques 175


architecture behavioral of adc is
type states is (ready, perform, complete);
quantity vin across input to ref;
begin
entity_adc : assert(vmax > vmin)
report "Wrong Scaling Range. vmax must > vmin."
severity error;
rin : entity work.resistor
generic map (rnom => 50.0)
port map ( p => input,
m => ref);
clock_proc : process
variable d_drv : std_logic_byte;
variable delta_v : real ;
variable input_hold : real ;
variable counter : integer := d_drv'high;
variable conv_flag : states := ready;
variable conv_end : std_logic := '0';
variable d_tmp : std_logic := '0';
begin
case conv_flag is
when ready =>
wait on start until start = '1' or start = 'H';
delta_v := vmax - vmin;
-- The input signal must be shifted to generate
-- normal offset binary
input_hold := vin - vmin;
counter := d'high;
eoc <= '0' after delay;
conv_flag := perform;
when perform =>
-- convert one bit during each clock cycle
delta_v := delta_v / 2.0;
-- set current bit
wait on clock until clock = '1' or clock = 'H';
if input_hold >= delta_v then
d_drv(counter) := '1';
input_hold := input_hold - delta_v;
else
d_drv(counter) := '0';
end if;
counter := counter - 1;
if counter < 0 then
conv_flag := complete;
end if;
when complete =>
-- the conversion has been completed
176 Chapter 9Mixed-Signal Modeling

-- make the conversion results accessible from ext. and
-- reset the end of conversion signal.
-- d <= d_drv after delay;
conv_end := '1';
eoc <= '1' after 2.0*delay;
conv_flag := ready;
end case;
if conv_end = '1' then
for i in d_drv'high downto d_drv'low loop
d(i) <= d_drv(i);
end loop;
conv_end := '0';
end if;
end process;
end architecture behavioral;
VHDL-AMS variables are used in the ADC model. As noted previously in the temperature-depen-
dent resistor model, variables are similar to constants, except that their values can change after they
have been declared.
The digital pin, d, as well as the variable d_drv are declared as type std_logic_byte. Std_logic_byte
is declared in the work.dsp_systems package as an 8-bit subtype of std_logic_vector (which is
undefined in size).
This model also introduces the case statement. The case statement is useful when decisions within
the model are to be made from a pre-defined list of choices. For example, the ADC model will be in
one of three "states" during simulation: ready, perform, or complete. These three states are declared
at the beginning of the architecture with
type states is (ready, perform, complete);
The case statement then checks to see which of these states is true, and executes the corresponding
statements using the following syntax:
when ready =>
"ready" statements;
when perform =>
"perform" statements;
when complete =>
"complete" statements;
The overall operation of the model is as follows: the variable conv_flag is initialized to ready. The
when ready case is therefore selected first, and the statements within it are executed. Inside the
when ready statement, statement execution waits for a rising edge on the start pin. The overall input
voltage range is calculated (vmax - vmin), and the input voltage is stored in variable input_hold.
Variable counter is assigned a value equal to the number of bits declared with pin d (using the
dhigh attribute), the end-of-conversion eoc pin is initialized to logic 0, and the conv_flag variable
is set to perform.
Analog to Digital Modeling Techniques 177


Now the when perform case statements are executed. The general operation of these statements is
as follows: the input voltage range is divided by two, which sets it to the value of one MSB. When
a rising clock edge occurs, this MSB value is compared to the input_hold voltage. If input_hold is
greater than the MSB value, the upper-most digital bit of intermediate logic_byte buffer d_drv is set
(this indexing is accomplished with the d_drv(counter) := 1 statement). The MSB value is then
subtracted from input_hold and the result is reassigned to input_hold. If the original MSB value was
greater than input_hold, then a logic 0 is assigned to d_drv. This process is continued (starting
with a new calculation for the MSB) until all of the digital output bits have been assigned a value.
At this point, the conv_flag variable is set to complete.
Now the when complete case statements are executed, which set the eoc variable to a logic 1 and
reset the conv_flag to ready. At this time the buffer values of d_drv are assigned to their respective
output pins.
MAST 8-bit A/D Converter
template adc8_l4 in refin start ena q7 q6 q5 q4 q3 q2 q1 q0 gnd = td
electrical refin, gnd, in
state logic_4 q7, q6, q5, q4, q3, q2, q1, q0, start, ena
number td = 1n # delay time to output results
{
state v vin, vref, ref0, ref1, ref2, ref3, ref4, ref5, \
ref6, ref7
state time outtime
# Initialize the converter for two conditions:
# 1) when ena goes inactive (l4_0), set outputs to l4_0 after delay, td.
# 2) if beginning dc or time analysis, and outputs are unknown
# (the default startup value is l4_X), then initialize them to l4_0.
when ((event_on(ena) & (ena == l4_0)) |
((dc_init | time_init) &
(q7 == l4_X) & (q6 == l4_X) & (q5 == l4_X) & (q4 == l4_X) &
(q3 == l4_X) & (q2 == l4_X) & (q1 == l4_X) & (q0 == l4_X))) {
if (ena == l4_0)outtime = time + td
else outtime = time
schedule_event(outtime, q7, l4_0)
schedule_event(outtime, q6, l4_0)
schedule_event(outtime, q5, l4_0)
schedule_event(outtime, q4, l4_0)
schedule_event(outtime, q3, l4_0)
schedule_event(outtime, q2, l4_0)
178 Chapter 9Mixed-Signal Modeling

schedule_event(outtime, q1, l4_0)
schedule_event(outtime, q0, l4_0)
}
# When conversion is required, break the reference voltage up into 8
# bits. These will be used to compare to the input voltage.
when (event_on(start) & (start == l4_1) & (ena == l4_1)) {
vin = v(in, gnd)
vref = v(refin, gnd)
vref = vref*0.5
ref7 = vref
ref6 = vref*0.5
ref5 = vref*0.25
ref4 = vref*0.125
ref3 = vref*0.0625
ref2 = vref*0.03125
ref1 = vref*0.015625
ref0 = vref*0.0078125
outtime = time + td
# Next, compare the input voltage to the MSB (ref7).
# If its greater or equal to MSB,
# set q7, subtract equiv. voltage of MSB from vin, and move on
# to next bit.
# MSB
if (vin >= ref7) {
vin = vin - ref7
if (q7 ~= l4_1) schedule_event(outtime, q7, l4_1)
}
else if (q7 ~= l4_0) schedule_event(outtime, q7, l4_0)
# Then, do the same test for the next most significant bit (ref6).
# Again, if vin
# is greater or equal to ref6, set q6, and subtract equiv. voltage of
# ref6 from vin and move on to the next bit.
# Next bit
if (vin >= ref6) {
vin = vin - ref6
if (q6 ~= l4_1) schedule_event(outtime, q6, l4_1)
}
else if (q6 ~= l4_0) schedule_event(outtime, q6, l4_0)
# Next bit
if (vin >= ref5) {
vin = vin - ref5
Analog to Digital Modeling Techniques 179


if (q5 ~= l4_1) schedule_event(outtime, q5, l4_1)
}
else if (q5 ~= l4_0) schedule_event(outtime, q5, l4_0)
# Next bit
if (vin >= ref4) {
vin = vin - ref4
if (q4 ~= l4_1) schedule_event(outtime, q4, l4_1)
}
else if (q4 ~= l4_0) schedule_event(outtime, q4, l4_0)
if (vin >= ref3) {
vin = vin - ref3
if (q3 ~= l4_1) schedule_event(outtime, q3, l4_1)
}
else if (q3 ~= l4_0) schedule_event(outtime, q3, l4_0)
# Next bit
if (vin >= ref2) {
vin = vin - ref2
if (q2 ~= l4_1) schedule_event(outtime, q2, l4_1)
}
else if (q2 ~= l4_0) schedule_event(outtime, q2, l4_0)
# Next bit
if (vin >= ref1) {
vin = vin - ref1
if (q1 ~= l4_1) schedule_event(outtime, q1, l4_1)
}
else if (q1 ~= l4_0) schedule_event(outtime, q1, l4_0)
# LSB
if (vin >= ref0) {
vin = vin - ref0
if (q0 ~= l4_1) schedule_event(outtime, q0, l4_1)
}
else if (q0 ~= l4_0) schedule_event(outtime, q0, l4_0)
}
}
The MAST model implementation is a little different than the VHDL-AMS model. In this case,
there is no clock or eoc (end of conversion) signals at all. The model simply receives a start
command, performs the analog to digital conversion instantly (in simulator time), then outputs the
results at that same instant plus a user-specified delay time. This model would therefore not be
appropriate if ADC conversion time itself was under investigation; it assumes the user knows what
the ADC conversion time will be, and just puts out the digital data when that time has elapsed.
180 Chapter 9Mixed-Signal Modeling

This model operates as follows: when a rising edge on the start pin is detected, the input reference
voltage is measured. From this reference, the respective analog values for each of the eight bits are
calculated. The input voltage is then compared with the MSB reference value. If it is greater than
the MSB reference value, the MSB digital pin is scheduled to a logic 1 at time, outtime, and the
MSB reference value is subtracted from the input voltage value. If the input voltage is less than the
MSB, the MSB digital pin is scheduled to a logic 0 at time, outtime.
The process is then repeated with the input voltage (which may be an MSB smaller) and the next
bit. When all of the bits have been set and time outtime is reached, the values will appear on the
digital pins of the model.
9.3. Digital to Analog Modeling Techniques
The process of going from digital to analog is achieved through three fundamental principles:
detecting digital events, synchronizing digital and analog signals, and providing continuous analog
transitions.
A. Detect Digital Events
In any digital to analog model, digital events must be detectable. This means that the model must
have a method for knowing when a digital event occurseither externally or internallyso that
some action can then be taken.
VHDL-AMS Event Detection
Events are detected in VHDL-AMS using the wait on function with sensitivities. The general form
used for event detection is:
label: process
process statements
wait on (sensitivity list)
For example:
clock: process
process statements;
wait on clk_int;
end process;
An equivalent form for this process would be:
clock: process (clk_int)
process statements;
end process;
In either of the previous clock process implementations, the process statements are executed each
time an event occurs on the clk_int signal.
Digital to Analog Modeling Techniques 181


MAST Event Detection
The method for detecting events in MAST is by using the event_on function. This function is used to detect
when some sort of transition, or event takes place so some action can then be taken.
Syntax:
when (event_on(statevariable [, oldvalue ]))
Where:
statevariable is the state variable to be monitored for an event. When an event is placed on statevariable,
the condition is true.
oldvalue (optional) is the name of a state variable, which, when statevariable receives a value, in turn
receives the previous value of statevariable. Thus, oldvalue is an output variable.
For example:
when (event_on(is)) {
...
}
This statement will cause whatever is in the braces to be executed whenever an event on is occurs.
when (event_on(is, was)) {
...
}
As above, this statement will cause whatever is in the braces to be executed whenever is changes state, and
also record the old value of is in the state variable was.
B. Synchronize Digital and Analog Signals
There must also be some method for ensuring that the digital simulation engine can be synchronized with the
analog engine. In this way, an analog timestep can be scheduled to occur simultaneously with a digital event,
even though the simulator, if left to itself, would not schedule a timestep at that particular time.
VHDL-AMS D to A Synchronization
Digital to analog synchronization in VHDL-AMS is accomplished with the break on statement. The break
on statement performs two primary functions: first, it instructs the simulator to take a timestep when it is
encountered; second, it optionally allows for quantities to be re-initialized after the break.
MAST D to A Synchronization
The primary MAST mechanism for forcing the simulator to evaluate the analog portions of the system is the
schedule_next_time function which was introduced in Section 7.2.
182 Chapter 9Mixed-Signal Modeling

C. Provide Continuous Transitions for Analog Signals
The third key to digital to analog conversion is extremely important. In essence, when transitioning
from digital to analog simulation, we are actually moving from a discontinuous world to a
continuous one. Instant transitions from one signal level to another, while perfectly permissible in
the digital world are devastating in the analog world. Example transition regions are shown in
Figure 9.3-1.
When analog signals change too quickly, they require inordinate amounts of simulation processing
time. Recall that all analog waveforms are actually constructed from discrete time segments called
timesteps. If transitions in the analog domain occur very rapidly, more timesteps will be required in
order to simulate the transitions.
When analog signals attempt to change levels instantaneously, the result is a discontinuity.
Discontinuities cause problems ranging from models that yield incorrect results to models that will
not converge at all.
Defining an Analog Transition Time
By exploring the rising-edge transition region of the analog waveform in Figure 9.3-1, we can
define an algorithm which guarantees a finite transition time. This algorithm and accompanying
illustration is shown in Figure 9.3-2.
(input)
(output)
old_out
new_out
Tbegin
Tend
tt
Digital transition
Analog transition
When changing from digital to
analog, special care must be
given to ensure no analog
discontinuities are introduced.
An analog transition region
must be defined.
Figure 9.3-1. Signal transitions in analog and digital domains.
new_out
old_out
Tbegin
Tend
tt
vout newout
oldout newout ( ) Tend ti me ( )
tt
------------------------------------------------------------------------------------------- + =
Figure 9.3-2. Analog transition algorithm with user-specified transition time.
Digital to Analog Modeling Techniques 183


The transition algorithm is derived as follows:
As the transition ramp is time-dependent, we can normalize it as follows:
Equation (9.3-1) results in a value between 0 and 1 throughout the ramping region. When applied to
the range of voltage, (old_out - new_out), it produces the following amount of voltage:
But this needs to be added to the final voltage for its reference, which yields:
where Tend - Tbegin is the transition time (tt), leaving:
Transition Time Example
Let tt = 1s, Tbegin = 2s (which puts Tend at 3s). Also, let old_out = 0V, and new_out = 5V. Evaluate
the output voltage at time = 2.4s. We should expect to see the output voltage reach 40% of its final
value, 5V. This should give an output voltage of (5V)*(.4) = 2V.
To test this, begin with the algorithm given in Figure 9.3-2:
Substituting in values for time:
Using this value, the original equation is expressed as:
Tend time
Tend Tbegin
--------------------------- (9.3-1)
oldout newout ( ) Tend time ( )
Tend Tbegin
----------------------------------------------------------------------------------------- (9.3-2)
vout newout
oldout newout ( ) Tend time ( )
Tend Tbegin
----------------------------------------------------------------------------------------- + =
(9.3-3)
vout newout
oldout newout ( ) Tend time ( )
tt
----------------------------------------------------------------------------------------- + =
(9.3-4)
vout newout
oldout newout ( ) Tend time ( )
tt
----------------------------------------------------------------------------------------- + =
(9.3-5)
Tend time
tt
----------------------
3s 2.4s
1s
-----------------
0.6 = = (9.3-6)
vout newout oldout newout ( ) 0.6 + =
(9.3-7)
184 Chapter 9Mixed-Signal Modeling

Which can be solved with voltages to give:
The output voltage level, at time 2.4s, is 2V. This is what we expected.
VHDL-AMS Continuous Analog Transition
SRamp(tr, tf) is a quantity that follows signal S, but with specified rise and fall times. The default
for tf is tr; the default for tr is 0.0. This implicit quantity provides linear ramping between signal
levels.
MAST Continuous Analog Transition
In MAST, the algorithm derived as (9.3-4) can be used to ensure a linear transition from one level
to another. This algorithm is repeated as Equation (9.3-9):
D. Digital to Analog Model Examples
To illustrate digital to analog modeling, two devices will be presented: a digitally-controlled analog
switch, and an 8-bit D/A converter.
Digitally-controlled Switch
In this model, the control signal ctl is digital, and the pins p and m are analog. Model
implementations are given next.
vout 5V 0V 5V ( ) 0.6 + 2V = = (9.3-8)
vout newout
oldout newout ( ) Tend time ( )
tt
----------------------------------------------------------------------------------------- + =
(9.3-9)
p m
ctrl
Figure 9.3-3. Digitally-controlled analog switch.
when ctrl = 0 switch is open
when ctrl = 1 switch is closed
when ctrl = x or z switch remains unchanged
Digital to Analog Modeling Techniques 185


VHDL-AMS Digitally-Controlled Switch
library ieee;
use ieee.std_logic_1164.all;
use work.energy_systems.all;
use work.electrical_systems.all;
entity switch_logic is
generic (
ron : real := 0.1; -- On resistance
roff : real := 1.0e9; -- Off resistance
tr : real := 1.0e-9; -- Rise time
tf : real := 1.0e-9); -- Fall time
port (
terminal p : electrical;
terminal m : electrical;
signal c : in std_logic); -- digital control signal
end entity switch_logic;
architecture simple of switch_logic is
quantity v across i through p to m;
signal reff : real := roff; -- effective resistance
begin
c1 : process
begin
if c = '1' or c = 'H' then
reff <= ron;
else
reff <= roff;
end if;
wait on c;
end process;
-- During transition, resistance varies linearly with time.
i == v / reff'ramp(tr, tf);
end architecture simple;
As seen in the VHDL-AMS implementation, signal reff is assigned either the ron or roff switch
resistance value depending on the position of the control signal c. Note the use of the ramp intrinsic
quantity, which ensures a linear ramp between output transitions. The duration of the ramp is
specified by tr (rising transition time) and tf (falling transition time).
186 Chapter 9Mixed-Signal Modeling

MAST Digitally-Controlled Switch
template swt crtl p m = ron, roff, tt
state logic_4 crtl
electrical p,m
number ron, roff, tt
{
branch v=v(p, m), i=i(p->m)
val nu R_sw
state time Tend = -1
state v new_out=roff, old_out=ron
state logic_4 old_crtl = l4_1
when (event_on(crtl)) {
if (crtl == l4_0 & old_crtl == l4_1) { # Open
old_crtl = l4_0 # input filtering
old_out = R_sw
new_out = roff
schedule_next_time(time)
Tend = time + tt
if (tt ~= 0) schedule_next_time (Tend)
}
else if (crtl == l4_1 & old_crtl == l4_0) { # Closed
old_crtl = l4_1 # Input filtering
old_out = R_sw
new_out = ron
schedule_next_time(time)
Tend = time + tt
if (tt ~= 0) schedule_next_time (Tend)
}
}
values {
if (time > Tend) R_sw = new_out
else R_sw = new_out + (Tend-time)*(old_out - new_out)/tt
}
equations {
i = v/R_sw # Use Ohms law
}
}
The main difference between the VHDL-AMS and MAST model implementations is that the
analog transition time must be explicitly defined in the MAST model. Equation (9.3-9) is adapted
Digital to Analog Modeling Techniques 187


for use in the switch model by making the switch resistance a val which can be made to transition
linearly from one resistance value to another.
8-bit D/A Converter
Digital to analog (D/A) converters "construct" analog signals out of digital bit patterns. For a D/A
converter, Figure 9.2-4 would represent the input, and Figure 9.2-3 would represent the output.
VHDL-AMS 8-bit D/A Converter
library ieee;
use ieee.std_logic_1164.all;
use work.electrical_systems.all;
use work.dsp_systems.all;
entity d2a is
generic (
vmax : real; -- High output
vmin : real); -- Low output
port (
signal data_in : in std_logic_byte; -- 8-bit vector input
terminal output : electrical; -- analog output
terminal ref : electrical); -- electrical reference
end entity d2a;
architecture behavioral of d2a is
signal sout : real := 0.0;
quantity vout across iout through output to ref;
begin
proc : process
variable v_sum : real;
variable delt_v : real;
begin
v_sum := vmin;
delt_v := vmax - vmin;
for i in data_in'high downto data_in'low loop
delt_v := delt_v / 2.0;
if data_in(i) = '1' or data_in(i) = 'H' then
v_sum := v_sum + delt_v;
end if;
end loop;
188 Chapter 9Mixed-Signal Modeling

sout <= v_sum;
wait on data_in;
end process;
vout == sout'ramp(100.0E-9);
end architecture behavioral;
The core of this model is the following for loop:
for i in data_in'high downto data_in'low loop
delt_v := delt_v / 2.0;
if data_in(i) = '1' or data_in(i) = 'H' then
v_sum := v_sum + delt_v;
end if;
end loop;
Starting with the highest (most significant) bit defined in the data_in vector (which is declared as
std_logic_byte - an 8-bit subtype of std_logic_vector), the loop first calculates a voltage reference
level as half of the total input range (vmax - vmin), which corresponds to the value of the most
significant bit (MSB). If the data_in bit is high, then this calculated voltage is added to the overall
output voltage sum, v_sum; if the data_in bit is low, no voltage is added. Then the next bit is
evaluated, and half of the previously-calculated voltage is added to the overall sum if the new
data_in bit is high. This process loops through the entire data_in vector, resulting in an output
voltage level which is proportional to the input bit pattern.
MAST 8-bit D/A Converter
template d2a8_l4 d7 d6 d5 d4 d3 d2 d1 d0 ena \
ref_in ref_out out vcc gnd = Td_e,Td_dat,slew,Rout,voffset,Vref, \
i_vcc,ena_true,ena_init
state logic_4 d7, d6, d5, d4, d3, d2, d1, d0, ena
electrical out, ref_in, ref_out, vcc, gnd
number Td_e = 20n, # Enable delay time
Td_dat= 50n, # Data minimum set-up time (after Tde)
slew = 10, # Slew rate of analog output in volts/usec (large sig)
Rout = 47, # Output Resistance
voffset = 0, # DC offset voltage for output
Vref = 10, # Internal Reference voltage
i_vcc = 20m, # Power supply load current
ena_true = 1, # Enable true state
ena_init = 0 # Force enabled at initialization -- enable can override
Digital to Analog Modeling Techniques 189


{
state time next=0, step=1, begin=0, datatime=0, entime=0
state v lvsum, vsum=0, dsum=0, data=0
state nu endtime[2], e_init=0
state logic_4 enable, entrue
val v vo, v_ref, vnorm, videal
var i i
var i iref
number Tslew
number pb7, pb6, pb5, pb4, pb3, pb2, pb1, pb0
parameters {
pb7 = 0.5
pb6 = 0.25
pb5 = 0.125
pb4 = 0.0625
pb3 = 0.03125
pb2 = 0.015625
pb1 = 0.0078125
pb0 = 0.00390625
Tslew = 1u/slew
}
i.vcc vcc gnd = i_vcc
# Initializing states
when ((dc_init | time_init) & (entrue == L4_X | ena_init==1)) {
if (ena_true == 0) entrue = l4_0
else entrue = l4_1
if (ena_init == 1) {
enable = entrue
e_init = 1
}
else enable = ena
}
# Enable pin minimum pulse-width determined here
when (event_on(ena)) {
# True
if (ena == entrue) entime = time
# Not true
else if ((ena ~= L4_x) & (ena ~= L4_z)) {
entime = time
}
# Schedule an event on "enable", "Td_e" from now to the value of "ena"
if (entime >= time)schedule_event (entime+Td_e,enable,ena)
190 Chapter 9Mixed-Signal Modeling

}
# Is there a change on any digital input AND
# is the enable pin low for the enable min time
# Then schedule an output change after data set-up time
when ((event_on(d0) | event_on(d1) | event_on(d2) | event_on(d3) |
event_on(d4) | event_on(d5) | event_on(d6) | event_on(d7)) &
# Ensure that the enable set-up time is not being violated
enable==entrue & (ena==entrue | e_init)) {
# initialize the "next output" calculated value
dsum = 0
# calculate the successive approx.
if (d7==l4_1) dsum = pb7
if (d6==l4_1) dsum = dsum + pb6
if (d5==l4_1) dsum = dsum + pb5
if (d4==l4_1) dsum = dsum + pb4
if (d3==l4_1) dsum = dsum + pb3
if (d2==l4_1) dsum = dsum + pb2
if (d1==l4_1) dsum = dsum + pb1
if (d0==l4_1) dsum = dsum + pb0
datatime = time + Td_dat
schedule_event(datatime,data,dsum)
}
# After the data set-up time or an enable change
when ((event_on(data) | event_on(enable)) &
(enable == ena | e_init) & ~dc_domain) {
# data event in
if (data) vsum = data
# enable went true
else if (enable == entrue)vsum = dsum
# enable went false
else vsum = 0
# current value of output, regardless of transition
lvsum = vnorm
if (Lvsum ~= vsum) {
if ((time>begin) & (time<next)) {
deschedule(endtime)
}
begin = time
next = begin + abs((Lvsum - vsum) * Tslew)
step = next - begin
schedule_next_time (begin)
endtime = schedule_next_time (next)
}
data = 0
}
Digital to Analog Modeling Techniques 191


# Analog system assignments
values {
v_ref= v(ref_in)-v(gnd)
# If in transition, interpolate
if ((time >= begin) & (time <= next)) {
vnorm = ((time-begin)/step) * (Vsum-Lvsum) + Lvsum
}
# Otherwise simply maintain the calculated value
# from the state calculation, above
else vnorm = vsum
# Actual output voltage source, including offset
# and reference voltage swing
videal = vnorm*v_ref + voffset
# Compensating for output resistance
vo = videal + i*rout
}
# Analog system simultaneous equations
equations {
# The current in the analog output sums to the system by i
i(out->gnd) += i
i(ref_out->gnd) += iref
# The current is adjusted such that the voltage on
# the output pins equals the calculated voltage from
# the values section
i: vo = v(out) - v(gnd)
iref: v(ref_out) -v(gnd) = Vref
}
}
This D2A model is a little more sophisticated than the VHDL-AMS version. The core of the actual
digital-to-analog conversion is similar, but extra behavioral features have been added, such as data
setup time control, output voltage offset, supply current, output resistance, and slew rate.
The output voltage is still determined by a successive approximation approach. The digital bit
pattern is evaluated one bit at a time. If a bit is high, the corresponding amount of voltage is added
to the state output dsum. Dsum is then scheduled to state variable data after the setup time, Td_dat.
If the model is enabled, the data value is transferred to the vsum state variable, which eventually
works its way to the vo value that is presented across the analog output pins.
This is an example of how a relatively simple model can become complex by adding behavioral
features which make it more realistic.
192 Chapter 9Mixed-Signal Modeling

9.4. Connecting Analog and Digital Models
Connectivity between analog and digital models requires special consideration. This subject should
not be confused with the interplay between the analog and digital algorithms. Rather, it concerns
how Boolean state changes are interpreted by analog models, and vice-versa.
A. Interface Models
The customary solution to the problem of interfacing analog and digital models is to insert a special
interface model directly between the digital and analog part. These interface models define the
analog characteristics of the digital pins to which they are connected. There are no corresponding
physical parts for these interface models. They are used only to change representations of signals
between the digital and analog domain.
Figure 9.4-2 shows where interface models would be inserted for a simple mixed-signal circuit.
The management of interface model insertion quickly becomes overwhelming without some type
of automation. Robust simulation tools solve this problem by having a schematic-to-simulation
conversion program automatically insert the appropriate interfaces between the digital and analog
parts. These tools read the schematic and separate the analog and logic parts into their appropriate
netlistsand determine where interface models are to be inserted. Supplying this information by
means of symbol properties or a "mapping" file makes placement completely transparent to the
designer.
V = L*di/dt
I = is*(e
v/vt
- 1)
out = A & B
set = /C + /D
What the analog simulator says... What the digital simulator says...
Figure 9.4-1. Analog and digital do not speak the same language.
P P
N N
Digital Analog
Clock
P P
N N
Digital Analog
d2a
a2d
Clock
Figure 9.4-2. Interface model insertion for mixed-signal circuits.
I/F
Models
Connecting Analog and Digital Models 193


As to the models themselves, a simple but possibly dangerous approach for developing interface
models is to design them to change logic level 0's and 1's to a corresponding set of voltages only,
such as Vol = 0V and Voh = 5V, for the analog portion of the circuit. This type of scheme may
provide simple functional operation, but without a rigorous concern for timing characteristics and
representative impedances, subtle analog electrical characteristics are lost.
The analog portion of the circuit must "see" the appropriate electrical properties at the node where
the interface model is inserted. Output loading, non-linear input parasitics, and input thresholds are
all considerations when defining an interface model. TTL, MOS, ECL, and other logic family
electrical characteristics must be definable. Even these categories can be resolved into finer
electrical characteristics. As an example, different logic devices have different types of TTL
outputs, and TTL characteristics change with different manufacturers and processes.
Almost all digital simulators allow unknown (X) and high-impedance (Z) states. The X state
indicates to a logic simulator that the state at a node is unknown, a state that the digital simulator
can handle. An analog simulator, however, must solve for all currents and voltages at every time
step, so an unknown state prevents it from reaching a solution. Similarly, the Z state indicates that a
node is not being driven to either state, in which case the rest of the system determines its value.
The interface models must know how to change to the proper analog electrical characteristics given
a Z state for an input. Finally, they must be able to model hysteresis where it exists in actual
components.
VHDL-AMS and MAST implementations of analog-to-digital and digital-to-analog interface
models are given next.
B. Example - A/D Interface Model
VHDL-AMS A2D Interface
library ieee;
use ieee.std_logic_1164.all;
use work.energy_systems.all;
use work.electrical_systems.all;
use work.ai_standard.all;
use work.hypermodels.all;
entity ide_a2dn is
generic (
strength : signal_strength := strong;
vxh : real := 2.8; -- upper bound of uncertain region
vxl : real := 1.8; -- lower bound of uncertain region
194 Chapter 9Mixed-Signal Modeling

rin : real := 1.0e6; -- input resistance
tt : real := 1.0e-9; -- transition time
cin : real := 1.0e-12; -- input capacitance
vlow : real := 0.2; -- output voltage low
vx : real := 2.5; -- output voltage unknown
vhigh : real := 4.8; -- output voltage high
ron : real := 0.1; -- output resistance. strong states
rweak : real := 1.0e4; -- output resistance. weak states
roff : real := 1.0e9; -- output resistance. high impedance
cout : real := 1.0e-11); -- output capacitance
port (signal d: out std_logic;
terminal a, m: electrical);
end entity ide_a2dn;
architecture Simple of ide_a2dn is
constant strength : signal_strength := strong;
constant vxh : real := model.vxh;
constant vxl : real := model.vxl;
constant rin : real := model.rin;
constant tt : real := model.tt;
quantity vin across iin through a to m;
begin
p1: process
constant td : time := 1.0 sec;
variable region : three_state := unknown;
variable above_vxh : boolean := true;
variable above_vxl : boolean := false;
constant logic_high : std_logic := reduced_logic(strength,'1');
constant logic_low : std_logic := reduced_logic(strength,'0');
constant logic_unknown : std_logic := reduced_logic(strength,'X');
begin
case region is
when one =>
d <= logic_high;
wait on vin'above(vxh);
-- The output goes into the uncertain region
region := unknown;
when unknown =>
d <= logic_unknown after tt*td;
-- The following if statement is used to determine initial
-- conditions. If analog input is low or high, digital output
-- will be set accordingly.
if vin < vxl then d <= logic_low;
elseif vin > vxh then d <= logic_high;
end if;
wait on vin'above(vxh), vin'above(vxl);
above_vxh := vin'above(vxh);
Connecting Analog and Digital Models 195


above_vxl := vin'above(vxl);
region := check_level (above_vxh, above_vxl);
when zero =>
d <= logic_low;
-- Conceptually, analog value is initialized to 'low
-- and therefore, region should be '0'. During dc analysis,
-- vxl should be crossed first if vin rises. If vin rises
-- to above vxh, then region will change again to '1'.
-- The vin'above(vxh) should not be used here.
-- However, In case vin starts at a value greater than vxl
-- the first transition will be missing.
-- Therefore, vxh is also tested here until it is no longer
-- needed.
wait on vin'above(vxh), vin'above(vxl);
above_vxh := vin'above(vxh);
above_vxl := vin'above(vxl);
region := check_level (above_vxh, above_vxl);
end case;
end process;
iin == vin/rin;
end architecture Simple;
In this model, the function check_level is used to assign appropriate case elements based on the
input level. The function is listed next:
function check_level(above_vxh, above_vxl : boolean)
return three_state is
begin
if above_vxh then
return one;
elsif not above_vxl then
return zero;
else
return unknown;
end if;
end function check_level;
It was not necessary to use this function in order to simplify the model. However, the function can
now be re-used by other models requiring a similar level check.
196 Chapter 9Mixed-Signal Modeling

This VHDL-AMS model implementation results in the waveforms illustrated in Figure 9.4-3:
As shown in the figure, an analog input voltage which ramps linearly across low and high threshold
levels will cause the indicated transitions to occur on the digital output of the model. The voltage
levels at which these transitions occur are specified with the parameters vxh and vxl.
This model ignores signals that pass through the unknown region (between vxl and vxh) faster than
the transition time, tt, as indicated by the positive-going ramp in the figure. If the analog input stays
within the unknown region for longer than tt, then the model waits until tt passes, then sets the
output into the unknown state until another threshold is crossed. This is shown with the
negative-going ramp in the figure.
MAST A2D Interface
template a2d a m d = td, il, ih
electrical a, m
state logic_4 d
number td=0, # input/output time delay
il=1.8, # input low voltage
ih=2.8 # input high voltage
{
state nu before, # variables for threshold
after # direction
when (dc_init) { # dc initialization
schedule_event(time, d, l4_0)
}
t(s)
0
1
x
0
Figure 9.4-3. VHDL-AMS analog-to-digital conversion model (1 bit).
Input
Output
vxh
vxl
t(s)
tt
Connecting Analog and Digital Models 197


# threshold crossing low
when (threshold(v(a)-v(m), il, before, after)) {
if ((after<0) & (driven(d)~=l4_0)) {
schedule_event(time+td, d, l4_0)
}
}
# threshold crossing high
when (threshold(v(a)-v(m), ih, before, after)) {
if ((after>0) & (driven(d)~=l4_1)) {
schedule_event(time+td, d, l4_1)
}
}
}
This MAST implementation of the 1-bit analog-to-digital conversion model is a little more ideal
than the corresponding VHDL-AMS model. While these models perform the same basic function,
the MAST model does not ignore signals that quickly transition through the unknown region, and it
also presents no loading to whatever is driving it.
This MAST model implementation results in the waveforms illustrated in Figure 9.4-4:
As shown in the figure, an analog input voltage which ramps linearly from low to high will cause
the indicated transitions to occur on the digital output of the model. The voltage levels at which
these transitions occur are specified with the parameters vxh and vxl.
t(s)
0
x
1
x
0
Figure 9.4-4. MAST analog-to-digital conversion model (1 bit).
Output
t(s)
Input
vxh
vxl
198 Chapter 9Mixed-Signal Modeling

C. Example - D/A Interface Model
VHDL-AMS D2A Interface
library ieee;
use ieee.std_logic_1164.all;
use work.electrical_systems.all;
use work.ai_standard.all;
entity ide_d2an is
generic ( vlow : real := 0.2; -- output voltage low
vx : real := 2.5; -- output voltage unknown
vhigh : real := 4.8; -- output voltage high
ron : real := 0.1; -- output resistance. strong states
rweak : real := 1.0e4; -- output resistance. weak states
roff : real := 1.0e9; -- output resistance. high impedance
tt : real := 1.0e-9);-- transition time
port (signal din: in std_logic;
terminal aout, ref: electrical);
end entity ide_d2an;
architecture Simple of ide_d2an is
-- The contents in std_logic:
-- ('U', 'X', '0', '1', 'Z', 'W', 'L', 'H', '-');
constant r_table: real_table :=
(ron, ron, ron, ron, roff, rweak, rweak, rweak, rweak);
constant v_table: real_table :=
(vx, vx, vlow, vhigh, vx, vx, vlow, vhigh, vx);
quantity vout across iout through aout to ref;
signal reff: real := ron; -- effective output resistance
signal veff: real := vx; -- effective output voltage
begin
p1 : process
begin
wait on din;
reff <= r_table(din);
-- In case din = 'z' the previous voltage will be
-- maintained. Therefore, veff will not change.
if din /= 'Z' then
veff <= v_table(din);
end if;
end process;
Connecting Analog and Digital Models 199


-- The iout current flowing through the branch from p to m.
-- veff is included the branch.
-- Therefore, a plus sign should be used here to calculate vout.
vout == veff'ramp(tt) + iout * reff'ramp(tt);
end architecture Simple;
This VHDL-AMS model implementation results in the waveforms illustrated in Figure 9.4-5:
As shown in the figure, a digital input voltage will cause the indicated transitions to occur on the
analog output of the model. The voltage levels at which these transitions occur are specified with
the parameters vlow, vx, and vhigh.
The constants r_table and v_table are declared as type real_table, which declares a nine element
array whose values correspond to those given by std_logic.
MAST D2A Interface
template d2a in p m = oh, ol, tt
state logic_4 in
electrical p, m
number oh = 4.8, # output high voltage level (logic 1)
ol = 0.2, # output low voltage level (logic 0)
tt = 1n # transition time
{
branch v=v(p,m), i=i(p->m)
state time Tend = -1
state v new_out, old_out
t(s)
0
x
1
x
0
0.2V
2.5V 2.5V
0.2V
4.8V
Figure 9.4-5. Digital-to-analog conversion model (1 bit).
Input
Output
tt
200 Chapter 9Mixed-Signal Modeling

state logic_4 old_in
when (event_on(in, old_in)) {
if (in ~= l4_x & in~= old_in) {
old_out = v # assures continuity
# even if output changes during output transition
if (in ==l4_0) new_out = ol
else new_out = oh
if (time_domain) {
schedule_next_time (time)
Tend = time + tt
if (tt ~= 0) schedule_next_time (Tend)
}
}
}
equations {
v = if (time > Tend) then new_out \
else new_out + (Tend-time)*(old_out - new_out)/tt
}
}
The performance of the MAST model is similar to that illustrated in Figure 9.4-5, however, this
model has no specification for an undefined input levelits output will remain unchanged for an
unknown logic input level.
To make the model more realistic, output resistance could be added as an input argument and
implemented as follows:
...
val v v_drv
...
when (event_on(in, old_in)) {
if (in ~= l4_x & in~= old_in) {
old_out = v_drv # assures continuity
...
}
values {
if (time > tend) then v_drv = new_out
else v_drv = new_out + (tend-time)*(old_out - new_out)/tt
}
equations {
v = v_drv + i*rout
}
}
As is often the case with more complex MAST models, a Values section has been added to keep the
model straightforward. Additional features such as a tri-state (high impedance) output can also be
Chapter Summary 201


implemented by declaring ron and roff resistance values, and having the model transition from ron
to roff whenever the input goes to a logic_Z.
9.5. Chapter Summary
This chapter has illustrated several mixed-signal models. Both analog-to-digital and
digital-to-analog conversions were discussed. On the A/D side, detecting thresholds was illustrated,
as well as digital state (signal) assignments. On the D/A side, detecting digital events was
discussed, as well as assigning analog values, and synchronizing the digital and analog simulators.
202 Chapter 9Mixed-Signal Modeling



chapter 10
Sampled Data Modeling
Discrete analog systems have grown tremendously in popularity over the past decade. Much of this
growth can be seen in the telecommunications industry. In addition, a variety of traditional analog
design functions have also been giving way to digital implementations. From automobile
controllers to standard control systems, digital signal processors (DSPs) and microprocessors now
permeate the industry.
This chapter will illustrate how to develop some basic sampled data systems, and also how to
transform s-domain functions into the z-domain.
10.1. Characteristics of Sampled Data Models
An example design made from sampled data (discrete) models is shown in Figure 10.1-1.
Sampled data models are different from physics-based models in the following respects:
Signals are discontinuous (they are digital in nature)
Conservation laws (e.g. KCL) do not apply
Signals have no units
Signals have no reference point
+
1 + az
-1
1 + bz
-1
_
kz
-1
Figure 10.1-1. Typical z-domain design.
204 Chapter 10Sampled Data Modeling

10.2. Z-Domain Building-Block Models
A. Sample/Hold (analog to z-domain)
Where r is the input signal, k is the sample number, T is the sample period, is the impulse
function, and t is the current time.
The characteristic equation for the sample/hold model represents the continuous input signal, r(t) as
a series of impulses. At any instant in time, the strength of the output impulse will be proportional
to the amplitude of the input signal. The z-domain sample/hold model converts a continuous analog
input into a sequence of event-driven analog states as shown in Figure 10.2-1.
If a smooth curve is used to connect the peaks of the sampled output in Figure 10.2-1, it can be seen
that a sinusiudal waveform will be approximated.
This model samples the difference between
the two analog input signals on the rising
edge of each clock pulse. The characteristic
equation is:
zout r kT ( ) t kT ( )
k 0 =

=
a2z
ain
zout
gnd
clock
r(t)
2T T 2T 3T 5T 6T 7T
4T
2T T 2T 3T 5 T 6 T 7 T 4T
r(t) r(kT)
t kT
a2z
ain
zout
gnd
clock
Figure 10.2-1. Z-domain sample/hold waveforms.
Z-Domain Building-Block Models 205


Each time a clock pulse in Figure 10.2-1 appears, the input signal level is sampled and stored. It is
then presented at the output until the next sample occurs. In the time-domain, a continuous
sinewave on the input of this component will appear at the output as shown in Figure 10.2-2.
VHDL-AMS and MAST model implementations of the sample/hold model are given next.
VHDL-AMS Sample/Hold
library ieee;
use ieee.std_logic_1164.all;
use work.energy_systems.all;
use work.electrical_systems.all;
entity sampleHold_1 is
generic (
clock_delay : TIME := 0.0 ns); -- delay time
port (
terminal ain : electrical;
terminal ref : electrical;
signal zout : out real := 0.0;
signal clock : in std_logic);
end entity sampleHold_1;
architecture simple of sampleHold_1 is
quantity vin across ain to ref;
begin
p_smp: process
begin
zout <= vin;
Figure 10.2-2. Sampled sinewave waveform.
206 Chapter 10Sampled Data Modeling

loop
if clock = '1' or clock = 'H' then
zout <= vin after clock_delay;
end if;
wait on clock;
end loop;
end process;
end architecture simple;
Zout is defined as a real signal of type out. Unlike signals of type std_logic, real signals of type out
(or in) can take on any value, but only at discrete instants in time. In this case, each time clock
occurs, loop is executed, and if clock is high, zout is assigned the current value of vin after the
clock_delay time has elapsed.
MAST Sample/Hold
# A template converting an analog signal a(t) to a discrete
# time state z[n]
# z[n] = a(nT), where T is the period of time of the sample
# signal at clock.
template a2z ain smp zout gnd = a, clock_delay
electrical ain, gnd
state nu smp, zout
number a = 1, # transfer gain of the template
clock_delay = 100n # Delay time to put sampled data out
{
val v Va # internal value of the output voltage
state nu znew=0, zold=0 # internal states of zout
when(dc_init | tr_start) {
# make sure that the state of znew will be updated at the beginning
# even if Va = 0, dc.
zold = undef
znew = a*Va
schedule_event(time,zout,znew)
}
Z-Domain Building-Block Models 207


when(event_on(smp)) {
znew = a*Va
if(znew ~= zold) {
schedule_event(time+clock_delay, zout, znew)
zold = znew
}
}
values {
Va = v(ain) - v(gnd)
}
}
Zout is defined as a state variable with nu units. Unlike state variables of type logic_4, this state
variable can take on any value, but only at discrete instants in time. When a clock pulse appears on
smp, intermediate state variable znew is assigned the value of the input voltage, Va, optionally
multiplied by gain a. If there is any change in znew from its previous value (now stored in zold),
znew is scheduled on pin zout at the current time plus clock_delay.
B. Linear Combination
VHDL-AMS Linear Combination
library ieee;
use ieee.std_logic_1164.all;
entity zlcmb2 is
generic (
a : real := 1.0; -- Coefficient to input
b : real := 1.0); -- Coefficient to input
port (
zin1 : in real; -- Input signal
This model takes the sum of two
event-driven inputs, optionally
multiplied by a gain factor. The
characteristic equation is:
zout a z in
1
b z in
2
+ =
zlcmb2
zin
1
zout
zin
2
208 Chapter 10Sampled Data Modeling

zin2 : in real; -- Input signal
zout : out real := 0.0); -- Output signal
end entity zlcmb2;
architecture simple of zlcmb2 is
begin
p1 : process
begin
zout <= a * zin1 + b * zin2;
wait on zin1, zin2;
end process;
end architecture simple;
Zin1 and zin2 are declared as real inputs; zout is declared as a real output. The inputs and output of
this model can therefore take on any value, but only at discrete instants in time.
MAST Linear Combination
# A linear combination function in z_domain
# The system function is
# H(z) = gain*(a*zin1 + b*zin2)
template zlcmb2 zin1 zin2 zout = a, b
# the input, output and the sampling signal
state nu zin1, zin2, zout
number a=1, b=1 # default coefficients to input states
{
state nu znew=0, zold=0 # internal states of zout
when(event_on(zin1) | event_on(zin2)) {
# calculate the present output state zout
znew = a*zin1 + b*zin2
if(znew ~= zold) {
schedule_event(time, zout, znew)
znew = zold
}
}
}
Z-Domain Building-Block Models 209


All of the pins of this model are declared as state nu, so they can take on any value, but only at
discrete instants in time.
C. Delay
VHDL-AMS Delay
-- A delay block in z domain (Called by zDelay)
-- H(z) = z**(-k)
-- The output signal is delayed by k clock cycles plus clock_delay.
-- If k = 0, there will be zero clock cycle delay plus clock_delay.
ibrary ieee;
use ieee.std_logic_1164.all;
entity zDelay is
generic (
k : natural; -- Delay cycles
init : real := 0.0; -- Initial value
clock_delay : time := 0 ns); -- Delay of sample event
port (
signal zin : in real; -- Input signal
signal clock : in std_logic; -- Sample signal
signal zout : out real := 0.0); -- Output signal
end entity zDelay;
architecture simple of zDelay is
begin
p_clock : process
subtype hold_vector is real_vector (0 to k);
variable hold : hold_vector;
begin
for i in hold'range loop
hold(i) := init;
The output state assumes the value of
the input delayed by k clock pulses.
The characteristic equation is:
zout n [ ] zin n k [ ] =
zdelay
zin zout
clock
210 Chapter 10Sampled Data Modeling

end loop;
-- TR code
loop
-- The contents in the hold register right shift by one bit
-- each time the clock goes high
if clock = '1' or clock = 'H' then
if k > 0 then
for i in k downto 1 loop
hold(i) := hold(i-1);
end loop;
end if;
-- The input signal goes into the most left bit and the
-- output signal is obtained from the most right bit.
hold(0) := zin;
zout <= hold(k);
end if;
wait on clock;
wait for clock_delay;
end loop;
end process;
end architecture simple;
We start this model implementation by declaring a vector which is the same length as the
user-specified number of cycle delays, k. This done by declaring a real_vector subtype called
hold_vector. Hold_vector is then a vector whose range is restricted from 0 to k. Another variable,
hold is declared to index hold_vector.
At the beginning of a simulation, each element of hold_vector is initialized to 0.0. Each time a
rising-edge of the clock occurs, the contents of each element in hold_vector is shifted one place to
the right. So, if k = 10, it will take ten clock cycles for the input of the delay model to propagate its
way to the output of the model.
MAST Delay
# a delay block in the z_domain. Its system function is
# H[z] = gain*z**(-k)
template zdelay zin smp zout = k, initi
# the input, output and the sampling signal
state nu zin, zout, smp
Z-Domain Building-Block Models 211


number k=1,
initi[*]=[0] # The initial state of the state array px
{
# The size of the array px must at least be k.
# The default size is 16. if k > 16, revise the size.
state nu px[16]
state nu znew=0,
# the index of the present input state in px
# if Tx = 6, then the present input state
# is stored in px[6].
Tx=0
# a state to hold the moment when an event occurs on smp
# this time is used to test whether the input state changes at
# the same time.
state time smp_time
when(dc_init | time_init) {
# to avoid reset when restart a transient analysis, time_init
# instead of tr_start is used in the condition.
# Reset px and Tx.
if(k > 0) {
Tx = k
}
smp_time = time
schedule_event(time, zout, znew)
}
when(k > 0 & event_on(smp)) {
# Forward the state wheel one slot ahead
Tx = Tx + 1
if(Tx > k) Tx = 1
# Obtain the current output state
znew = px[Tx]
if(znew ~= driven(zout)) {
schedule_event(time, zout, znew)
}
# Update the state which will become the output state
# in k clock cycles.
px[Tx] = zin
212 Chapter 10Sampled Data Modeling

# save the time information
smp_time = time
}
when(k > 0 & event_on(zin)) {
if(time == smp_time) {
# This is the case that the input signal changes at
# the same moment as smp changes. Update the state.
px[Tx] = zin
}
}
when(k == 0 & event_on(zin)) {
# No delay
# pass the input to the output immediately
znew = zin
if(znew ~= driven(zout)) {
schedule_event(time, zout, znew)
}
}
}
The MAST implementation is similar in principle to the VHDL-AMS model. In this case, an array,
px, is declared as the same size as the user-defined cycle delay, k, and variable Tx is used to index
the array.
10.3. Transforming From S-domain to Z-Domain
Z-domain modeling capabilities are only useful if the z-domain equations can be derived. This
section gives an example of how to transform a function described in the s-domain into the
z-domain, create difference equations, and design and write VHDL-AMS and MAST models. The
example is a single pole lowpass filter.
A. Transforming a Lowpass Filter
The transfer function for a 50Hz lowpass filter (314 rad/s) is given in Equation (10.3-1):
314
s 314 +
----------------- (10.3-1)
Transforming From S-domain to Z-Domain 213


The resulting frequency-domain response of (10.3-1) is shown in Figure 10.3-1:
As shown in the figure, this function represents a simple lowpass filter with a -3dB point at 50Hz.
Bilinear Transform
There are many methods for transforming an s-domain function into an equivalent z-domain
function. One of the most popular methods is the bilinear transform. This transformation entails
substituting the following expression for s in the system to be transformed:
Where T is the sample period, and z is the z-domain operator.
To convert the original s-domain transfer function into the z-domain, substitute 100us for T into
Equation (10.3-2), and substitute the resulting expression into (10.3-1):
Shown equivalently as:
Figure 10.3-1. S-domain waveform for lowpass filter.
2
T
---
1 z
1

1 z
1
+
-----------------



(10.3-2)
100u
2
------------
314 314z
1
+
1 0.968z
1

--------------------------------



(10.3-3)
0.0314 0.0314z
1
+
2.0314 1.9686z
1

----------------------------------------------- (10.3-4)
214 Chapter 10Sampled Data Modeling

The z-domain equivalent transfer function of (10.3-4) can then be simulated in the time domain,
and transformed into the frequency domain using the FFT transform. The resulting waveform is
shown along with the s-domain equivalent waveform in Figure 10.3-2.
The z-domain filter yields results that are the same as those obtained in the s-domain. An advantage
to working in the z-domain is that the sample clock frequency effects can be simulatedsomething
that cannot be done in the s-domain.
B. Creating Difference Equations
The next step in transforming an s-domain transfer function into software code is to create
difference equations from the z-domain function description. In this case, this can be accomplished
as follows:
Substituting k for z:
where k represents the current clock cycle; k-1 represents the previous clock cycle (one clock
delayed). Solving (10.3-6) for Y(k):
Which is in a format that can be directly used as software code.
Figure 10.3-2. S-domain and corresponding z-domain waveforms.
Y z ( )
X z ( )
------------
0.0314 0.0314z
1
+
2.0314 1.9686z
1

----------------------------------------------- = (10.3-5)
Y k ( )
X k ( )
------------
0.0314 k ( ) 0.0314 k 1 ( ) +
2.0314 k ( ) 1.9686 k 1 ( )
---------------------------------------------------------------- = (10.3-6)
Y k ( ) 0.01548X k ( ) 0.01548X k 1 ( ) 0.969Y k 1 ( ) + + = (10.3-7)
Transforming From S-domain to Z-Domain 215


C. Creating the Simulation Models
Two models will be developed to implement (10.3-7). The VHDL-AMS model combines the three
z-domain models, previously developed, into a test bench that fully implements the lowpass filter
circuit. The MAST model implements a behavioral approach and uses a C foreign subroutine to
implement (10.3-7) directly.
The z-domain implementation of the lowpass filter using the a2z, zdelay, and zlcmb2 models is
illustrated in Figure 10.3-3. The VHDL-AMS test bench is given next.
VHDL-AMS Lowpass Filter
library ieee;
use ieee.math_real.all;
use ieee.std_logic_1164.all;
use work.energy_systems.all;
use work.electrical_systems.all;
use work.ai_standard.all;
use work.dsp_systems.all;
entity ex_zdomain is
end ex_zdomain;
architecture struct of ex_zdomain is
-- Internal buses of this cell.
terminal vin : electrical ;
signal clk_in : std_logic;
signal a2zout, zout_sum1, x_delay, y_delay, y_out : real;
zdelay
clock
zlcmb2 a2z
clock
zlcmb2
zdelay
clock
Analog
Input
a = 0.01548
b = 0.01548
a = 1.0
b = 0.969
Y(K)
X(K)
Figure 10.3-3. Lowpass filter implemented with z-domain models.
216 Chapter 10Sampled Data Modeling

begin
v_sin : entity work.vsource_sine(simple)
generic map (
amplitude => 2.5,
freq => 500.0,
phase => 0.0,
offset => 0.0,
delay => 0.0e-3)
port map (
p => vin,
m => ground);
clk1 : entity work.clock_src(simple)
generic map (
ontime => 25.0 us,
offtime => 25.0 us,
init => '0',
delay => 0.0 ms)
port map (
output => clk_in);
a2z1 : entity work.a2z(simple)
generic map (
clock_delay => 0.0 ms)
port map (
clock => clk_in,
ain => vin,
ref => ground,
zout => a2zout);
zlcmb_1 : entity work.zlcmb2(simple)
generic map (
a => 0.01548,
b => 0.01548)
port map (
zin1 => a2zout,
zin2 => x_delay,
zout => zout_sum1);
zlcmb_2 : entity work.zlcmb2(simple)
generic map (
a => 1.0,
b => 0.969)
port map (
zin1 => zout_sum1,
zin2 => y_delay,
Transforming From S-domain to Z-Domain 217


zout => y_out);
zdelay_1 : entity work.zdelay(simple)
generic map (
k => 1,
init => 0.0,
clock_delay => 0.0 ms)
port map (
clock => clk_in,
zin => a2zout,
zout => x_delay);
zdelay_2 : entity work.zdelay(simple)
generic map (
k => 1,
init => 0.0,
clock_delay => 0.0 ms)
port map (
clock => clk_in,
zin => y_out,
zout => y_delay);
end struct;
This is basically a structural model implementation of the filter. In this case, the filter is driven by a
500 Hz, 10 V pk-pk sinewave.
The results from simulating this model are shown in Figure 10.3-4.
Figure 10.3-4. Simulation results for structural implementation of LPF.
218 Chapter 10Sampled Data Modeling

As shown in the figure, the input sinewave has a 10V pk-pk amplitude; the output sinewave has a
1V pk-pk amplitude. This factor of ten gain reduction is what we would expect for a 50 Hz lowpass
filter being driven by a 500 Hz sinewave.
MAST Lowpass Filter
# This is the MAST template that calls the subroutine "lowpass."
template zlowpass zin smp zout
state nu zin, smp, zout
{
foreign lowpass
state nu zin_m1, # Input states
zout_m0, zout_m1 # output states

# Initialize all states at DC analysis
when(dc_init) {
zin_m1 = 0
zout_m0 = 0
zout_m1 = 0
}
when (event_on(smp)) {
schedule_next_time(time) # Take analog timestep whenever smp occurs
zout_m0 = lowpass(zin) # This is the call to the subroutine
schedule_event(time, zout, zout_m0) # Schedule results on output pin
}
}
/* This is the C subroutine which implements the filter equation */

lowpass_(in,nin,ifl,nifl,out,nout,ofl,nofl,aundef,ier)
int *nin, *nifl, *nout, *ofl, *nofl, *ier;
double *in, *out, *aundef;
{
double zin, zin_m1;
double zout_m0, zout_m1;
int flag;
Chapter Summary 219


/* This flag is used to initialize variables the first time through */
if (flag != 1) {
zin_m1=0;
zout_m0=0, zout_m1=0;
}
flag = 1;
zin = in[0];
zout_m1 = zout_m0;
zout_m0 = 0.01548*zin + 0.01548*zin_m1 + 0.969*zin_m1;
zin_m1 = zin;
out[0] = zout_m0;
}
The MAST model is fairly straightforward: it waits for a clock signal, at which time it executes the
C subroutine, which implements (10.3-7) directly. The result of each subroutine call is then
returned to the MAST model, and scheduled on pin zout. This model yields results that are nearly
identical to those shown in Figure 10.3-4.
10.4. Chapter Summary
This chapter has discussed discrete analog models in VHDL-AMS and MAST. Several model
examples were given for basic z-domain building block components. An example of transforming
an s-domain transfer function description into a z-domain equivalent description was also given.
The z-domain transfer function was then transformed into a difference equation suitable for
software coding. The difference equations were coded, and implemented as a test bench in
VHDL-AMS, as well as written as a C subroutine for a MAST behavioral model.
220 Chapter 10Sampled Data Modeling



chapter 11
Hydraulic and Mechanical Modeling
A powerful and important feature of MSHDLs is their non-restrictive approach to modeling in
many energy domains. In this chapter we will illustrate hydraulic and mechanical simulation
models with an applicationan anti-lock brake system (ABS).
11.1. ABS System
The full ABS system is shown in Figure 11.1-1.
Figure 11.1-1. Full anti-lock brake system (ABS).
222 Chapter 11Hydraulic and Mechanical Modeling

The ABS system spans four technological boundaries: electronics, magnetic, mechanical, and
hydraulic. This span is not just conceptual, the actual models and system effects are described in
terms that are native to their domains.
To simplify the explanation of this ABS system, we will focus on one wheel in detail, as shown in
Figure 11.1-2.
After discussing the operation of the hydraulic system, we will look at VHDL-AMS and MAST
models for each technology, and then look at the mixed-technology models.
11.2. Hydraulic System Operation and Models
In this section we will look at the hydraulic operation of the ABS. We will first discuss the overall
hydraulic system before going on to the models for several hydraulic components.
The hydraulic system works as follows: when the brake pedal is pressed, an actuator in the pedal
builds up fluid pressure. The lower valve, valve_in is open and allows fluid to flow through rigid
Figure 11.1-2. Single wheel of ABS.
Hydraulic System Operation and Models 223


and flexible lines, where it fills the brake cylinder and displaces the brake shoe. The
fluid-displacement path for brake actuation is shown in Figure 11.2-1.
If the brake locks up, it is detected by a wheel sensor, and fed into the micro-computer, uC. The
computer commands the input valve, valve_in to close, and the return valve, valve_out to open. The
computer also starts up a pump which pulls fluid away from the brake cylinder, thereby preventing
lock-up. Returned fluid is stored in an accumulator, and some is also fed back to the brake pedal,
Figure 11.2-1. Brake actuation fluid path for ABS.
224 Chapter 11Hydraulic and Mechanical Modeling

providing some "feel" for the brake operator. The fluid-displacement path for brake release is
shown in Figure 11.2-2.
Basic ABS operation is shown in Figure 11.2-3.
Figure 11.2-2. Brake deactivation fluid path for ABS.
Figure 11.2-3. Sample response of ABS operation.
Hydraulic System Operation and Models 225


In Figure 11.2-3, the brake pedal is applied at 0.5s. The pressure builds and the brake locks up at
0.7s. This lock-up is detected in the wheel, and reported to the uC, which commands the drive
electronics for valve_in to close the valve, and for valve_out to open. The pressure then drops,
unlocking the brake, which is sensed and reported to the uC, which resets the valves to their
braking settings. With the brake pedal still applied, the pressure quickly builds back up until
locking is again detected between 0.8s and 0.9s. Once again the uC commands a pressure drop until
the brakes are no longer locked. Of special interest to the designer of this ABS system is the level
of the pressure spikes due to hoses flexing. These high spikes may result in resizing components
along the hydraulic path.
Four of the hydraulic component models which make up the ABS will now be described. The
models are:
Fluid chamber
Spring acting extend actuator
Accumulator
2-way valve
A. Fluid Chamber
Properties of the fluid chamber will be discussed next, followed by VHDL-AMS and MAST model
implementations.
Pressure - Force
The fluid chamber element models the pressure,
force and flow relationships for a moving
boundary linear actuating device. Pressure at the
node connected to pin p1 acts on the area to
create a force between the mechanical pins
mech1 and mech2. The flow rate into the
element is a function of both the relative velocity
of the mechanical pins and the compressibility of
the instantaneous volume of fluid.
mech1
mech2
p1
F P A =
F force applied between mech1 and mech2 =
P pressure at pin p1 =
A cross sectional area =
where
(11.2-1)
226 Chapter 11Hydraulic and Mechanical Modeling

Flow Rate
VHDL-AMS Fluid Chamber
use work.mechanical_systems.all;
use work.fluidic_systems.all;
entity fluid_cham is
generic (
area : real ; -- Cylinder area (m**2)
lvmin : real := 0.0); -- Length (mech1-mech2) where vol=0
port (
terminal p1 : fluidic; -- Hydraulic pin
terminal mech1 : translational; -- Mechanical translation pin #1
terminal mech2 : translational); -- Mechanical translation pin #2
end entity fluid_cham;
library ieee;
use ieee.math_real.all;
architecture simple of fluid_cham is
constant bulk : real := 689.5e6; -- Value of bulk modulus (N/m**2)
quantity posn across force through mech1 to mech2; -- Mechanical pins
quantity pres across flow through p1 to fluidic_ref; -- Fluidic pin(s)
Q
t d
d
Vol Vol_c + ( ) =
Vol length of fluid column A =
pos mech1 ) pos mech2 ( ) lvmin ( [ ] A =
where
Vol_c compressed volume of fluid =
P Vol
bulk
------------------ =
lvmin minimum length of fluid column =
bulk bulk modulus =
Q flow rate into the chamber =
(11.2-2)
Hydraulic System Operation and Models 227


-- Pressure in (N/m**2), Flow in (m**3/s)
quantity vol_p : real;-- Instantaneous physical cylinder (m**3) volume
quantity vol_f : real;-- Instantaneous physical cylinder (m**3) volume
begin
if (posn <= lvmin) use
vol_p == 0.0;
else
vol_p == (posn-lvmin)*area;
end use;
vol_f == vol_p + pres*vol_p/bulk;
force == area*pres;
flow == vol_f'dot;
end architecture simple;
The fluid chamber model introduces two new types of terminals: fluidic and translational. These
terminals must obey conservation laws, and they have across and through quantities associated with
them. The fluidic (hydraulic) pin has flow as the through quantity, and pressure as the across
quantity; the translational pins have force as the through quantity, and translational position as the
across quantity (as opposed to angular position).
This device is modeled such that either a mechanical input can cause fluid displacement, or fluid
displacement can cause translational mechanical movement. This model is used as the core
component of several hydraulic models.
MAST Fluid Chamber
template fluid_cham p1 mech1 mech2 = area, lvmin, pinit
hyd_mks p1 # Hydraulic pin
translational_pos mech1, # Mechanical connection #1
mech2 # Mechanical connection #2
number area, # Cylinder area (m**2)
lvmin = 0, # Length (mech1-mech2) where vol=0
pinit = undef # Initial pressure. (N/m**2)
export val frc_N force_mks # Force applied to piston. (N)
# Exportable for stress measure
{
val pos_m posn_mks # Instantaneous differential position. (m)
var q_m3ps q_mks # Flow into p1 (m**3/s)
val p_Npm2 pres_mks # Pressure inside (N/m**2)
228 Chapter 11Hydraulic and Mechanical Modeling

val vol_m3 vol_p_mks # Instantaneous physical volume of
# cylinder(m**3)
val vol_m3 vol_f_mks # Instantaneous physical volume of
# cylinder(m**3)
external number bulk # Global value of bulk modulus (N/m**2)
values {
pres_mks= p_Npm2(p1)
posn_mks = pos_m(mech1) - pos_m(mech2)
if (posn_mks <= lvmin) vol_p_mks = 0
else vol_p_mks = (posn_mks-lvmin)*area
vol_f_mks = vol_p_mks + pres_mks*vol_p_mks/bulk
force_mks = area*pres_mks
}
control_section {
initial_condition(p_Npm2(p1),pinit)
}
equations {
frc_N(mech1->mech2) += force_mks
q_m3ps(p1) += q_mks
q_mks: q_mks = d_by_dt(vol_f_mks)
}
}
As with the VHDL-AMS model, the MAST fluid chamber model introduces two new pin types:
hyd_mks (fluidic/hydraulic) and translational_pos (mechanical translational). These pins must obey
conservation laws, and they have across and through variables associated with them. The hydraulic
pin has flow as the through variable, and pressure as the across variable; the mechanical pins have
force as the through variable, and translational position as the across variable (as opposed to
angular position). These unit definitions and others are defined in the units.sin file.
As noted for the VHDL-AMS model, this fluid chamber is modeled such that either a mechanical
input can cause fluid displacement, or fluid displacement can cause translational mechanical
movement. Again, the fluid chamber model is used as the core component of several hydraulic
models.
Hydraulic System Operation and Models 229


B. Spring Acting Extend Actuator
The spring acting extend actuator is located in the brake pedal model. This actuator provides fluid
displacement as a function of applied mechanical force to the brake pedal.
The actuator itself is built from a fluid chamber, a spring, and a hard stop as follows:
The characteristics of the single acting extend actuator are modeled using the building blocks
shown above. This actuator can apply positive force between the rod and body pins as a function of
the pressure at pin p1. The internal spring acts to return the piston rod to the minimum length, lmin,
and defaults to a small, negligible value. Spring and hard stop models will be discussed later in this
chapter.
VHDL-AMS Actuator
use work.mechanical_systems.all;
use work.fluidic_systems.all;
230 Chapter 11Hydraulic and Mechanical Modeling

entity actr_e is
generic (
area : real ; -- Area of piston (m**2)
stroke : real ; -- Actuator stroke (m)
fmin : real := 0.0; -- minimum force of internal spring (N)
fmax : real := 1.0e-6; -- maximum force of internal spring (N)
kbot : real := 100.0e6; -- Spg. rate of stop at bottom of stroke (N/m)
dbot : real := 0.0; -- Damp factor of stop at bottom of stroke (N/(m/s)
ktop : real := 100.0e6; -- Spring rate of stop at top of stroke (N/m)
dtop : real := 0.0; -- Damp factor of stop at bottom of stroke (N/(m/s)
lmin : real := 0.0); -- minimum (retracted) length = min(rod - body)
port (
terminal p1 : fluidic; -- Hydraulic pin
terminal bdy : translational; -- Mechanical translation pin #1
terminal rod : translational);-- Mechanical translation pin #2
end entity actr_e;
library ieee;
use ieee.math_real.all;
architecture simple of actr_e is
constant k1 : real := (fmax-fmin)/stroke; -- Spring rate of
-- internal spring (N/m)
constant delta0 : real := lmin-(fmin/k1); -- Spring offset posn.
-- to set preload (m)
constant bulk : real := 689.5e6;-- Value of bulk modulus (N/m**2)
begin
fld_chm1 : entity work.fluid_cham(simple)
generic map (
area => area,
lvmin => lmin)
port map (
p1 => p1,
mech1 => rod,
mech2 => bdy);
spring1 : entity work.spring_nonlin_t(simple)
generic map (
k1 => k1,
k3 => 0.0,
delta0 => delta0)
port map (
pos1 => rod,
pos2 => bdy);
stop1 : entity work.stop_t(simple)
generic map (
pbot => lmin,
kbot => kbot,
Hydraulic System Operation and Models 231


ptop => stroke+lmin,
ktop => ktop,
dbot => dbot,
dtop => dtop)
port map (
pos1 => rod,
pos2 => bdy);
end architecture simple;
This is really a structural model implementation where VHDL-AMS modeling features are used
only to calculate the values for the input arguments.
MAST Actuator
template actr_e p1 rod body = area, stroke,lmin,fmin,fmax,
kbot,dbot,ktop,dtop
hyd_mks p1 # Hydraulic pin
translational_pos body, # Mechanical translation pin #1
rod # Mechanical translation pin #2
number area, # Area of piston (m**2)
stroke, # Actuator stroke (m)
fmin = 0, # minimum force of internal spring (N)
fmax = 1u, # maximum force of internal spring (N)
kbot=100meg, # Spring rate of stop at bottom of stroke (N/m)
dbot=0, # Damping factor of stop at bottom of stroke (N/(m/s)
ktop=100meg, # Spring rate of stop at top of stroke (N/m)
dtop=0, # Damping factor of stop at bottom of stroke (N/(m/s)
lmin = 0 # minimum (retracted) length = min(rod - body)
{
val frc_N force_mks # Total force (N)
val p_Npm2 pres_mks # Pressure inside (N/m**2)
external number bulk # Global value of bulk modulus (N/m**2)
number k1 # Spring rate of internal spring (N/m)
number delta0 # Spring offset posn. to set preload (m)
232 Chapter 11Hydraulic and Mechanical Modeling

parameters {
k1 = (fmax-fmin)/stroke
delta0 = lmin-(fmin/k1)
}
###...Netlist section.
fluid_cham.1 p1 rod body = area = area, lvmin=lmin
spring_t.1 rod body = k = k1, delta0 = delta0,include_stress=0
stop_t.1 rod body = pbot=lmin, kbot=kbot, ptop=stroke+lmin, ktop=ktop,
dbot=dbot,dtop=dtop,include_stress=0
###...End of netlist
}
This is a combination of a macromodel and a behavioral model. Parameters are passed in at the
top-level and calculations are made based on them. The results of these calculations are passed
down into the proper component models defined in the Netlist section of the overall model.
C. Accumulator
The characteristics of the spring loaded accumulator are modeled using the building blocks shown
above. The building block parameters are calculated to provide for the precharge, vmax and pvmax
values specified by the model user.
This device starts filling with fluid when the pressure at pin p1 exceeds the precharge pressure,
pcharge. It continues to fill against the linear spring characteristic until the volume reaches vmax.
As the pressure increases further, the fluid compresses as a function of the bulk modulus and
applied pressure.
Hydraulic System Operation and Models 233


VHDL-AMS Accumulator
use work.mechanical_systems.all;
use work.fluidic_systems.all;
entity accum_s is
generic (
area : real ; -- Accumulator piston area (m**2)
vmax : real; -- Maximum volume capacity (m**3)
pcharge : real; -- Precharge pressure (N/m**2)
pvmax : real; -- Pressure at volume = vmax (N/m**2)
damp : real := 0.0; -- Damping factor for piston (N/(m/s))
mass : real := 0.0);-- Mass of accumulator piston (kg)
port (
terminal p1 : fluidic); -- Hydraulic pin
end entity accum_s;
library ieee;
use ieee.math_real.all;
architecture simple of accum_s is
constant k1 : real := (pvmax-pcharge)*(area**2.0)/vmax; --Spg rt. (N/m)
constant bulk : real := 689.5e6; -- Value of bulk modulus (N/m**2)
terminal rod : translational; -- Internal mechanical pin
begin
fld_chm1 : entity work.fluid_cham(simple)
generic map (
area => area)
port map (
p1 => p1,
mech1 => rod,
mech2 => translational_ref);
spring1 : entity work.spring_nonlin_t(simple)
generic map (
k1 => k1,
k3 => 0.0,
delta0 => -pcharge*area/k1)
port map (
pos1 => rod,
pos2 => translational_ref);
stop1 : entity work.stop_t(simple)
generic map (
pbot => 0.0,
234 Chapter 11Hydraulic and Mechanical Modeling

kbot => 100.0e6,
ptop => vmax/area,
ktop => 100.0e6)
port map (
pos1 => rod,
pos2 => translational_ref);
mass1 : entity work.mass(simple)
generic map (
m => mass)
port map (
pos => rod);
damper1 : entity work.damper_t(simple)
generic map (
d => damp)
port map (
pos1 => rod,
pos2 => translational_ref);
end architecture simple;
The accumulator model is made up from a combination of existing components. Many hydraulic
models are developed using this structural approach.
MAST Accumulator
template accum_s p1 = area, vmax, pcharge, pvmax, damp, mass
hyd_mks p1
number area, # Accumulator piston area (m**2)
vmax, # Maximum volume capacity (m**3)
pcharge, # Precharge pressure (N/m**2)
pvmax, # Pressure at volume = vmax (N/m**2)
damp = 0, # Damping factor for piston (N/(m/s))
mass = 0 # Mass of accumulator piston (kg)
{
number k # Spring rate (N/m)
parameters {
k = (pvmax-pcharge)*(area**2)/vmax
}
Hydraulic System Operation and Models 235


# Netlist section.
fluid_cham.1 p1 rod 0 = area = area
spring_t.1 rod 0 = k = k, delta0 = -pcharge*area/k,
include_stress=0
stop_t.1 rod 0 = ptop=vmax/area, ktop=100meg, pbot=0, kbot=100meg,
include_stress=0
damper_t.1 rod 0 = d =damp
mass.1 rod = m=mass
# End netlist section.
}
Again, this model is built up from a combination of macromodeling and behavioral modeling
approaches.
The following 2-way valve models a variable area orifice type flow device that interfaces with
mechanical translational elements.
D. 2-Way Hydraulic Valve
The mechanical pin cntl varies the orifice area as a function of its position. There are no force
reactions within this model (no flow forces, springs and so on). This model includes an amin
parameter to specify an insignificant leak area so that numerical reference across the valve is
maintained. This value must be kept as small as possible relative to total valve area. This should
only be increased to help with simulation-related numerical reference problems.
236 Chapter 11Hydraulic and Mechanical Modeling

Pressure Flow Relationship
Where
In the following VHDL-AMS and MAST model implementations, there are two basic modes of
valve model operation, laminar flow, and turbulent flow. The models calculate which mode to use
by comparing the current differential pressure to the value of p_lam. The area of the valve opening
(slot) is determined by adding the minimum slot area, amin, to the product of the slot length (b) and
slot width (w).
Q cd_eff area
2P
rho
---------- =
(11.2-3)
Q flow rate through the valve =
P pressure differential =
area flow area = f ( cntl position, popen, pclose, amin) =
rho fluid mass density =
where
Reynolds Number, N
R
rho D
h
Q
mu area
------------------------- =
mu Absolute viscosity of fluid =
D
h
effective hydraulic diameter =
4 area
perimeter
------------------------- =
(11.2-4)
If N
R
rlam : <
If N
R
rlam
cd_eff cd turbulent coefficient of discharge , =
where cdlam
cd
rlam
---------------- =
cd_eff laminar coefficient of discharge =
cdlam N
R
=
(11.2-5)
Hydraulic System Operation and Models 237


VHDL-AMS Hydraulic Valve
use work.mechanical_systems.all;
use work.fluidic_systems.all;
use work.my_functions.all;
entity v_2way is
generic (
amax : real; -- flow area (m^2)
cd : real := 0.6; -- coefficient of discharge (nu)
rlam : real := 10.0; -- Reynold's No. for laminar/turb trans.(nu)
popen : real;-- Position of cntl when valve open
pclose : real := 0.0; -- Position of cntl when valve closed
offset : real := 0.0; -- Spool attachment offset/adjustment (m)
amin : real := 1.0e-12); -- minimum flow area (m^2)
port (
terminal p1, p2 : fluidic; -- Hydraulic pins
terminal ctl : translational);-- Mechanical translation pin
end entity v_2way;
library ieee;
use ieee.math_real.all;
architecture simple of v_2way is
constant rho : real := 1.0e3; -- Value of rho (kg/m**3)
constant mu : real := 14.3e-3;-- Value of mu (N-s/m**2)
constant b_max : real := b_max_chk(popen, pclose);
-- Maximum flow slot length (m)
constant sign_b : real := sign_b_chk(popen, pclose);
--Polarity of NO NC relationship (nu)
constant w : real := (amax - amin)/b_max; -- Width of the slot (m)
constant cdlam : real := cd/(SQRT(rlam));
-- Laminar flow coeff. for rectangular orifice (nu)
quantity delp across flow through p1 to p2;
quantity posn across ctl to translational_ref;
quantity p_lam : real; -- Pressure for turb-lam transition. (N/m^2)
quantity b : real; -- Variable length of the slot (m)
quantity b_eff : real; -- Effective flow slot length (m)
quantity dh : real; -- Hydraulic diameter of the slot (m)
quantity area : real; -- Slot (valve opening) area (m^2)
begin
b == sign_b*((posn - offset) - pclose);
-- Slot opening
238 Chapter 11Hydraulic and Mechanical Modeling


if (b <= 0.0) use
area == amin;
elsif (b > b_max) use
area == amax;
else
area == amin + b * w;
end use;
b_eff == area/w;
dh == 2.0*b_eff*w/(b_eff+w);
p_lam == ((cd*mu/dh)**2.0)/(2.0*rho*(cdlam**4.0));
if(delp >= p_lam) use -- Positive (+) turbulent flow
flow == cd*area*SQRT(2.0*delp/rho);
elsif(delp >= -p_lam) use -- Laminar flow (+ or -)
flow == ((2.0*area*(cdlam**2.0)*dh*delp)/mu);
else -- negative (-) turbulent flow
flow == (-cd*area*SQRT(-2.0*delp/rho));
end use;
end architecture simple;
For the VHDL-AMS model implementation, function calls were used to assign values to the b_max
and sign_b constants. These calculations are implemented as functions in order to simplify the
overall model listing. The functions are listed next.
function sign_b_chk (
popen : real;
pclose : real)
return real is
variable sign_b : real;
begin
if (popen > pclose) then
sign_b := 1.0;
else
sign_b := -1.0;
end if;
return (sign_b);
end function sign_b_chk;
function b_max_chk (
popen : real;
pclose : real)
return real is
variable b_max : real;
begin
if (popen > pclose) then
Hydraulic System Operation and Models 239


b_max := popen-pclose;
else
b_max := pclose-popen;
end if;
return (b_max);
end function b_max_chk;
Again note how the use clause is implemented with the conditional if statements. This is always the
case when simultaneous equations are included as part of the conditional statement.
MAST Hydraulic Valve
template v_2way cntl p1 p2 = amax, cd, rlam, popen, pclose, offset, amin
hyd_mks p1, # hydraulic inlet port
p2 # hydraulic outlet port
translational_pos cntl # spool position input
number amax, # flow area (m^2)
cd=.6, # coefficient of discharge (nu)
rlam=10, # Reynold's No. for laminar/turb trans.(nu)
popen, # Position of cntl when valve open
pclose=0, # Position of cntl when valve closed
offset=0, # Spool attachment offset/adjustment (m)
amin = 1p # minimum flow area (m^2)
{
<consts.sin
val q_m3ps q_mks # Flow through valve (m^3/s)
val p_Npm2 delp_mks # Differential pressure across valve (N/m^2)
val p_Npm2 p_lam # Pressure for turb-lam transition. (N/m^2)
val pos_m b # Variable length of the slot (m)
val pos_m b_eff # Effective flow slot length (m)
val pos_m dh # Hydraulic diameter of the slot (m)
val area_m2 area # Slot (valve opening) area (m^2)

struc {
number bp, inc
} ns[*] # Newton steps on pressure
240 Chapter 11Hydraulic and Mechanical Modeling


number b_max # Maximum flow slot length (m)
number sign_b # Polarity of NO NC relationship (nu)
number w # Width of the slot (m)
number cdlam # Laminar flow coeff. for rectangular orifice (nu)
external number rho # Global value of rho (kg/m**3)
external number mu # Global value of mu (N-s/m**2)
parameters {
if (popen > pclose) {
b_max = popen-pclose
sign_b = 1
}
else {
b_max = pclose - popen
sign_b = -1
}
w = (amax - amin)/b_max
cdlam = cd/(SQRT(rlam))
ns = [(-1,1.9),(1,0)]
}
values {
b = sign_b*((pos_m(cntl) - offset) - pclose) # Slot opening
delp_mks = p_Npm2(p1)-p_Npm2(p2)
if (b <= 0) {
area = amin
}
else if (b > b_max) {
area = amax
}
else {
area = amin + b * w
}
b_eff = area/w
dh = 2*b_eff*w/(b_eff+w)
p_lam = ((cd*mu/dh)**2)/(2*rho*(cdlam**4))

if(delp_mks>=p_lam) { # Positive (+) turbulent flow
q_mks=cd*area*SQRT(2*delp_mks/rho)
}
else if(delp_mks>=-p_lam) { # Laminar flow (+ or -)
q_mks=((2*area*(cdlam**2)*dh*delp_mks)/mu)
}
else { # negative (-) turbulent flow
q_mks=(-cd*area*SQRT(-2*delp_mks/rho))
}
}
Mechanical System Operation and Models 241


control_section {
newton_step(delp_mks,ns)
}
equations{
q_m3ps(p1->p2) += q_mks
}
}
We see in the MAST implementation that the bulk of the equations describing the system are
located in the Values section. This is done for the sake of clarity in the model, and helps to keep the
Equations section from becoming too cumbersome.
11.3. Mechanical System Operation and Models
One of the key components to the ABS system is the hydraulic valve that controls the direction and
volume of fluid flow throughout the system. The fluidic characteristics of the valve have already
been discussed, but the entire valve model itself is built from a combination of electro-magnetic,
hydraulic, and mechanical components and effects as shown in Figure 11.3-1.
Before exploring the valve model in detail, a few words are in order with regards to how
mechanical systems are typically represented for use with MSHDLs. Figure 11.3-1 may seem a
little strange to a mechanical designer. This stems from the different ways in which mechanical and
electrical engineers view systems.
Figure 11.3-1. ABS valve model topology.
242 Chapter 11Hydraulic and Mechanical Modeling

A mechanical engineer may find that the system shown in Figure 11.3-2 represents a basic
mass-spring-damper system in a familiar configuration: the mass, spring, and damper are
connected together, and suspended between two rigid bodies.
For this system, the mass is displaced distance x as a result of the applied force, F. The total
generated force, F, minus inertial, spring, and damping forces, must always sum to zero. This
equation is of the same form as any equation to be solved using conservation laws. In this case, the
through variable is force, and the across variable is position.
While this mass-spring-damper implementation may be familiar, it is not in an optimum form to be
simulated. To look at it another way, the same system is redrawn in Figure 11.3-3.
Figure 11.3-3, though technically representing the same system as shown in Figure 11.3-2, helps to
illustrate two things: first, it shows a source drivera force source which contributes a quantity of
the through variable to the system. Second, the mass has been repositioned to highlight that it is the
Figure 11.3-2. Simple mass-spring-damper system and characteristic equation
The conservation laws
governing this system can be
stated as:
F m
t
2
d
d x
d
t d
dx
kx 0 =
Figure 11.3-3. Modified mass-spring-damper representation.
Mechanical System Operation and Models 243


position of the mass which we will be analyzing (it is the mass that we are trying to accelerate with
a force). In this figure, we can see that the force source exerts a force on the mass, the movement of
which is influenced by the attached spring and damper. A final variation of this system is given in
Figure 11.3-4.
The mechanical system now appears in a format consistent with other technologies simulated with
MSHDLs. Here we have a force source driving a system node called "x." This node value
represents position, and its movement will be governed by all of the mechanical effects connected
to itone of which is mass.
For example, if the force source applies 5N to node x, and the spring is preloaded to 4 meters, the
total static displacement would be F/k = 5/1 = 5 meters from the source, plus 4 meters from the
preload, resulting in a total of 9 meters of displacement.
Now that we have discussed the general approach to representing mechanical systems with
computer simulation tools, we will discuss the operation of the valve in Figure 11.3-1 (redrawn as
Figure 11.3-5 for convenience):
Figure 11.3-4. Final mass-spring-damper representation.
Figure 11.3-5. ABS valve model topology.
244 Chapter 11Hydraulic and Mechanical Modeling

We have already discussed the hydraulic core of the valve model itself. But the core model does not
specify any mechanical properties for the valve spool. Figure 11.3-5 represents the valve itself as
well as the mechanical effects which govern the spool movement.
To operate the valve, electronic command signals are given to the electro-magnet. The
electro-magnet forces a mechanical piston in the solenoid to move. The mechanical characteristics
of the solenoid piston are given by the mass, spring, damper, and hard stop effects shown in the
figure. The mechanical piston movement displaces the mechanical spool at the valve input.
Each of the mechanical effects used to govern the valve spool movement will now be discussed:
A. Translational Mass
VHDL-AMS Mass
use work.mechanical_systems.all;
entity mass is
generic (m : real); -- Mass constant
port (terminal pos : translational); -- Position connection
end entity mass;
architecture simple of mass is
quantity posn across force through pos to translational_ref;
begin
assert m > 0.0
report "Mass should be greater than 0!"
severity error;
force == - m * posndotdot;
end architecture simple;
pos
This model represents a mechanical
mass. An acceleration of the mechanical
connection (pos) produces a reaction
force proportional to that acceleration.
The characteristic equation is:
F ma m
t
2
d
d x
= =
Mechanical System Operation and Models 245


MAST Mass
template mass pos = m, units
translational_pos pos # Position connection.
number m # Mass constant.
mech_def..units units = mks # Selects "units" assumed for arguments.
{
val pos_m posn_mks # Position (meters).
var vel_mps velo_mks # Differential velocity (meters/sec).
values {
posn_mks = pos_m(pos)
}
equations {
frc_N(pos) += d_by_dt(-m*velo_mks)
velo_mks: velo_mks = d_by_dt(posn_mks)
}
}
The MAST mass model implementation again uses an intermediate var to perform double
differentiation. In this model, this var is called velo_mks and declared as pin type vel_mps because
the first derivative of position is velocity. The argument definition (argdef) statement
mech_def..units units = mks is used to select mks as the type of units for this model. Argdefs were
introduced in Chapter 4.
B. Translational Nonlinear Spring
pos1
pos2
This models behavior is such that a differential
position between the input connections (pos1 and
pos2) produces a force proportional to that
difference. The characteristic equation is:
where x = pos1 - pos2, and delta0 is the
equilibrium position of the spring.
force k1 x delta0 ( ) k3 x delta0 ( )
2
=
246 Chapter 11Hydraulic and Mechanical Modeling

VHDL-AMS Nonlinear Spring
use work.mechanical_systems.all;
entity spring_nonlin_t is
generic ( k1: real; -- Linear spring coefficient [Unitless]
k3: real := 0.0; -- Third power spring coefficient[Unitless]
delta0 : real := 0.0);-- Equilibrium position of spring,
-- where force = 0.
port (terminal pos1, -- Position connection 1
pos2 : translational); -- Position connection 2
end entity spring_nonlin_t;
architecture simple of spring_nonlin_t is
quantity posn across force through pos1 to pos2;
begin
force == -k1*(posn - delta0) - k3*(posn - delta0)**3;
end architecture simple;
For the following MAST model implementation, a linear version of the spring will be illustrated.
This is accomplished by neglecting the k
3
term, used in the VHDL-AMS model.
MAST Linear Spring
template spring_t pos1 pos2 = k, delta0, units
translational_pos pos1, # Position connection 1.
pos2 # Position connection 2.
number k, # Spring constant.
delta0 = 0 # Equilibrium position of spring (where force = 0).
mech_def..units units = mks # Selects "units" assumed for arguments.
{
val pos_m posn_mks # Differential position (meters).
val frc_N force_mks # Force in Newtons
Mechanical System Operation and Models 247


values {
posn_mks = pos_m(pos1) - pos_m(pos2) # Distance between the
# inputs (meters).
force_mks = -1*k*(posn_mks - delta0) # Restraining force (N).
}
equations {
frc_N(pos1->pos2) += force_mks
}
}
C. Translational Damper
VHDL-AMS Mechanical Damper
use work.mechanical_systems.all;
entity damper_t is
generic ( d: real); -- Translational damping constant.
port (terminal pos1, -- Position connection 1
pos2 : translational);-- Position connection 2
end entity damper_t;
architecture simple of damper_t is
quantity posn across force through pos1 to pos2;
begin
force == -d*posndot;
end architecture simple;
This model represents a linear damper (dashpot).
A relative translational velocity between the
mechanical connections produces a damping
force proportional to that velocity. The
characteristic equation is:
where x = pos1 - pos2.
F d
t d
dx
=
248 Chapter 11Hydraulic and Mechanical Modeling

MAST Mechanical Damper
template damper_t pos1 pos2 = d, units
translational_pos pos1, # Position connection 1.
pos2 # Position connection 2.
number d # Translational damping constant.
mech_def..units units = mks # Selects "units" assumed for arguments.
{
val pos_m posn_mks # Differential position (meters).
values {
posn_mks = pos_m(pos1) - pos_m(pos2) # Distance between the
# inputs (meters).
}
equations {
frc_N(pos1->pos2) += d_by_dt(-d * posn_mks)
}
}
D. Translational Hard Stop
VHDL-AMS Mechanical Hard Stop
use work.mechanical_systems.all;
use work.ai_standard.all;
This model represents a two-position hard stop
(mechanical limit). When the relative position
(pos1 - pos2) is within the limits, the model
exerts no force. However, a stiff mechanical
spring and damper provide a restraining force
beyond the travel limits. The characteristic
equations are described in the model listings.
Mechanical System Operation and Models 249


entity stop_t is
generic (ktop : real := 0.0; -- Stiffness of "stop" at top.
dtop : real := 0.0; -- Damping factor of "stop" at top.
ptop : real := undef; -- Position of top stop.
kbot : real := 0.0; -- Stiffness of "stop" at bottom.
dbot : real := 0.0; -- Damping factor of "stop" at bottom.
pbot : real := undef); -- Position of bottom stop.
port (terminal pos1, pos2 : translational); -- Position connections
end entity stop_t;
architecture simple of stop_t is
quantity posn across force through pos1 to pos2;
quantity vel : real; -- Relative velocity (m/s).
begin
if (posn > ptop and ptop /= undef and ptop /= inf) use
force == -1.0*ktop*(posn - ptop) - dtop*vel;
elsif (posn < pbot and pbot /= undef and pbot /= inf) use
force == kbot*(pbot - posn) - dbot*vel;
else
force == 0.0;
end use;
vel == posn'dot;
end architecture simple;
This model essentially checks to see if the input position, posn, is greater than ptop, or less than
pbot. If either condition is true, the appropriate force equations are applied; if posn is within the
limits imposed by ptop and pbot, no force is contributed by the model.
MAST Mechanical Hard Stop
template stop_t pos1 pos2 = ktop, dtop, ptop, kbot, dbot, pbot, units
translational_pos pos1, # Translational position 1 connection.
pos2 # Translational position 1 connection.
number ktop = 0, # Stiffness of "stop" at top.
dtop = 0, # Damping factor of "stop" at top.
ptop = undef, # Position of top stop.
kbot = 0, # Stiffness of "stop" at bottom.
dbot = 0, # Damping factor of "stop" at bottom.
250 Chapter 11Hydraulic and Mechanical Modeling

pbot = undef # Position of bottom stop.
mech_def..units units = mks # Selects "units" assumed for arguments.
{
var vel_mps velocity # Relative velocity (m/s).
val pos_m posn_mks # Relative position (meters).
val frc_N force_mks # Force in Newtons
values {
posn_mks = pos_m(pos1) - pos_m(pos2)
if (posn_mks > ptop & ptop ~= undef & ptop ~= inf) {
force_mks = -1*ktop*(posn_mks - ptop) - dtop*velocity
}
else if (posn_mks < pbot & pbot ~= undef & pbot ~= inf) {
force_mks = kbot*(pbot - posn_mks) - dbot*velocity
}
else {
force_mks = 0
}
}
equations {
frc_N(pos1->pos2) += force_mks
velocity: velocity = d_by_dt(posn_mks)
}
}
As with the VHDL-AMS implementation, this model checks to see if the input position, posn, is
greater than ptop, or less than pbot. If either condition is true, the appropriate force equations are
applied. If posn is within the limits imposed by ptop and pbot, no force is contributed by the model.
11.4. Mixing Technology Domains
Multiple energy domains can be combined in a single model in both VHDL-AMS and MAST. The
2-way valve model presented earlier was an example of this capability: the controlling spool port
was mechanical in nature (with force and position as respective through and across variables), and
the hydraulic ports were fluidic in nature (with flow and pressure as respective through and across
variables).
We will now discuss two additional mixed-technology models associated with the ABS system.
First, we will present the electro-mechanical motor which drives the system pump; then we will
discuss the pump itself, which is modeled with a combination of mechanical and hydraulic
properties.
Mixing Technology Domains 251


A. Electrical/Mechanical DC Motor
Characteristic Equations
Electrical
v
r
= i r # voltage across winding resistance
v
gen
= K
e
# back-emf (voltage constant*shaft velocity)
# voltage across winding inductance:

v
l
=

v
p
- v
m
= v
r
+ v
gen
+ v
l
# KVL applied to electrical side of motor
Mechanical
viscous loss = d # constant damping factor*shaft velocity
torque
gen
= i K
T
# (input current)*(torque constant)
momentum = j # shaft moment of inertia*shaft velocity
# Conservation of torque applied to mechanical side of the motor:
torque
rotor
= torque
gen
- - visc. loss
This is a DC motor model with a permanent
magnet surrounding the rotor. It accepts electrical
input to the armature connections and provides a
rotational mechanical output. The characteristic
equations are described below.
d(li)
dt
d(momentum)
dt
252 Chapter 11Hydraulic and Mechanical Modeling

VHDL-AMS DC Motor
use work.electrical_systems.all;
use work.mechanical_systems.all;
entity dc_motor is
generic (
kt: real := 6.405e-3; -- torque constant
j: real := 5.0e-7; -- shaft (rotor) moment of inertia
r: real := 50.0; -- stator winding resistance
ke:real := 6.405e-3; -- voltage constant
d: real := 3.0e-6; -- viscous damping constant
l: real := 40.0e-3); -- stator winding inductance
port (terminal p, m : electrical;
terminal rotor: rotational_v );
end entity dc_motor;
architecture dc_motor_bhv of dc_motor is
quantity vel across torque through rotor to rotational_v_ref;
quantity vin across iin through p to m;
begin
vin == l*iin'dot + iin*r + ke*vel;
torque == iin*kt - j*vel'dot - d*vel;
end architecture dc_motor_bhv;
The VHDL-AMS motor model introduces a new mechanical terminal type: rotational_v. This
terminal must obey conservation laws, and has across and through quantities associated with it. It
has torque as the through quantity, and angular velocity as the across quantity (as opposed to
translational velocity).
MAST DC Motor
template dc_motor p m rotor stator = ke, kt, j, d, l, r
electrical p, m
rotational_vel rotor, stator
number ke, kt, j, d, l, r
{
Mixing Technology Domains 253


branch vin=v(p, m), iin=i(p->m)
branch w=w_radps(rotor, stator), Te=tq_Nm(rotor->stator)
equations {
vin = iin*r + ke*w + d_by_dt(l*iin)
Te = iin*kt - d_by_dt(j*w) - d*w
}
}
The MAST motor model also introduces a new mechanical pin type: rotational_vel. Pins of this
type must obey conservation laws, and has across and through variables associated with it. It has
torque (tq_Nm) as the through variable, and angular velocity (w_radps) as the across variable (as
opposed to translational velocity). These unit definitions and others are defined in the units.sin file.
B. Mechanical/Hydraulic Pump
The combination pump/motor element models the characteristics of a fixed displacement
continuous delivery device. The shaft has a rotational velocity type pin. The pump/motor, as the
name implies, can be used either as a pump, with power input from the shaft, or as a motor, where
the hydraulics provide the power output to the shaft. Typical device inefficiencies, such as leakage
and cavitation are modeled within this element. Additional effects, such as shaft inertia and
damping, can be attached to the shaft node to model such effects.
The basic characteristics of this device involve shaft speed to flow rate, and shaft torque to pressure
differential relationships. The leakage across the hydraulic portion is modeled as laminar (linear)
flow and is determined by both the user-supplied coefficient leak and the differential pressure.
The cavitation is modeled as described below.
This model represents a fixed-displacement
hydraulic pump. User-controlled leakage
characteristics and cavitation effects are included
in the model. The characteristic equations are
described below.
254 Chapter 11Hydraulic and Mechanical Modeling

Shaft Speed to Flow Rate
Leakage
Cavitation
The cavitation for this device is modeled as an effect that essentially opens a valve across the
hydraulic pins. That is, when the lowest pressure at either pin drops to the value pcav, flow is
bypassed to simulate the effective inefficiency. The leakage is increased as the pin pressure drops,
to the point where all of the theoretical flow is bypassed when the pressure drops to absolute zero.
This added inefficiency due to cavitation is conserved across to the torque pressure relationship to
simulate the effects of the slippage on the external power source or load.
Torque to Pressure
VHDL-AMS Hydraulic Pump
use work.fluidic_systems.all;
use work.mechanical_systems.all;
entity pum_mot is
generic (
displ: real := 1.0e-3;-- Volumetric displacement per rev.(m**3/rev)
leak: real := 1.0e-12);-- Leakage per unit pres. diff. ((m**3/s)/(N/m**2)
port (terminal p1, p2 : fluidic;
terminal shaft: rotational_v);
end entity pum_mot;
Q displ N efficiency =
where
N shaft rotational speed =
displ volumetric displacement per revolution (parameter) =
efficiency f(leak, cavitation) =
(11.4-1)
Q_leak P leak =
where
P differential pressure across hydraulic pins =
leak leakage coefficient (parameter) =
(11.4-2)
T P
displ
2
------------- =
(11.4-3)
Mixing Technology Domains 255


library ieee;
use ieee.math_real.all;
architecture simple of pum_mot is
constant ktorq : real := displ/(2.0*math_pi);
-- Torque factor, Torque/(unit delta pressure)
constant pcav : real := -95.0e3; -- Value of pcav (N/m**2)
constant patm : real := -101325.0; -- Value of patm (N/m**2)
quantity p1p across q1 through p1 to fluidic_ref;
quantity p2p across q2 through p2 to fluidic_ref;
quantity pres across qnet through p1 to p2; -- Net pump flow (m^3/s)
-- and pressure differential across pump (N/m**2)
quantity w across torq through shaft to rotational_v_ref;
--Shaft rotational velocity (rad/s)
quantity qleak : real; -- Leakage flow due to pressure diff. (m**3/s)
quantity qcav : real; -- Flow loss due to cavitation (m**3/s)
quantity qideal : real; -- Ideal flow (no losses) (m**3/s)
quantity cav_fact : real; -- Relative state of cavitation (nu)
begin
if (p1p <= pcav and w < 0.0) use
cav_fact == (pcav-p1p)/(pcav-patm);
elsif (p2p <= pcav and w > 0.0) use
cav_fact == (pcav-p2p)/(pcav-patm);
else
cav_fact == 0.0;
end use;
if(cav_fact > 1.0) use
cav_fact == 1.0;
end use;
qleak == leak*pres;
qideal == -ktorq*w;
qcav == qideal*cav_fact;
qnet == qideal-qcav+qleak;
torq == -pres*ktorq;
end architecture simple;
256 Chapter 11Hydraulic and Mechanical Modeling

MAST Hydraulic Pump
template pum_mot shaft p1 p2 = displ, leak
hyd_mks p1, # Hydraulic pin #1
p2 # Hydraulic pin #2
rotational_vel shaft # Rotational velocity pin
number displ = 1m, # Volumetric displacement per rev.(m**3/rev)
leak = 1p # Leakage per unit pres. diff. ((m**3/s)/(N/m**2)
{
val w_radps wr_rad # Shaft rotational velocity (rad/s)
val w_rpm wr_deg # Shaft rotational velocity (rev/min)
val q_m3ps qleak # Leakage flow due to pressure diff. (m**3/s)
val q_m3ps qcav # Flow loss due to cavitation (m**3/s)
val q_m3ps qideal # Ideal flow (no losses) (m**3/s)
val nu cav_fact # Relative state of cavitation (nu)
val p_Npm2 p1p # Pressure at pin #1
val p_Npm2 p2p # Pressure at pin #2
val q_m3ps qnet_mks # Net flow output of pump (m^3/s)

val p_Npm2 pres_mks # Pressure differential across pump (N/m**2)

val tq_Nm torq_mks # Net torque on shaft (N-m)
number ktorq # Torque factor, Torque/(unit delta pressure)

<consts.sin # Saber include file for use of math_pi
external number pcav # Global value of pcav (N/m**2)
external number patm # Global value of patm (N/m**2)

parameters {
ktorq = displ/(2*math_pi)
}
values {
p1p = p_Npm2(p1)
p2p = p_Npm2(p2)
pres_mks = p1p-p2p
wr_rad = w_radps(shaft)
Chapter Summary 257



if (p1p <= pcav & wr_rad < 0) {
cav_fact = (pcav-p1p)/(pcav-patm)
}
else if (p2p <= pcav & wr_rad > 0) {
cav_fact = (pcav-p2p)/(pcav-patm)
}
else{
cav_fact = 0
}
if(cav_fact>1) {
cav_fact = 1
}
qleak = leak*pres_mks
qideal = -ktorq*wr_rad
qcav = qideal*cav_fact
qnet_mks = qideal-qcav+qleak
torq_mks = -pres_mks*ktorq
}
equations {
q_m3ps(p1->p2) += qnet_mks
tq_Nm(shaft) += torq_mks
}
}
11.5. Chapter Summary
This chapter has focused on the hydraulic (fluidic) and mechanical energy domains. An application
of an anti-lock brake system (ABS) was discussed, and several supporting models were described.
Specific models for different energy domains were presented and discussed. These include
hydraulic models for a valve, actuator, accumulator and fluid chamber; and mechanical models for
a mass, spring, damper, and hard stop. Mixed-technology electrical/mechanical motor and
mechanical/hydraulic pump models were also presented.
258 Chapter 11Hydraulic and Mechanical Modeling



chapter 12
Simulator Convergence
This chapter focuses on frequently encountered causes of simulation nonconvergence, and how
models can be written to prevent them. There are several reasons why a particular simulation may
fail, but with a proper understanding of the mechanisms causing nonconvergence, designers can
find an acceptable solution in nearly all cases.
12.1. Numerical Oscillation and Divergence
Two common forms of simulation nonconvergence are numerical oscillation and numerical
divergence. These will be discussed in turn.
A. Numerical Oscillation
Numerical oscillation is a common cause of simulation nonconvergence. As shown in Figure
12.1-1, the Newton Raphson iteration starting point is selected as x
(0)
. The function is evaluated at
that point and the tangent line is projected from it and intersects the x-axis at x
(1)
. The process is
repeated, but because there is an inflection point between x
(0)
and x
(1)
, (where the function crosses
the x-axis), the selection of x
(2)
results in a tangent line which ends up at x
(1)
again. The process
repeats and numerical oscillation results.
x
(o)
x
(1)
x
(2) x
y
f(x)=0
Inflection point
x
(0)
is the initial guess.
x
(1)
is the first iteration to the
initial guess.
x
(2)
is the second iteration, but
the tangent line intersects at x
(1)
again.
The process repeats and numerical
oscillation results.
Figure 12.1-1. Numerical oscillation about an inflection point.
260 Chapter 12Simulator Convergence

Oscillations of this nature are common in functions that contain an inflection point. These types of
functions are tricky for simulators because the curve of the function changes at the point of
inflection. This can cause a problem because the slope of the function is the primary mechanism the
Newton-Raphson method uses to pick the next iteration value (as discussed in Chapter 2), and
unless the initial iteration lands close to the solution, it can be passed over.
B. Numerical Divergence
In the case of numerical divergence shown in Figure 12.1-2, x
(0)
is again selected as the Newton
Raphson iteration starting point. The function is evaluated at that point and the tangent line is
projected from it. Where this tangent line intersects the x-axis becomes x
(1)
. But again because of
an inflection point, the tangent line now drawn to the function evaluated at x
(1)
results in a location
of x
(2)
that is further from the solution than the initial guess of x
(0)
. The process repeats and
numerical divergence results.
The problems of numerical oscillation and numerical divergence have a common solution: Newton
damping.
C. Newton Damping
For some models, it is necessary to restrict where the simulator can pick an independent variable
used to solve the corresponding dependent variable. Recall the overall solution form of a DAE as
discussed in Chapter 2, which is repeated in Equation (12.1-1):
y
x
(0)
x
(1)
x
(2)
x
(3)
y=f(x)
x
0
f(x)=0
Inflection point
x
(0)
is the initial guess.
x
(1)
is the first iteration to the
initial guess.
x
(2)
is the second iteration, but is
further away from the solution
than the initial guess, x
(0)
.
x
(3)
is the third iteration, but is
further away from the solution
than x
(1)
.
The process repeats and numerical
divergence results.
Figure 12.1-2. Numerical divergence about an inflection point.
x J
1
f x ( ) =
(12.1-1)
Numerical Oscillation and Divergence 261


Newton damping is used to limit the amount that the independent variable is allowed to change
during iterations within some specified region. In essence, Equation (12.1-1) is modified to:
Where is a diagonal matrix whose values lie somewhere between zero and one. By setting
various elements of this matrix to a fraction of one, the range of independent variable selection
during Newton-Raphson iterations will be restricted. This is further illustrated in Figure 12.1-3.
In the case of either numerical oscillation or divergence, the Newton damping method steers the
simulator to a solution by restricting the amount the independent variable can move through the
range of interest. This is illustrated in Figure 12.1-5. Figure 12.1-4 is included for comparison.
Figure 12.1-4. Numerical oscillation about
an inflection point.
Figure 12.1-5. No oscillation about
inflection point with Newton
damping applied.
x J
1
f x ( ) =
(12.1-2)
x
0 1 0 0
0 0 1 0

0 0 0 1

x
1

f
1
( )
k
x
2

f
1
( )
k

x
n

f
1
( )
k
x
1

f
2
( )
k
x
2

f
2
( )
k

x
n

f
2
( )
k

x
1

f
n
( )
k
x
2

f
n
( )
k

x
n

f
n
( )
k
1
f x ( ) =
Figure 12.1-3. Expanded view of Equation (12.1-2).
x
(o)
x
(1)
x
(2) x
y
f(x)=0
Inflection point
x
(o) x
(bnd)
x
(1)
x
y
limit
x
(2)
262 Chapter 12Simulator Convergence

The iteration process for Figure 12.1-5 is as follows: the initial solution guess is x
(0)
. The function
is solved at x
(0)
, and the tangent drawn to this point intersects the x-axis far right of the actual
solution. However, as the selection for the next iteration hits the Newton damping boundary x
(bnd)
,
its movement becomes restricted to an amount no greater than limit. So the next iteration occurs at
point x
(1)
, which is the amount limit past x
(bnd)
. The selection of x
(1)
is close enough to the
inflection point that it allows the simulator to converge from that point on.
Newton step implementations are now given for the MOSFET transfer function of Figure 12.1-6.
To ensure the iteration algorithm does not overstep the transition region of Figure 12.1-6 (the area
between the dashed lines), a Newton step should be placed in the region. Since the boundaries of
the transition region are defined by the relationship b/2a, this expression can be used for the
Newton step. By setting the Newton step limiting to b/2a, a step will be forced directly in the
middle of the transition region. Alternately, since the entire transition region is from -b/2a to b/2a
(or 2b/2a), we can ensure the iteration never misses the region by limiting it to 1.9b/2a within the
region. For example, if the last iteration was at -5, and the next is chosen at +5, as soon as the b/2a
boundary on the left is crossed, the maximum variable change is limited to 1.9b/2a (0.95), which
puts it inside the transition region. This technique will be illustrated with model implementations.
As Newton step limiting is not defined as part of the VHDL-AMS language standard, its
implementation is simulator-specific and can be accomplished with a foreign subroutine. Because it
is not part of the language standard, a VHDL-AMS example of Newton step limiting will not be
given. However, regardless of how the limiting is applied, it will be similar in concept to the MAST
model example given next.
i f x >
-b
2a
then y =
-b
2
4a
el se i f x <
b
2a
then y =
b
2
4a
el se i f x > 0 then y = ax
2
+ bx
el se x <= 0 then y = -ax
2
+ bx
Let a = -1, b=1
x
y
-b
2a
b
2a
= =
-1
2
1
2
{
Newton step limit
Figure 12.1-6. Simple MOSFET transfer function and characteristic equations.
Transition region
Function description
Numerical Oscillation and Divergence 263


MAST Newton Step Limiting
template mos p m = a, b
electrical p,m
number a=-1,b=1
{
val i i
val v v
values {
v=v(p)-v(m)
if (v>(-b/2/a)) i=-b*b/4/a
else if (v>0) i=a*v*v+b*v
else if (v<b/2/a) i=b*b/4/a
else i=-a*v*v+b*v
}
control_section {
newton_step(v,[b/2/a, -1.9*b/2/a, -b/2/a, 0])
}
equations {
i(p->m)+=i+1u*v
}
}
The Newton step is implemented in a breakpoint (bp), increment (inc) format:
newton_step(v,[bp,inc,bp,inc,...bp,inc,bp,0])
The breakpoints define the regions of interest, and the increments define how the Newton step
limiting is to be applied (to the independent variable, v, in this case) within each region. In this
example, there are two breakpoints, b/2/a and -b/2/a. Within the range of these breakpoints, the
maximum Newton step increment is -1.9*b/2/a. The Newton step specification must always end
with a zero increment.
For more information regarding MAST syntax options for Newton steps, see Appendix B.
Note that for a or b coefficients with different signs, the corresponding conditional checks in the
Values section must be changed. This template was designed specifically for a negative value of a
and a positive value for b. A complete template would provide bullet-proofing checks to ensure that
this is the case.
Also note that in the Equations section, the term 1u*v has been added to the current. This is done to
prevent the slopes in the "flat" regions of the transfer function from being zero. The issue of
264 Chapter 12Simulator Convergence

unwanted zero-slope flat regions is discussed in the following section under the subheading "Zero
Slope Models."
12.2. Other Convergence Problems and Solutions
In this section, general tips for making models that handle convergence well are discussed.
A. Discontinuous Functions
Discontinuous functions are a notorious source of convergence problems. For example, the simple
voltage divider model shown in Figure 12.2-1 appears to be a straightforward function. However,
the function ceases to exist somewhere in the range of model operation, in this case, when vin
2
= 0.
When this happens, the simulator cannot solve the system of equations, and nonconvergence
occurs.
Figure 12.2-2 graphically illustrates the transfer function for this type of model. As shown, the
function becomes discontinuous on either side of the y-axis. Figure 12.2-3 illustrates a simple
solution to this problem.
Figure 12.2-2. Discontinuous reciprocal
function.
Figure 12.2-3. Continuous reciprocal
function.
vin
1
vin
2
v
out
Figure 12.2-1. Simple voltage divider model symbol and characteristic equation.
The characteristic
equation for this
model is:
v
out
vin
1
vin
2
----------- =
v
out
v
in
-eps
eps
v
in
-eps
eps
v
out
Other Convergence Problems and Solutions 265


As shown in Figure 12.2-3, the solid lines show vout as a function of v
in
. The dashed line shows the
simplest way of connecting the two segments, using a straight line segment through the origin that
intersects the hyperbolic branches of v
out
vs. v
in
. The values of eps and -eps determine the points at
which this line segment intersects the hyperbola.
VHDL-AMS Divider Function
use work.electrical_systems.all;
entity vdiv is
port (
terminal ip1,
ip2,
im1,
im2,
op,
om : electrical);
end entity vdiv;
library ieee;
use ieee.math_real.all;
architecture simple of vdiv is
constant eps : real := 0.01;
constant eps2 : real := 1.0 / eps*eps;
quantity vin1 across ip1 to im1;
quantity vin2 across ip2 to im2;
quantity vout across iout through op to om;
quantity onev : real;
begin
if (abs(vin2) < 1.0e-12) use
onev == 0.0; -- Prevent divide-by-zero
else
onev == 1.0/vin2;
end use;
if (abs(vin2) > eps) use
vout == vin1*onev; -- output voltage
-- Next line prevents output from growing without bounds
else
vout == vin1*vin2*eps2;
end use;
end architecture simple;
266 Chapter 12Simulator Convergence

The VHDL-AMS and MAST implementations of this model are very similar. The explanation
following the MAST listing applies to both models.
MAST Divider Function
template vdiv ip1 im1 ip2 im2 op om
electrical ip1, ip2, im1, im2, op, om
{
val v vin1, vin2, onev, vout
var i iout
number eps = 1e-6, eps2
struc {number bp, inc;} nv2[*]
parameters {
if (eps <=0) eps = 1e-15 # prevent negative eps values
if (eps >.01) eps = 0.01
eps2 = 1/(eps*eps)
nv2 = [(-2*eps,eps), (2*eps,0)]
# newton steps for vin2
}
values {
vin1 = v(ip1) - v(im1) # input voltage vin1
vin2 = v(ip2) - v(im2) # input voltage vin2
if (abs(vin2) < 1e-50) onev = 0 # Prevent divide-by-zero
else onev = 1/vin2
if (abs(vin2) > eps) vout = vin1*onev # output voltage
# Next line prevents output from growing without bounds
else vout = vin1*vin2*eps2
}
control_section {
newton_step (vin2, nv2) # assign newton steps to vin2
}
equations {
i(op->om) += iout # current contribution
iout: v(op) - v(om) = vout # equation to determine current
}
}
This model performs the following important checks. First, the following statements prevent a
divide-by-zero from occurring:
Other Convergence Problems and Solutions 267


if (abs(vin2) < 1e-50) onev = 0 # Prevent divide-by-zero
else onev = 1/vin2
Now the variable onev is either zero, or the reciprocal of vin
2
. Next, a check is made to see if vin
2
is
outside of the +/- eps region:
if (abs(vin2) > eps) vout = vin1*onev # output voltage
If vin
2
is outside the region, the model performs the standard function v
out
= vin
1
/vin
2
. However, if
vin
2
is inside the +/- eps region, the following algorithm is used to solve for v
out
:
Equation (12.2-1) must perform two critical functions: it must prevent v
out
from growing without
bounds for small values of vin
2
; and it must provide continuity at the boundaries +/- eps, where this
equation is replaced with the standard division equation. We will next analyze the equation to see if
both of these functions are realized.
The first function is satisfied because the value of v
out
is determined by the controlled factors in the
equation, and, as vin
2
gets smaller, v
out
also gets smaller since vin
2
appears in the numerator of the
equation.
We will check to see if there is continuity between the models governing equations with an
example. At the eps boundary, we would expect the value of v
out
predicted by (12.2-1) to be the
same as that predicted by the ratio of the input voltages.
Let vin
1
= 1V, vin
2
= 0.01V, eps = 0.01.
Using the standard divider equation, v
out
= vin
1
/vin
2
= 1/0.01 = 100V.
Using (12.2-1):
Both of the functions required by (12.2-1) are satisfied.
B. Discontinuous First Derivatives
Another common problem with convergence arises with continuous functions that have
discontinuous first derivatives. This may seem a little strange since, by definition, computer
simulators linearize the original functions in order to use matrix algebra techniques to solve them.
Linearization results in a first derivative discontinuity at the ends of each linear segment. However,
vout
vin
1
vin
2

eps eps
---------------------------- =
(12.2-1)
vout
1 0.01
0.01 0.01
--------------------------- 100V = =
(12.2-2)
268 Chapter 12Simulator Convergence

what is really at issue is not the existence of a discontinuity in the first derivative, but the size of the
discontinuity. Figure 12.2-4 shows the problem, and Figure 12.2-5 illustrates a solution.
In Figure 12.2-4, there is a large first derivative discontinuity at v=0. Depending on how this device
is used, nonconvergence may result. Figure 12.2-5 shows a solution to the problem. The idea is to
provide a smooth transition between the two regions of the transfer function. An example is helpful
to understand how this is accomplished.
Suppose we want a piecewise linear diode model where the transition between the two linear
segments occurs at 0.7V (the "knee" voltage of the diode). The equations which describe these
segments are as follows:
if (v > von) then i = gon*(v-von) + goff*von
else if (v < von) then i = goff*v
Where gon is the "on" conductance, goff is the "off" conductance, and von is the knee voltage.
We want to introduce a third segment that will smoothly join these two linear segments. There are
many choices for what type of function to use to join the segments, and we will pick the following
exponential function:
Where the degree of the exponent n controls the stiffness of the segment (the greater the value of n,
the closer the fit) as illustrated in Figure 12.2-6.
Figure 12.2-4. Ideal diode with sharp
transition between regions.
Figure 12.2-5. Ideal diode with smooth
transition between regions.
I
V 0
gon
goff
I
V 0
gon
goff
i a0 v a1 v
n
+ = (12.2-3)
Other Convergence Problems and Solutions 269


If we pick zero as the connection point for the exponential segment on the low end, and designate
an unknown variable v1 as the connection point on the high end, the overall diode equations can be
written as:
if (v > v1) then i = gon*(v-von) + goff*von
else if (v > 0) then i = a0*v + a1*v
n
else if (v < von) then i = goff*v
Now we need to somehow determine the values for v1, a0 and a1. To smoothly join the segments,
their functions and the derivative of their functions must match at the connection points. By picking
v = 0 as the connection point on the lower end, the exponential function exactly matches the linear
segment at that point (i = 0). At this connection point, we also want the derivative of (12.2-3) to
match that of goff, so we must satisfy the following:
Since these slopes need to match at v = 0, (12.2-4) reduces to a0 = goff (assuming that n > 1).
For the remaining unknowns, a1 and v1, we will solve two simultaneous equations. Equation
(12.2-5) ensures that the functions are continuous at the v1 connection point.
Where the left-hand side is the standard expression for the condition v > v1, and the right-hand side
is (12.2-3) with a0 replaced by goff (and v replaced with the unknown v1).
Equation (12.2-6) ensures that the derivatives of the segments match at the v1 connection point.
Where gon represents the slope or derivative of the v > v1 segment, and the right-hand side is the
derivative of the exponential function.
Equations (12.2-5) and (12.2-6) were solved for various values of n with gon = 1e6, goff = 1e-3,
von = 0.7, a0 = goff. The results are given in Table 12.2-1:
n a1 v1
2 357100 1.4
3 302300 1.05
4 307500 0.933
5 341200 0.875
Table 12.2-1. Simultaneous equation solutions for (12.2-5) and (12.2-6).
a0 n a1 v
n 1
+ goff = (12.2-4)
gon v1 von ( ) goff von + goff v1 a1 v1
n
+ = (12.2-5)
gon goff n a1 v1
n 1
+ = (12.2-6)
270 Chapter 12Simulator Convergence

The simulation curves obtained using these values are given in Figure 12.2-6.
The VHDL-AMS and MAST implementations for a smooth transition piecewise linear diode
model are given next.
VHDL-AMS Piecewise Linear Diode with Smoothing
use work.electrical_systems.all;
entity pwl_dio is
port (
terminal p, -- positive pin
m : electrical); -- minus pin
end entity pwl_dio;
architecture simple of pwl_dio is
quantity v across i through p to m;
constant gon: real := 1.0e6;
constant goff: real := 1.0e-3;
constant n: real := 5.0;
constant von: real := 0.7;
constant a0: real := goff;
constant a1: real := 341200.0;
constant v1: real := 0.875;
Figure 12.2-6. Piecewise linear diode simulation results using values from Table 12.2-1.
Other Convergence Problems and Solutions 271


begin
if (v > v1) use i == gon*(v-von) + goff*von;
elsif (v > 0.0) use i == a0*v + a1*v**n;
else i == goff*v;
end use;
end architecture simple;
Since this model implementation requires new coefficients for a1 and v1 to be computed for each
new value of n, all of the model constants have been declared internally rather than as entity
arguments.
MAST Piecewise Linear Diode with Smoothing
template pwl_dio p m
electrical p, m
{
number gon = 1meg, goff = 1m, n = 5, von = 0.7
number a0 = goff, a1 = 341200, v1 = 0.875
val v v
val i i
values {
v = v(p,m)
if (v > v1) i = gon*(v-von) + goff*von
else if (v > 0) i = a0*v + a1*v**n
else i = goff*v
}
equations {
i(p->m) += i
}
}
As with the VHDL-AMS implementation, this model requires new coefficients for a1 and v1 to be
computed for each new value of n. For this reason, all of the model constants have been declared
internally rather than as header arguments.
C. Zero Slope Models
Another problem for computer simulators occurs when multiple models in a system have transfer
functions that have large zero slope segments. Why is this a problem? In order to determine a
unique solution for a given node, the intersection point of all the equations for that node must be
272 Chapter 12Simulator Convergence

determined. If several models in a simulation have large zero slope regions, two things may
happen:
Recall from Newton-Raphson theory that the derivative of the function is taken and
projected out to the x-axis intersect point. With a zero slope function, this is not possible
since there may never be an intersection point.
When the derivative term in the Jacobian matrix is zero, it is difficult for the simulator to
know where to go when moving from a zero-slope region through a first derivative
discontinuity and to another zero-slope region. This is graphically illustrated in Figure
12.2-7.
Consider the voltage limiter model discussed previously, shown again in Figure 12.2-8. The
simplest way to make this model more robust is to add a slight slope to the limited (flat) regions, as
illustrated in Figure 12.2-9.
Model implementations with finite slopes in the limiting regions are illustrated next.
Figure 12.2-8. Voltage limiter with zero
slopes in limiting regions.
Figure 12.2-9. Voltage limiter with non-zero
slopes in limiting regions.
Figure 12.2-7. Simulator problem with zero slopes in limiting regions.
After encountering a discontinuity, the
simulator may not have enough
information to effectively backtrack if the
Jacobian matrix has zero slope terms.
?
?
v
out
v
in
zero slope
zero slope
V
max
-V
max
v
out
v
in
slope
slope
V
max
-V
max
Other Convergence Problems and Solutions 273


VHDL-AMS Voltage Limiter with Non-Zero Slopes
use work.electrical_systems.all;
entity v_limit2 is
generic (
up_lim : real := 10.0; -- upper limit
low_lim : real := -12.0); -- lower limit
port (
terminal ip, im, op, om : electrical);
end entity v_limit2;
architecture simple of v_limit2 is
quantity vin across ip to im;
quantity vout across iout through op to om;
constant slope : real := 1.0e-6;
begin
if vinabove(up_lim) use
vout == up_lim + slope*(vin - up_lim);
elseif not vinabove(low_lim) use
vout == low_lim + slope*(vin - low_lim);
else
vout == vin;
end use;
break on vinabove(up_lim), vinabove(low_lim);
end architecture simple;
When the lower limit is reached, vout is set to the low_lim value plus the difference between the
current input voltage and the low_lim value, times slope. This has the effect of adding a voltage
equal to the value of slope for each volt past the low_lim boundary. For example, with low_lim =
-10V, and vin = -11V, vout = -10 + 1u*(-1) = -10.000001V; if vin changes to -15V,
vout = -10 +1u*(-5) = -10.000005V. The same idea holds for positive values of vin.
MAST Voltage Limiter with Non-Zero Slopes
template limit2 inp inm outp outm = up_lim, low_lim
electrical inp, inm, outp, outm
number up_lim = 10, low_lim = -10
274 Chapter 12Simulator Convergence

{
branch vin=v(inp, inm)
branch vout=v(outp, outm), iout=i(outp->outm)
number slope = 1u
equations {
vout = if vin < low_lim then low_lim + slope*(vin - low_lim) \
else if vin > up_lim then up_lim + slope*(vin - up_lim) \
else vin
}
}
As with the VHDL-AMS example, when the lower limit in the MAST model is reached, vout is set
to the low_lim value plus the difference between the current input voltage and the low_lim value,
times slope. This has the effect of adding a voltage equal to the value of slope for each volt past the
low_lim boundary. For example, with low_lim = -10V, and vin = -11V, vout = -10 + 1u*(-1) =
-10.000001V; if vin changes to -15V, vout = -10 +1u*(-5) = -10.000005V. The same idea holds for
positive values of vin.
12.3. Debugging Models
This section focuses on ways in which models can be debugged (problems in the models can be
found and corrected). Since exact debugging methods will be simulator-dependent, general
guidelines are offered.
A. Define Test Circuits
The following guidelines should be used when testing a new model:
For functional testing
Create and simulate a simple test circuit that isolates the new model. This not only
prevents unwanted interaction with other components, it also assures that such things as
accuracy and timestep selection are influenced by the model under test.
For robustness and speed tests
- Create and simulate a large circuit with many instantiations of the new model.
- Create and simulate a circuit that uses the new model in a typical application of
moderate to large size.
- Use the full range of input parameter values.
For repeatable results
Use analysis automation and/or saved simulation forms which allow exact reproduction of
circuit setup and analysis settings.
Debugging Models 275


B. Use Available Debugging Utilities
Good simulators will provide utilities for debugging models. Three useful utilities are listed below.
Check for Model Location
In many instances there will be multiple versions of a model, stored in multiple locations.
The simulation user may believe that one model is being used, when another model is
actually found by the simulator. A good simulator will provide a method by which the
exact name and location of all models used in a simulation setting can be determined.
Check for Discontinuities
The simulator should also be able to identify and list all discontinuities present in a
system. This can be an invaluable debugging tool.
Check for Dependencies
Another useful debugging aid is for the simulator to display all of the
independent/dependent variable dependencies in a model. This is especially useful for
very complex models where the simulator makes assumptions regarding these
dependencies. In addition to checking for dependencies, the modeling language should
provide some method for the modeler to establish these dependencies.
C. Use Embedded Model Messaging
Model developers can create models which help the debugging process. One way to do this is to
use conditional messages that display useful "debug" data when needed, and not display the data
otherwise.
A MAST example is given of the DC motor model developed in Chapter 11: Hydraulic and
Mechanical Modeling. This revised model shows how to display intermediate variable values when
the debug string variable is set to "yes." Debug-related entries appear in bold.
Embedded Model Messaging (MAST Example)
template dc_motor2 p m rotor stator = ke, kt, j, d, l, r
electrical p, m
rotational_vel rotor, stator
number ke, kt, j, d, l, r
{
branch vin=v(p, m), iin=i(p->m)
branch w=w_radps(rotor, stator), Te=tq_Nm(rotor->stator)
string debug = "yes" # string which enables or disables "debug" mode
276 Chapter 12Simulator Convergence

val hsi mom # momentum (SI units)
val tq_Nm visc, # viscous loss
tgen # generated torque
val f flux # flux
val v vgen, # generated voltage
vres # resistive loss
val nu dum_val_tgen, dum_val_vres, dum_val_flux # debug variables
values {
vres = r * iin # Calculate resistance voltage drop
vgen = ke * w # Calculate back-EMF
flux = l * iin # Calculate flux
tgen = kt * iin # Calculate generated torque
visc = d * w # Calculate viscous damping
mom = j * w # Calculate momentum
if (debug == "yes") {
dum_val_vres = message("vres = %, time = %", vres, time)
dum_val_vres = message("vres = %, time = %", vres, time)
dum_val_flux = message("flux = %, time = %", flux, time)
dum_val_tgen = message("tgen = %, time = %", tgen, time)
}
}
equations {
vin = vres + vgen + d_by_dt(flux) # Electrical conservation
Te = tgen - d_by_dt(mom) - visc # Mechanical conservation
}
}
If the debug variable is set to "yes," this template will list the numerical values for the
dum_val_vres, dum_val_flux, and dum_val_tgen vals each time they are evaluated (if the signals are
listed in the signal list). Any other setting for the debug variable will prevent the values from being
displayed. The debug option can be made accessible to any user by declaring debug as an input
parameter rather than a local variable.
Also of note is the expanded use of the Values section compared to the previous version of this
model. Generally, MAST templates can be made easier to read by off-loading appropriate
operations from the Equations section to the Values section.
An alternate approach for displaying model information is to use a subroutine that prints out values
and message text passed to it each time it is called (using a printf statement in C, for example). This
technique works for both VHDL-AMS and MAST.
Chapter Summary 277


12.4. Chapter Summary
This chapter has offered solutions to problems of nonconvergence due to numerical oscillation and
divergence; to functions which are ill-defined in some part of the operational range; to large
first-derivative discontinuities; and to extended zero-slope regions. It concluded with practical
model debugging tips.
278 Chapter 12Simulator Convergence



appendix A
DAE Simulator Example Solutions
This appendix gives full solutions to the simulation examples discussed in Chapter 2: Time-Domain
Simulation. There is one complete solution for each of the following types of systems:
Linear Algebraic
Linear Differential-Algebraic
Nonlinear Algebraic
Nonlinear Differential-Algebraic
A.1. Linear Algebraic Equation Solutions
The most common way to solve linear systems of equations is by using matrix techniques. For
example, if we have the following three equations in a system of equations:
We could represent them in matrix form as shown in Equation (A.1-2):
This matrix could be solved by several techniques. Gaussian elimination is used for the following
solution.
To solve the equations, we will transform the original matrix into the form of Equation (A.1-3)
using standard matrix operations. The goal is to get a coefficient of one for each variable in each
x y 5z + 11 =
2x 0y z + 7 =
3x y z + + 11 =
(A.1-1)
1 1 5
2 0 1
3 1 1
x
y
z
11
7
11
=
(A.1-2)
280 Appendix ADAE Simulator Example Solutions

row, having eliminated the other two variables in that row. In other words, our objective is to get
ones along the main diagonal, with zeros everywhere else:
Thus, the solution to this matrix would be: 1x = b
1
; 1y=b
2
; 1z=b
3
.
In the following steps, we will manipulate the original matrix of (A.1-2) into the same form as
Equation (A.1-3).
Eliminate a
21
and a
31
: -2*R
1
+ R
2
-> R
2
; -3*R
1
+ R
3
-> R
3
:
1
Change a
22
coefficient to 1: 1/2*R
2
-> R
2
:
Eliminate a
12
: 1*R
2
+ R
1
-> R
1
:
1. This set of matrix operations translates as follows: multiply row R
1
by -2. Add this result to row R
2
, and
replace row R
2
with this sum. Then Multiply row R
1
by -3. Add this result to row R
3
, and replace row R
3

with this sum.
1 0 0
0 1 0
0 0 1
x
y
z
b
1
b
2
b
3
=
(A.1-3)
1 1 5
0 2 11
0 4 14
x
y
z
11
15
22
=
(A.1-4)
1 1 5
0 1
11
2
------
0 4 14
x
y
z
11
15
2
----- -
22
=
(A.1-5)
1 0
1
2
---
0 1
11
2
----- -
0 4 14
x
y
z
7
2
---
15
2
----- -
22
=
(A.1-6)
Linear Algebraic Equation Solutions 281


Eliminate a
32
: -4*R
2
+ R
3
-> R
3
:
Change a
33
coefficient to 1: R
3
/8 -> R
3
:
Eliminate a
13
and a
23
: 1/2*R
3
+ R
1
-> R
1
; 11/2*R
3
+ R
2
-> R
2
:
From which the following solutions are evident:
x = 4; y = -2; z = 1
A. Linear Algebraic Example
We will use the network shown in Figure A.1-1 to illustrate one method by which a simple linear
algebraic system may be solved using computer simulation.
1 0
1
2
---
0 1
11
2
----- -
0 0 8
x
y
z
7
2
---
15
2
------
8
=
(A.1-7)
1 0
1
2
---
0 1
11
2
----- -
0 0 1
x
y
z
7
2
---
15
2
------
1
= (A.1-8)
1 0 0
0 1 0
0 0 1
x
y
z
4
2
1
= (A.1-9)
Figure A.1-1. Linear algebraic network example.
R
1
R
2
I
src
gnd
v
1
v
2
R
3
282 Appendix ADAE Simulator Example Solutions

In order to solve the linear network of Figure A.1-1, we will employ the following steps:
1. Create a KCL equation for each node (v
1
and v
2
)
2. Generate conductance, voltage, and source matrices, and express in network form
3. Solve for the voltage matrix
Create KCL Equations
Multiplying through by G
2
and collecting terms:
Create Matrices
As a numerical example, let G
1
=0.5, G
2
=1, G
3
=1, I
src
=1A:
Solve Matrices (using Gaussian elimination):
Change coefficient of a
11
to 1: 2/3*R
1
-> R
1
:
G
1
v
1
G
2
+ v
1
v
2
( ) i
src
=
G
2
v
1
v
2
( ) G
3
v
2
=
(A.1-10)
G
1
G
2
+ ( )v
1
G
2
v
2
i
src
=
G
2
v
1
G
2
G
3
+ ( )v
2
0 =
(A.1-11)
G
1
G
2
+ G
2
G
2
G
2
G
3
+ ( )
v
1
v
2
i
src
0
=
(A.1-12)
3
2
--- 1
1 2
v
1
v
2
1
0
= (A.1-13)
1
2
3
---
1 2
v
1
v
2
2
3
---
0
= (A.1-14)
Linear Differential-Algebraic Equation Solutions 283


Eliminate a
21
: -1*R
1
+ R
2
-> R
2
:
Eliminate a
12
: -1/2*R
2
+ R
1
-> R
1
:
Change a
22
coefficient to 1: -3/4*R
2
-> R
2
:
v
1
= 1; v
2
= 1/2
These values correspond to the last entry in Figure 2.3-2 (the last entry is where the current input
has ramped up to 1Awhich is the input value with which this network was solved).
A.2. Linear Differential-Algebraic Equation Solutions
Linear differential-algebraic equations (DAEs) are solved only after numerical integration
algorithm(s) have been used to transform differential terms into time-finite algebraic terms.
Detailed discussions on the various integration algorithms were presented in Chapter 2. The
complete solution to a linear DAE system is given next.
1
2
3
---
0
4
3
---
v
1
v
2
2
3
---
2
3
---
=
(A.1-15)
1 0
0
4
3
---
v
1
v
2
1
2
3
---
=
(A.1-16)
1 0
0 1
v
1
v
2
1
1
2
---
=
(A.1-17)
284 Appendix ADAE Simulator Example Solutions

A. Linear DAE Example
The steps for solving a linear DAE example using computer simulation are:
1. Use KCL to generate linear differential-algebraic equations
2. Isolate differential terms on one side of the equations
3. Replace differential terms with numerical integration formula
4. Solve the new, algebraic equations using standard matrix algebra techniques
For this example, let G
1
=0.5, G
2
=1, G
3
=2, C
1
=1, C
2
=1, I
src
=1, timestep (h) = 0.1. Initial v
1
=v
2
=0
Use KCL to Generate Linear DAEs
Multiplying through where possible:
Collecting like terms:
Figure A.2-1. Linear differential-algebraic network example.
R
1
C
1
I
src
gnd
v
1
R
2
v
2
R
3
C
2
G
1
v
1
C
1
t d
d
v
1
G
2
+ + v
1
v
2
( ) C
2
t d
d
v
1
v
2
( ) + i
src
=
G
2
v
1
v
2
( ) C
2
t d
d
v
1
v
2
( ) + G
3
v
2
=
(A.2-1)
G
1
v
1
C
1
t d
d
v
1
G
2
+ + v
1
G
2
v
2
C
2
t d
d
v
1
C
2
t d
d
v
2
+ i
src
=
G
2
v
1
G
2
v
2
C
2
t d
d
v
1
C
2
t d
d
v
2
+ G
3
v
2
=
(A.2-2)
G
1
G
2
+ ( )v
1
C
1
C
2
+ ( )
t d
d
v
1
+ G
2
v
2
C
2
t d
d
v
2
i
src
=
G
2
v
1
G
2
G
3
+ ( )v
2
C
2
t d
d
v
1
C
2
t d
d
v
2
+ 0 =
(A.2-3)
Linear Differential-Algebraic Equation Solutions 285


Next, form capacitance and conductance matrices as follows:
Rearranging:
Isolate Derivatives
Substituting in numbers for the coefficients:
Recall that the inverse of a square matrix is calculated as shown in Equation (A.2-8)
1
:
Using (A.2-8) to take the inverse of the capacitance matrix:
1. In computer simulators, this calculation is typically made using LU Decomposition. The above approach is
used here in order to simplify the steps of the overall solution process.
G
1
G
2
+ ( ) G
2

G
2
G
2
G
3
+ ( )
v
1
v
2
C
1
C
2
+ ( ) C
2

C
2
C
2

+
t d
d
v
1
t d
d
v
2
i
src
0
=
(A.2-4)
C
1
C
2
+ ( ) C
2

C
2
C
2

t d
d
v
1
t d
d
v
2
G
1
G
2
+ ( ) G
2
+
G
2
G
2
G
3
+ ( ) +
v
1
v
2
i
src
0
+ =
(A.2-5)
t d
d
v
1
t d
d
v
2
C
1
C
2
+ ( ) C
2

C
2
C
2

1
G
1
G
2
+ ( ) G
2
+
G
2
G
2
G
3
+ ( ) +
v
1
v
2
i
src
0
+




= (A.2-6)
t d
d
v
1
t d
d
v
2
2 1
1 1
1
1.5 1
1 3
v
1
v
2
1
0
+




=
(A.2-7)
1
det
------- -
a
22
a
12
a
21
a
11
(A.2-8)
t d
d
v
1
t d
d
v
2
1
1
------
1 1
1 2
1.5 1
1 3
v
1
v
2
1
0
+




= (A.2-9)
286 Appendix ADAE Simulator Example Solutions

Multiply through by the reciprocal of determinant (-1):
Multiplying matrices:
Simplifying the right-hand side:
We next substitute the following form of the backward Euler integration formula for each
derivative:
Which, for this example will be re-written as follows:
Replace Differential Terms with Numerical Integration Formula
t d
d
v
1
t d
d
v
2
1 1
1 2
1.5 1
1 3
v
1
v
2
1
0
+




=
(A.2-10)
t d
d
v
1
t d
d
v
2
0.5 2
0.5 5
v
1
v
2
1
1
+ =
(A.2-11)
t d
d
v
1
t d
d
v
2
0.5 v
1
2 v
2
0.5v
1
5 v
2
1
1
+ =
(A.2-12)
t d
d
Y t
n 1 +
( )
Y t
n 1 +
( ) Y t
n
( )
stepsize
----------------------------------------- =
(A.2-13)
t d
d
v
x n 1 + ,
v
x n 1 + ,
v
x n ,

h
---------------------------------- =
(A.2-14)
v
1 n 1 + ,
v
1 n ,

h
----------------------------------
v
2 n 1 + ,
v
2 n ,

h
----------------------------------
0.5 v
1 n 1 + ,
2 v
2 n 1 + ,
0.5v
1 n 1 + ,
5 v
2 n 1 + ,
1
1
+ = (A.2-15)
Linear Differential-Algebraic Equation Solutions 287


Solve the Algebraic Equations
Multiplying through and combining like terms:
Expressing in network form (note that v
1,n
and v
2,n
variables go to zero for the initial timestep):
Isolating the new voltages:
Inverting the matrix:
And finally:
v
1 n 1 + ,
v
1 n ,
( ) h ( ) 0.5 v
1 n 1 + ,
2 v
2 n 1 + ,
[ ] + +
v
2 n 1 + ,
v
2 n ,
( ) h ( ) 0.5v
1 n 1 + ,
5 v
2 n 1 + ,
[ ] + +
h
h
=
(A.2-16)
1.05v
1 n 1 + ,
0.2v
2 n 1 + ,
( ) +
1.5v
2 n 1 + ,
0.05 v
1 n 1 + ,
v
1 n ,
v
2 n ,
0.1
0.1
+ =
(A.2-17)
1.05 0.2
0.05 1.5
v
1 n 1 + ,
v
2 n 1 + ,
0
0
0.1
0.1
+ =
(A.2-18)
v
1 n 1 + ,
v
2 n 1 + ,
1.05 0.2
0.05 1.5
1
0.1
0.1
=
(A.2-19)
v
1 n 1 + ,
v
2 n 1 + ,
1
1.585
-------------
1.5 0.2
0.05 1.05
0.1
0.1
=
0.94637 0.12618
0.031545 0.66246
=
0.1
0.1
(A.2-20)
v
1 n 1 + ,
v
2 n 1 + ,
0.082019
0.069400
=
v
1 n 1 + ,
0.082019 =
v
2 n 1 + ,
0.069400 =
(A.2-21)
288 Appendix ADAE Simulator Example Solutions

To solve for the next timestep, update initial conditions and repeat the previous step:
Simplifying:
So, the next timestep would yield:
The values from (A.2-21) and (A.2-24) correspond to the first two row entries in Figure 2.4-3.
A.3. Nonlinear Algebraic Equation Solutions
As discussed in Chapter 2, nonlinear systems are typically solved using iterative techniques, the
most popular by far being the Newton-Raphson method. The following example illustrates a
procedure for doing this in detail.
v
1 n 2 + ,
v
2 n 2 + ,
0.94637 0.12618
0.031545 0.66246
0.082019 0.1 +
0.069400 0.1 +
=
(A.2-22)
v
1 n 2 + ,
v
2 n 2 + ,
0.94637 0.12618
0.031545 0.66246
0.182019
0.169400
=
(A.2-23)
v
1 n 2 + ,
v
2 n 2 + ,
0.15088
0.11796
=
v
1 n 2 + ,
0.15088 =
v
2 n 2 + ,
0.11796 =
(A.2-24)
Nonlinear Algebraic Equation Solutions 289


A. Nonlinear Algebraic Example
We will use the network shown in Figure A.3-1 to illustrate how a simple nonlinear algebraic
system may be solved using computer simulation.
The equations describing this network are as follows:
This is similar to the previous example, but with the (v
2
)
2
term present, standard linear algebraic
solution techniques cannot be used to solve the system. To solve this nonlinear system of equations,
we will perform the following steps:
1. Simplify the equations and calculate f
1
(v
1
, v
2
) and f
2
(v
1
, v
2
)
2. Generate the Jacobian matrix, J
3. Determine change in voltage from previous iteration using
4. Find new voltage with
5. Iterate starting from (1) using updated voltage values until convergence
For this example, let G
1
=0.5, G
2
=1, G
3
=2, I
src
=1, timestep (h) = 0.1. Initial v
1
=v
2
=0.2
Figure A.3-1. Nonlinear algebraic network example.
R
1
R
2
I
src
gnd
v
1
v
2
R
3
i = v
2
G
1
v
1
G
2
+ v
1
v
2
( ) i
src
=
G
2
v
1
v
2
( ) G
3
v
2
v
2
( )
2
+ =
(A.3-1)
v
x
J
1
f v ( ) =
v
x k 1 + ,
v
x k ,
v
x
+ =
290 Appendix ADAE Simulator Example Solutions

Calculate f
1
(v
1
, v
2
)
,
f
2
(v
1
, v
2
)
Solving for f
1
:
And solving for f
2
:
Calculate Jacobian (J)
The Jacobian matrix is created by differentiating each equation (f
1
and f
2
), and populating a new
matrix with the results. The results occupy the same positions in the matrix as did the original
elements.
After differentiation, this becomes:
f
1
G
1
v
1
G
2
+ v
1
v
2
( ) i
src
=
G
1
v
1
G
2
+ v
1
G
2
v
2
i
src
=
G
1
G
2
+ ( )v
1
G
2
v
2
i
src
=
0.5 1 + ( )0.2 1 0.2 ( ) 1 =
0.9 =
(A.3-2)
f
2
G
2
v
1
v
2
( ) G
3
v
2
v
2
( )
2
=
G
2
v
1
G
2
v
2
G
3
v
2
v
2
( )
2
=
G
2
v
1
G
2
G
3
+ ( ) v
2
v
2
( )
2
=
1 0.2 ( ) 1 2 + ( ) 0.2 0.2 ( )
2
=
0.44 =
(A.3-3)
J
v
1

G
1
G
2
+ ( )v
1
v
2

G
2
( )v
2
v
1

G
2
v
1
v
2

G
2
G
3
( )v
2
v
2
( )
2
[ ]
=
(A.3-4)
J
G
1
G
2
+ G
2

G
2
G
2
G
3
2v
2

=
(A.3-5)
Nonlinear Algebraic Equation Solutions 291


Substituting numerical values:
Determine the Change From Previous Voltage
The determinant of J is:
And the inverse of the Jacobian is:
Solving the overall equation:
The individual voltage changes become:
Find the New Voltage
which yields:
J
1.5 1
1 3.4
=
(A.3-6)
v J
1
f v ( ) =
(A.3-7)
1.5 ( ) 3.4 ( ) 1 ( ) 1 ( ) 4.1 =
(A.3-8)
J
1 1
4.1
----------
3.4 1
1 1.5
0.829268 0.243902
0.243902 0.365853
= = (A.3-9)
v
0.829268 0.243902
0.243902 0.365853

0.9
0.44
= (A.3-10)
v
1
0.829268 ( ) 0.9 ( ) 0.243902 ( ) 0.44 ( ) + [ ] 0.639024V = =
v
2
0.243902 ( ) 0.9 ( ) 0.365853 ( ) 0.44 ( ) + [ ] 0.058536V = =
(A.3-11)
v
x
( )
k 1 +
v
x
( )
k
v
x
+ =
(A.3-12)
v
1
( )
k 1 +
0.2V 0.639024V + 0.839024V = =
v
2
( )
k 1 +
0.2V 0.058536V + 0.258536V = =
(A.3-13)
292 Appendix ADAE Simulator Example Solutions

Continue iterating until convergence is achieved.
The values from (A.3-13) correspond to the first entries in Table 2.5-4.
A.4. Nonlinear DAE Solutions
Solving a nonlinear differential-algebraic system represents the most common of all simulation
cases. A detailed solution to a nonlinear DAE is given next.
A. Nonlinear DAE Example
We will use the network shown in Figure A.4-1 to illustrate how a simple nonlinear
differential-algebraic system may be solved using computer simulation.
While it may seem like a straightforward task, there are actually several non-intuitive steps
involved in the solution. The detailed steps for the solutions of nonlinear DAEs are:
1. Generate the differential-algebraic equations which describe the overall system
2. Solve for dv/dt
3. Predict voltages at the next time point using the forward Euler integration formula. Use
results of (2) in order to solve for these voltages
4. Convert DAEs into algebraic equations using backward Euler integration formula
5. Create Jacobian matrix for the new algebraic equations
6. Use known (initial) values for v
(n)
, and values predicted in (3) to get numerical values into
the Jacobian
7. Solve the Jacobian, and invert it
8. Solve the algebraic equations from (4), using initial values for the past, and predicted
values for the next time point from (3). This produces solutions for f(v
1
, v
2
)
9. Multiply function solutions, f(v
1
, v
2
) with inverted Jacobian to calculate v (the change in
voltage)
Figure A.4-1. Nonlinear differential-algebraic network example.
R
1
C
1
I
src
gnd
v
1
R
2
v
2
R
3
C
2
i = v
2
Nonlinear DAE Solutions 293


10. Add v values to the past values to get new values (at the beginning of each timestep, the
past value will be the predicted value in (3). Subsequent iterations between timesteps will
use the immediate past iteration value as the starting value for the next iteration).
Generate DAEs for System
The overall approach to solving these equations is to solve the following:
Which, in terms of voltage becomes:
Isolate Derivatives
We begin, then with the original equations describing the system:
Multiplying through where possible:
Collecting like terms yields:
G
1
v
1
G
2
+ v
1
v
2
( ) C
t d
d
v
1
v
2
( ) + i
src
=
G
2
v
1
v
2
( ) C
t d
d
v
1
v
2
( ) + G
3
v
2
v
2
( )
2
+ =
(A.4-1)
x J
1
f x ( ) =
(A.4-2)
v J
1
f v ( ) =
(A.4-3)
G
1
v
1
C
1
t d
d
v
1
G +
2
+ v
1
v
2
( ) C
2
t d
d
v
1
v
2
( ) + i
src
=
G
2
v
1
v
2
( ) C
2
t d
d
v
1
v
2
( ) + G
3
v
2
v
2
( )
2
+ =
(A.4-4)
G
1
v
1
C
1
t d
d
v
1
G +
2
+ v
1
G
2
v
2
C
2
t d
d
v
1
C
2
t d
d
v
2
+ i
src
=
G
2
v
1
G
2
v
2
C
2
t d
d
v
1
C
2
t d
d
v
2
+ G
3
v
2
v
2
( )
2
+ =
(A.4-5)
G
1
G
2
+ ( )v
1
G
2
v
2
C
1
C +
2
( )
t d
d
v
1
C
2
t d
d
v
2
+ i
src
=
G
2
v
1
G
2
G
3
+ ( )v
2
C
2
t d
d
v
1
C
2
t d
d
v
2
+ v
2
( )
2
=
(A.4-6)
294 Appendix ADAE Simulator Example Solutions

Next, begin to isolate derivative terms:
Calculate Predicted Values for Next Timestep
Now we will solve the matrix for dv
1
/dt and dv
2
/dt. This solution will be used in the forward Euler
predictor integration formula:
in place of the dY(t)/dt factor on the right-hand side.
For our example, we will modify the appearance of the forward Euler formula to the following:
Where v
P
is the predicted value of the voltage at the next timestep, v
0
is the current value of
voltage, h is the step size, and v
0
is the derivative of the function at the current timestep.
At this point, we will assign values to the elements in the system, and then solve the matrix.
Let C
1
=1, C
2
=1, G
1
=0.5, G
2
=1, G
3
=2, I
src
=1, stepsize (h) = 0.1
Let all initial conditions be zero.
The system becomes:
Simplifying the right-hand side, we get:
C
1
C +
2
C
2
C
2
C
2

t d
d
v
1
t d
d
v
2
i
src
G
1
G
2
+ ( )v
1
G
2
v
2
+
v
2
( )
2
G
2
v
1
G
2
G
3
+ ( )v
2
+
= (A.4-7)
Y t 1 + ( ) Y t ( ) stepsize
t d
d
Y t ( ) + =
(A.4-8)
v
P
v
0
hv'
0
+ =
(A.4-9)
2 1
1 1
t d
d
v
1
t d
d
v
2
1 0.5 1 + ( )v
1
1v
2
+
v
2
( )
2
1v
1
1 2 + ( )v
2
+
= (A.4-10)
2 1
1 1
t d
d
v
1
t d
d
v
2
1.5v
1
v
2
1 + +
v
1
3v
2
v
2
( )
2
+ +
= (A.4-11)
Nonlinear DAE Solutions 295


Solving for the derivatives yields:
Inverting the capacitance matrix:
Solving, we get the following:
Collecting like terms gives:
At time=0, with initial conditions set to 0, we have:
We now have enough information to apply the forward Euler predictor formula:
Substituting in calculated derivative values and known initial values:
t d
d
v
1
t d
d
v
2
2 1
1 1
1
1.5v
1
v
2
1 + +
v
1
3v
2
v
2
( )
2
+ +
=
(A.4-12)
t d
d
v
1
t d
d
v
2
1 1
1 2
1.5v
1
v
2
1 + +
v
1
3v
2
v
2
( )
2
+ +
=
(A.4-13)
t d
d
v
1
t d
d
v
2
1.5v
1
v
2
1 v
1
3v
2
v
2
( )
2
+ + +
1.5v
1
v
2
1 + + 2v
1
6 v
2
2 v
2
( )
2
+
=
(A.4-14)
t d
d
v
1
t d
d
v
2
0.5v
1
2v
2
v
2
( )
2
1 +
0.5v
1
5 v
2
2 v
2
( )
2
1 +
= (A.4-15)
t d
d
v
1
t d
d
v
2
1
1
v'
0
= = (A.4-16)
v
P
v
0
hv'
0
+ =
(A.4-17)
296 Appendix ADAE Simulator Example Solutions

These predicted values will be used in two places. First, they will be used to get numerical values
into the Jacobian matrix for the next timestep; second, they will be used to solve the algebraic
functions, f
1
and f
2
numerically (after differential operators have been integrated out).
Convert Differential-Algebraic Equation to Algebraic Equation
In this step, we will remove all differential operators from the system of equations. This will give
us nonlinear algebraic equations. Starting with (A.4-15) repeated below:
Collecting matrices of the same side of the equals sign:
Next, these matrices will be combined into a single matrix:
We next substitute the backward Euler integration formula for each derivative:
Which, for this example will be shown in the following form:
v
1
P
0 0.1 1 ( ) + 0.1 = =
v
2
P
0 0.1 1 ( ) + 0.1 = =
(A.4-18)
t d
d
v
1
t d
d
v
2
0.5v
1
2v
2
v
2
( )
2
1 +
0.5v
1
5 v
2
2 v
2
( )
2
1 +
= (A.4-19)
t d
d
v
1
t d
d
v
2
0.5v
1
2v
2
v
2
( )
2
1 +
0.5v
1
5 v
2
2 v
2
( )
2
1 +
0 =
(A.4-20)
t d
d
v
1
0.5v
1
2v
2
v
2
( )
2
1 + [ ]
t d
d
v
2
0.5v
1
5 v
2
2 v
2
( )
2
1 + [ ]
0 =
(A.4-21)
t d
d
Y n 1 + ( )
Y n 1 + ( ) Y n ( )
stepsize
---------------------------------------- = (A.4-22)
t d
d
v
x n 1 + ,
v
x n 1 + ,
v
x n ,

h
---------------------------------- =
(A.4-23)
Nonlinear DAE Solutions 297


Which yields:
Multiplying through by h:
We now have an accurate, yet somewhat clumsy form of the system of algebraic equations. It will
prove easier to keep track of the positions of the matrix elements if we split the matrix up again,
using h as the separation point:
Generate Jacobian Matrix
From this, we create the Jacobian matrix by taking the derivative of each element in the array, and
placing the result in the same matrix position as the original element. Note that the past values are
zero.
Use Known Values to Get Numbers into Jacobian
Substituting in the value for h and the predicted value for the remaining variable, v
2
(which in this
case, just happen to have the same value of 0.1):
v
1 n 1 + ,
v
1 n ,

h
---------------------------------- 0.5v
1 n 1 + ,
2v
2 n 1 + ,
v
2 n 1 + ,
( )
2
1 + [ ]
v
2 n 1 + ,
v
2 n ,

h
---------------------------------- 0.5v
1 n 1 + ,
5 v
2 n 1 + ,
2 v
2 n 1 + ,
( )
2
1 + [ ]
0 =
(A.4-24)
v
1 n 1 + ,
v
1 n ,
h 0.5v
1 n 1 + ,
2v
2 n 1 + ,
v
2 n 1 + ,
( )
2
1 + [ ]
v
2 n 1 + ,
v
2 n ,
h 0.5v
1 n 1 + ,
5 v
2 n 1 + ,
2 v
2 n 1 + ,
( )
2
1 + [ ]
0 =
(A.4-25)
v
1 n 1 + ,
v
1 n ,

v
2 n 1 + ,
v
2 n ,

h
0.5v
1 n 1 + ,
2v
2 n 1 + ,
v
2 n 1 + ,
( )
2
1 +
0.5v
1 n 1 + ,
5 v
2 n 1 + ,
2 v
2 n 1 + ,
( )
2
1 +
0 =
(A.4-26)
J
1 0
0 1
= h
0.5 2 2v
2 t 1 + ,
( ) +
0.5 5 4v
2 t 1 + ,
( ) +
0 = (A.4-27)
J
1 0
0 1
= 0.1
0.5 2 2 0.1 ( )
0.5 5 4 0.1 ( )
0 = (A.4-28)
298 Appendix ADAE Simulator Example Solutions

Simplifying:
Now, recombining into a single matrix:
Solve for the Inverse of the Jacobian
Now we have the Jacobian matrix with no variables. Bearing in mind that our eventual goal is to
solve the following:
We will take the inverse of the Jacobian matrix, which yields:
Solve f(v1, v2)
Next, we need to solve for f(v), which is our algebraic equation system representation, using initial
conditions for previous voltage values, and forward Euler prediction results for next voltage values:
With numeric substitutions, this becomes:
J
1 0
0 1
=
0.05 0.22
0.05 0.54
0 =
(A.4-29)
J
1.05 0.22
0.05 1.54
0 = = (A.4-30)
v J
1
f v ( ) = (A.4-31)
J
1 1
det
--------
1.54 0.22
0.05 1.05
0.9459 0.1351
0.0307 0.64496
= =
(A.4-32)
f v
1
v
2
, ( )
v
1 n 1 + ,
v
1 n ,
h 0.5v
1 n 1 + ,
2v
2 n 1 + ,
v
2 n 1 + ,
( )
2
1 + [ ]
v
2 n 1 + ,
v
2 n ,
h 0.5v
1 n 1 + ,
5 v
2 n 1 + ,
2 v
2 n 1 + ,
( )
2
1 + [ ]
=
(A.4-33)
f v
1
v
2
, ( )
0.1 0 0.1 0.5 0.1 ( ) 2 0.1 ( ) 0.1 ( )
2
1 + [ ]
0.1 0 0.1 0.5 0.1 ( ) 5 0.1 ( ) 2 0.1 ( )
2
1 + [ ]
=
(A.4-34)
Nonlinear DAE Solutions 299


Simplifying:
Solve for New Voltage
Using the original formula (A.4-31) and solving for the change in voltage:
Finally, the next voltage value can be found by adding the change in voltage to the previous value
(which will be the predicted value for the first iteration after a new timestep):
In this instance, which is the first iteration after a timestep:
Which evaluates to:
These values correspond to the first entries in Table 2.6-1.
f v
1
v
2
, ( )
0.026
0.047
=
(A.4-35)
v J
1
f v ( ) =
0.9459 0.1351
0.0307 0.64496

0.026
0.047
=
0.0182437
0.03111
=
v
1
0.0182437 =
v
2
0.03111 =
(A.4-36)
v
x n ,
( )
k 1 +
v
x n ,
( )
k
v
x
+ = (A.4-37)
v
1 n ,
( )
k 1 +
v
1
P
v
1
+ =
v
2 n ,
( )
k 1 +
v
2
P
v
2
+ =
(A.4-38)
v
1 n ,
( )
k 1 +
0.1 0.0182437 0.081756 = =
v
2 n ,
( )
k 1 +
0.1 0.03111 0.068888 = =
(A.4-39)
300 Appendix ADAE Simulator Example Solutions



appendix B
MAST Supplement
This appendix is intended as a limited MAST reference source. Please refer to MAST documenta-
tion referenced in Appendix D for further sources of information.
B.1. Mathematical Functions and Expressions
A. Expressions With Operators
Unary Operators:
- negation
~ boolean not
Binary Operators:
** to the power of
* multiply
/ divide
+ plus
- minus
< less than
> greater than
>= greater than or equal to
<= less than or equal to
== equal to
~= not equal to
& boolean and
| boolean or
// string concatenation
Operator Precedence:
unary operators
302 Appendix BMAST Supplement

**
* /
+ -
//
<> <= >=
== ~=
&
B. Mathematical Functions
Trigonometric and Hyperbolic Functions:
sin cos tan
asin acos atan
sinh cosh tanh
asinh acosh atanh

Logarithmic and Exponential Functions:
ln log exp limexp
Other Mathematical Functions:
d_by_dt (the derivative function)
1

delay
sqrt (square root)
abs (absolute value)
random
C. If Statements and Expressions
If Statement Syntax
if ( expression ) statement
[else if ( expression ) statement ]
[else statement]
statement can be:
1. The d_by_dt and del ay functi ons can onl y be used i n the Equati ons secti on.
Mathematical Functions and Expressions 303


any statement which would be legal in this section
another if statement
a compound statement:
{
one or more statements which would be legal in this section
}
expression is any expression which would be legal in this section.
If expression 0, then the following statement is evaluated.
If expression = 0, then the following statement is skipped.
The statement following the else block (if it exists) is evaluated if the expression (x == y) evaluates
to false (zero).
if (x == y) out = 1
else if (y == z) out = 2
else {
out = 1 + y-x
abc = out
}
if (a == b & c == d) {
w = 10
x = y+z
}
If statements can be used in Parameters, Values, Control, Equations sections, and When statements.
If Expression Syntax
if control_expression expression1 else expression2
expression1 and expression2 can be:
any expression which would be legal in this section
another if expression
control_expression is any expression which would be legal in this section.
If control_expression 0, then the if expression evaluates to expression1.
If control_expression = 0, then the if expression evaluates to expression2.
out = if x == y 1 else 1 + y-x

x = if time < stop then time else stop

v = if (in < -max) then (-max + slope*(in+max)) \
else if (in < max) then in \
else -max + slope*(in-max))
else if and else blocks are optional.
If no control expressions (conditions) are satisfied, the entire if statement is ignored.
304 Appendix BMAST Supplement

B.2. Mixed-Signal Modeling
MAST is a mixed-signal modeling language. Model pins provide information to the simulator as to
whether analog or digital signals are appropriate. In MAST, digital pins are called state pins, and
digital variables are called state variables.
A. Variable Types
State variables can change value instantaneously, and retain their value from assignment to
assignment, regardless of time. They consume CPU time only when they are assigned new values
or receive events. If not explicitly initialized otherwise in their declarations, logic_4 variables are
initialized to l4_x.
B. When Statements
Although they look like any other section in a MAST template, When "sections" are actually
statements. They differ from template sections in two ways. First, there will often be several When
statements in a single template. Second, when is also a keyword, and the body of a When statement
will only be executed when condition is met:
when (condition) {
statements
}
The condition is a logical expression involving one or more of the intrinsic functions named
threshold() (detect analog threshold) and event_on (detect digital event) or various simulator
variables (simvars) discussed shortly.
There are four basic statement types available in the body of When statements:
Assignment statement
type time value
Anal og
val , var (unit v, i )
Conti nuous Conti nuous
state
(unit v, nu)
Di scr ete Di sconti nuous
state
l ogi c_4
(unit l 4_0, l 4_1, l 4_x, l 4_z)
Di scr ete Di scr ete
Table B.2-1. Variable Types
Simulator Variables and Functions 305


If statement
Subroutine call
message()
1
Only variables of type state may be assigned values in the body of When statements
To summarize, the following points apply to When statements:
Multiple When statements are allowed (unlike template sections)
When statements are used to detect events on digital inputs and state variables
(when (event_on()). Events are scheduled to digital outputs using (schedule_event()).
When statements will always be present for anything digital
When statements are used to detect analog thresholds (when (threshold())
Changes to a state variable or state pin are assigned in When statements
All variables that are assigned values in the body of When statements are declared as type
state
When statements cannot be nested
When statements cannot appear within conditional statements
B.3. Simulator Variables and Functions
A. Simulator Variables (Simvars)
For the following simvar definitions, true in MAST is non-zero. For example, 1 and -1 are both
true.
DC Simvars
dc_domain - Has a non-zero value when DC or DC transfer analysis is being carried out.
It is equal to zero otherwise.
dc_init - Becomes true at the start of DC analysis, DC transfer analysis, and the DC por-
tion of the combined DC/TR analysis.
dc_start - Becomes true at the start of any DC analysis.
dc_done - Becomes true at the end of a DC analysis, or the DC portion of the combined
DC/TR analysis (it is set to true after the algorithm has completed).
Transient (TR) Simvars
time_domain - Has a non-zero value when transient analysis is being carried out. It is
equal to zero otherwise.
1. There is typically no messaging in the Values or Equations sections. Also, vals can only be changed in the
Values section, vars can only be changed in the Equations section, and numbers can only be changed in the
Parameters section.
306 Appendix BMAST Supplement

time_init - Becomes true at the start of transient analysis, and the transient portion of the
combined DC/TR analysis. It does not become true when a transient analysis is restarted
from a previous transient analysis.
tr_start - Becomes true at the start of any transient analysis, including one restarted from a
previous transient analysis.
tr_done - Becomes true at the end of a transient analysis, or the transient portion of the
combined DC/TR analysis (it is set to true after the algorithm has completed).
time_step_done - Becomes true at the end of each timestep. It is recommended to avoid
using this simvar by using when(threshold()) in its place.
Small-Signal AC Simvars
freq - Contains the current simulation frequency when a frequency domain (small-signal
AC) analysis is carried out. It is equal to zero otherwise.
freq_domain - Has a non-zero value when a frequency domain analysis is being carried
out. It is equal to zero otherwise.
freq_mag - Has a non-zero value when a frequency domain analysis is being carried out,
and the simulator is requesting the magnitude portion of a complex number. It is equal to
zero otherwise.
freq_phase - Has a non-zero value when a frequency domain analysis is being carried
out, and the simulator is requesting the phase portion of a complex number. It is equal to
zero otherwise.
Miscellaneous Simvars
statistical - Has a non-zero value if the simulation environment is statistical, such as when
the Monte Carlo (MC) command is executed. It has a value of zero when the simulation
environment is deterministic.
step_size - Allows the template to influence the size of the timestep during transient sim-
ulation. The value of step_size places an upper limit on the size of the timestep.
time - Contains the current simulation time when a time domain (transient) analysis is car-
ried out. It is equal to zero otherwise.
next_time - Allows the template to specify a future time that the simulator must reach
exactly. Used only in the Values section.
B. Event_on Function
Receive an Event
The method for detecting events in MAST is the event_on function. This function is used to detect
when some sort of transition, or event takes place so another event can be scheduled.
Simulator Variables and Functions 307


Syntax:
when (event_on(statevariable [, oldvalue ]))
Where:
statevariable is the state variable to be monitored for an event. When an event is placed on
statevariable, the condition is true.
oldvalue (optional) is the name of a state variable, which, when statevariable receives a value, in
turn receives the previous value of statevariable. Thus, oldvalue is an output variable.
Example:
when (event_on(is)) {
...
}
This statement will cause whatever is in the braces to be executed whenever an event on is occurs.
when (event_on(is, was)) {
...
}
As above, this statement will cause whatever is in the braces to be executed whenever is changes
state, and also record the old value of is in the state variable was.
C. Schedule_event Function
Create an Event
[scheduling_id =] schedule_event(time, statevariable, expression)
Where:
scheduling_id (optional) is an array of two state variables. This array is assigned a unique identifier
when the event is scheduled, and can be used to deschedule the event.
time is an expression whose value indicates the time at which the assignment is to occur.
statevariable is the state variable that is to receive expression as its new value at time: time.
expression is evaluated when schedule_event is called, the resulting value is assigned to
statevariable at time: time.
examples:
schedule_event(time+td, out, l4_0)
schedule_event(11.3n, next, 12 + previous)
In this example, when vin crosses the threshold, thresh, a logic 0 (l4_0) is scheduled on pin out at
time+td, and a real state value of 12 plus its previous value is scheduled on pin next at 11.3 ns
(previous is just the name of a variable which holds the old value. It can have any name).
308 Appendix BMAST Supplement

Time is a simulator variable that holds the present value of simulation time.
D. Deschedule Function
The Event Queue
State connection points have events scheduled and descheduled on them at specific times in an
event queue.
Events are placed in the queue using:
schedule_event(3u, out, l4_0) or # Place l4_0 on out at time = 3us
handle = schedule_event(3u, out, l4_0)
Events are detected using:
when(event_on(out3)) # Detect when event occurs on out3
when(event_on(out1) | event_on(out2)) # Detect out1 OR out2
Events are removed from the queue using:
deschedule(handle) # From above example, l4_0 will no longer
# be placed on out at 3us
E. Schedule_next_time Function
An analog timestep may be forced in the simulator using the schedule_next_time function:
schedule_next_time function
[scheduling_id = ] schedule_next_time (time)
event # time name value
1 3u out l 4_0
2 4u out3 l 4_1
3 6u i n1 l 4_0
...
27 61u i n2 l 4_x
Table 1: Simplified Event Queue
Simulator Variables and Functions 309


Where:
scheduling_id (optional) is an array of two state variables. This array is assigned a unique
identifier when the event is scheduled, and can be used for descheduling the event.
time is an expression whose value is the time at which the Saber simulator is to evaluate the
analog system. Unless this scheduling is subsequently de-scheduled, the simulator will not
step over this scheduled time, even if the timestep algorithm indicates that it should.
The schedule_next_time function is commonly used to force an analog time step to occur after a
state has changed. An example of this will be given shortly using a digitally-controlled analog
switch.
F. Threshold Function
In MAST, the threshold function is used to detect threshold crossings. The threshold function is
evaluated independently of the timestep and is used as follows:
threshold(expression1, expression2 [, beforestate [, afterstate ]])
Where expression1 is compared to expression2 continuously to see if a threshold condition has
been met. Beforestate and afterstate are output variables (threshold assigns values to them) of type
state unit that can be used to determine how the threshold condition was met. Beforestate and
afterstate are assigned values as follows:
Beforestate equals:
1 if expression1 > expression2 before the threshold
-1 if expression1 < expression2 before the threshold
0 if expression1 = expression2 before the threshold
Afterstate equals:
1 if expression1 > expression2 after the threshold
-1 if expression1 < expression2 after the threshold
0 if expression1 = expression2 after the threshold
beforestate afterstate
-1
1
0
-1
1
0
1
-1
1
0
0
-1
310 Appendix BMAST Supplement

For example, the following statements can be used to assign a logic "1" (l4_1) to digital pin out
when the voltage at pin p becomes more positive than the voltage at pin m. Otherwise, a logic "0"
(l4_0) will be assigned to pin out:
when (threshold(v(p), v(m), before, after)) {
if (after >= 0) schedule_event(time+td, out, l4_1)
else schedule_event(time+td, out, l4_0)
}
B.4. Stress Analysis
Stress analysis is used by Saber to detect and report any component that is operating outside its
intended region of operation. The following steps illustrate how to add stress analysis capability to
a resistor model:
1. Add the required stress_measure statements to the Control section of the template. For
example:

stress_measure (pdavg, power, "Avg Power Diss.", pwrd, average, xpdavg)
stress_measure (vmax, voltage, "Max Voltage", abs(v), max, xvmax)

A stress_measure statement takes the following form:

stress_measure (uid, gid, "name", val, measure, rating[ref rating])
Where,
uid "unique identifier" identifies the stress measure, and is used as the value for the
smeasurelist of the stress command.
gid "group identifier" identifies the type of grouping of stress measures to which the
stress measure belongs.
name is the test used to describe the stress measure in a stress report.
val is the name of a variable in a template from which the value of the stress measure
is to be extracted using the measurement specified in the measurement field.
measure specifies the measurement to be made on the template variable specified in
the val field. This measurement provides the actual or measured value for the stress
ratio calculation. Available measurements are: peak, max, winmax, min, winmin, rms,
and average.
rating is the manufacturers rating for the stress measure. It can be entered as a
constant or as a variable (val is compared to this).
Stress Analysis 311


ref_rating is optional. When specified, the measured and derated values are
referenced to this value rather than to zero when the stress ratio is calculated.
2. Determine if the variable specified in the val field for each stress measure is available in
the template and add if necessary.
3. Add stress ratings to the template as follows in an example:
Declare a structure called "ratings" (other names can be declared if desired)

struc {
number pdmax_ja=undef, # Max. power diss. w/o heatsink
pdmax_jc=undef, # Max. power diss. with heatsink
tjmax = undef, # Max. temperature
tjmin = undef, # Min. temperature
vmax = undef # Max. voltage
} ratings
Add structure name to template header:

template resistor p m = rnom, tc, tnom, ratings, ...
Define local variables to store bullet-proofed ratings:

xvmax, # Final value of maximum voltage rating
xtjmax, # Final value of max. temp. rating
xtjmin # Final value of min. temp. rating
Add error checking (bullet-proofing) for ratings:

xvmax = ratingbp(ratings->vmax, "vmax")

Where ratingbp is a MAST function that checks to see if the rating was specified as a
zero or a negative number.
4. Add thermal resistances (optional)
5. Add means to disable stress in a template (optional):

external number temp, include_stress, ...
6. Add means for specifying device type and class (optional) - used for stress reports and
derating files:
Add a device_type statement to the Control section:

device_type(part_type, part_class)
Declare part_type and part_class as strings in the Header declarations section. Give
them default values as shown:
312 Appendix BMAST Supplement


string part_type = "resistor", # type of device
string part_class = "generic" # class of device
The next example illustrates how stress measures have been added to the dc_motor model discussed
in Chapter 11: Hydraulic and Mechanical Modeling. All model modifications are shown in bold.
A. DC Motor Model Example
template dc_mtr p m rotor stator = \
ke,kt,j,d,l,r,ratings,part_type,part_class
electrical p, m
rotational_vel rotor, stator
number ke, kt, j, d, l, r
string part_type = "motor"
string part_class = "dc permanent magnet"
struc {
number wmax = undef, # maximum rotational shaft speed
tqmax = undef # maximum torque output
} ratings=()
# exported stress variables
external number include_stress
{
number xke, xkt, xr, xl
number xwmax, # final value of max. rotor speed
xtqmax # final value of maximum torque
val hsi mom # momentum (SI units)
val tq_Nm visc, # viscous loss
tgen
val f flux # flux
val v vgen, # generated voltage
vres, # resistive loss
vin
val w_radps w
var i i
parameters {
# Bullet proof input parameters
xr = argbp("gt_w","undef_w","inf_w",r,"r",0.1,0)
xl = argbp("gt_e","undef_e","inf_e",l,"l",xl,0)
xkt = argbp("gt_e","undef_e","inf_e",kt,"kt",xkt,0)
xke = argbp("gt_e","undef_e","inf_e",ke,"ke",xke,0)
Stress Analysis 313


# bullet proof ratings
xwmax = ratingbp(ratings->wmax,"wmax")
xtqmax = ratingbp(ratings->tqmax,"tqmax")
}
values {
vin = v(p,m)
w = w_radps(rotor) - w_radps(stator)
vres = xr * i
vgen = xke * w
flux = xl * i
tgen = xkt * i
mom = j * w
visc = d * w
}
control_section {
device_type(part_type, part_class)
if (include_stress) {
stress_measure(wmax,speed,"max rotor speed",abs(w),max,xwmax)
stress_measure(tqmax,torque,"max torque",abs(tgen),max,xtqmax)
}
}
equations {
i: vin = vres + vgen + d_by_dt(flux)
i(p->m) += i
tq_Nm(rotor) += tgen - d_by_dt(mom) - visc
}
}
# Test circuit
v.v1 m:0 p:v_in = tran=(pulse=(v1=0,v2=10,tr=1m,tf=1m,pw=1,per=2))
dc_mtr.m1 p:v_in m:0 rotor:load = l=40m, kt=6.405m, j=414n, r=50, \
ke=6.405m, d=3u
This example introduces a new function, argbp, which is commonly used for parameter
bullet-proofing. Built-in bullet-proofing MAST functions are discussed in the next section.
B. Built-in Bullet-Proofing Functions
There are three MAST functions in addition to ratingbp that are commonly used for bullet-proofing
template arguments (particularly templates that implement stress measures):
argbp - used to check a parameter against undef, inf, and a numeric value. For example:

xrnom = argbp("gt_w", "undef_w", "inf_w", rnom, "rnom", 1k, 0)

The first three arguments are strings that determine what is checked, and how errors are
handled. The _e suffix issues an error, the _w suffix issues a warning for a check that fails.
314 Appendix BMAST Supplement

The following fields are for the parameters value, name, default value, and the numerical
limit it is checked against.
In this example, a warning is issued and a default value of 1k is assigned to xrnom if rnom
is undef, inf, or not greater than 1k.
argsbp - used to check a parameter against undef, inf, and another parameter
1
. For
example:
xr1 = argsbp("gt_w", "undef_w", "inf_w", r1, "r1", 1meg, r2, "r2")
The first three arguments are strings that determine what is checked, and how errors are
handled.
The following fields are for the parameters value, name, default value, and the value and
name of the parameter to check it against.
This example checks for r1 > r2, as well as undef and inf. It issues a warning if any of the
tests fail, and a default of 1meg is assigned to xr1.
argrngbp - used to check a parameter against undef, inf, and a numerical range. For
example:
xr1 = argrngbp("gt_w", "lt_w", "undef_w", "inf_w", r1, "r1", 0.5, 0, 1)
The first four arguments are strings that determine what is checked, and how errors are
handled.
The following fields are for the parameters value, name, default value, lower_limit and
upper_limit.
This example checks for 0 < r1 < 1, as well as undef and inf. It issues a warning if any of
the tests fail, and a default of 0.5 is assigned to xr1.
General conditioning error checking descriptions are given in Table B.4-1.
1. The MAST functions argbp and argsbp use a passing condition for the first field, and a "failing" condition
for the second and third fields.
Code Suffixes Function
gte _e, _w >=
gt _e, _w >
l te _e, _w <=
l t _e, _w <
eq _e, _w ==
Table B.4-1. Error Checking - General Conditional
Statistical Analysis 315


Undefined and infinite checking descriptions are given in Table B.4-2.
B.5. Statistical Analysis
Statistical analysis is typically used to determine the effects of component tolerances on the
performance of a system. This analysis is achieved by randomly assigning component values to
component parameters (within tolerances and with a user-defined distribution), and recording these
values. Correlations between system performance measures and component tolerances can then be
made, allowing designers to produce more "manufacturable" designs.
A model can be made to take advantage of the statistical capabilities built into MAST by making a
few modifications to the model description. For example, if we wish to create a resistor model
which has a resistance tolerance that can be controlled globally (so the tolerance values of all the
resistors in a design can be changed at once by altering this single variable), we would make the
following additions to our standard resistor model :
Bring in relevant the global variable and distribution function externally:

external number r_tol # for a resistors, r_tol is a global variable which can
# set the default resistor tolerance. Its use is optional.
external standard..pdist pdist # pdist specifies the type of distribution to be used.
# Its default is normal.
In the Parameters section, call the distribution function, distfunc as follows:

r = distfunc(rnom, r_tol, pdist)
By adding this information to the model, the resistance will have tolerance, r_tol, which can be
globally controlled. During statistical analysis, r_tol will be applied to the nominal resistance value,
rnom. The results will be assigned to r, which will be normally distributed by default (this can also
neq _e, _w ~=
Code Function
none No undefi ned check i s performed
undef Assi gn defaul t, no message gener ated
undef_e I ssue ERROR message
undef_w Assi gn defaul t, WARNI NG gener ated
Table B.4-2. Error Checking - Undefined and Infinite
Code Suffixes Function
Table B.4-1. Error Checking - General Conditional
316 Appendix BMAST Supplement

be specified for uniform distribution, or a user-defined piecewise linear distribution). The full
resistor model implementation follows, where statistical-related model additions are given in bold.
A. Statistical Resistor Model Example
element template r_mc p m = rnom, tc, tnom
electrical p, m
number rnom, tc[2] = [0,0], tnom = 27
external number temp, r_tol
external standard..pdist pdist
{
val v vres
val p power
val i current
number r
parameters {
r = distfunc(rnom,r_tol,pdist)
r = r*(1+tc[1]*(temp-tnom)+tc[2]*(temp-tnom)**2)
}
values {
vres = v(p,m)
current = vres/r
power = vres*current
}
equations {
i(p->m) += current
}
}
# Test circuit
# Netlist with resistor and Monte Carlo distribution
v.v1 p:vcc m:0 = 10
r_mc.r1 p:vcc m:net1 = rnom = 1k
r_mc.r2 p:net1 m:0 = rnom = 1k, r_tol = 0.2
In this netlist example, r_mc.r1 will have whatever tolerance is specified by the global variable,
r_tol. The instance r_mc.r2 has a locally-specified value for r_tol, which will over-ride the global
specification.
If global tolerance and distribution control is not desired, statistical information can also be added
at the netlist level to each model instance. In this case, no statistical modifications need to be made
to the resistor model itself.
Sample Points 317


For example,
v.v1 p:vcc m:0 = 10
r.r1 p:vcc m:net1 = rnom=normal(1k,0.1)
r.r2 p:net1 m:0 = rnom=uniform(1k,0.2)
This circuit will work in a statistical simulation with a 10% tolerance for r.r1, which will be
normally distributed about the nominal resistance, 1k. The r.r2 instance has a 20% tolerance,
which will be uniformally distributed about its nominal resistance, also 1k.
B.6. Sample Points
There are several considerations for selecting sample points (introduced in Chapter 2:
Time-Domain Simulation):
A. Sample-Point Considerations
Accuracy vs. speed. Denser sample points provide better accuracy of the piecewise linear
approximation of the nonlinearity, but this is usually accompanied by slower simulation speed.
Optimum combination of accuracy and speed. The Saber simulator lets you change the density
of the sample points at run time by means of the density variable, den. You should specify values
for sample points such that the accuracy of the piecewise linear approximation is sufficient for the
default simulator density of 1 (which means density has no effect on sample points). Of course, the
meaning of sufficient accuracy depends upon the application.
Operation limits. These are the minimum and maximum values that the independent variable is not
supposed to exceedif it does, the Saber simulator reports a warning and sets the variable to the
limit value.
Intended region of operation of the model. This is a region inside the operation limits where the
model is intended to be used. Typically, you want better accuracy inside this region than outside.
Numerical considerations. The independent variable may be restricted to a certain value range by
the laws of physics, but during iterations it may assume values outside this range. (For example,
absolute temperature may become negative during iterations.)
Other requirements. The Saber simulator requires that 0 (zero) be a sample point.
318 Appendix BMAST Supplement

Using sample points to describe how nonlinear functions will be linearly approximated was
introduced as piecewise linear evaluation in Chapter 2. The accuracy of piecewise linear evaluation
is demonstrated in Figure B.6-1.
This figure shows a nonlinear function y=f(x) and a linear approximation that intersects the function
at x
1
and x
2
. That is, x
1
and x
2
are sample points of y=f(x). Further, y
1
and y
2
are the function values
at x
1
and x
2
, respectively, and is the maximum error of the linear approximation of f(x) between x
1
and x
2
. In order to find approximate sample points for x, we need to express as a function of
x=x1-x2. If there were such a function, its inverse would yield the sample point spacing for a
given maximum error. In general, such a function is difficult to derive, except in the very simplest
cases, such as this voltage squarer.
Figure B.6-1 shows that is always smaller than y = y
2
-y
1
if the sign of the slope of f(x) does not
change between x
1
and x
2
.
Therefore, if f(x) is monotonic between x
1

and x
2
, y is an upper bound for the approximation error.
Because simulation always involves a trade-off between accuracy and speed, you will expect a
certain accuracy of simulation results (such as three digits of relative accuracy or an absolute
accuracy of 10 ). In both cases, you actually specify a minimum resolution or granularity for
the simulator results, and you expect y to be smaller than this level of resolution.
Next, find x as a function of y. In many cases, it is possible to do this using the inverse
relationship x = f
-1
(y). In more complicated cases (particularly with multi-dimensional
nonlinearities), selecting the sample points may be a process of trial and error. Keep in mind the
concept of resolution or granularity as an aid for quickly finding a reasonable set of sample
points. Remember too, that y might be a pessimistic upper bound (i.e., too large) for the
approximation error, depending upon the nonlinearity.
In the case where f(x) is non-monotonic between x
1
and x
2
, divide x into smaller parts, such that
f(x) is monotonic throughout each part. In practice, this further division is not critical, because the
monotonicity of f(x) is required only to ensure that is smaller than y. Therefore, if x is
sufficiently small, y is a good upper bound for the approximation error.
y
y
2
y
1
y = f(x)
x
x
1
x
2

Figure B.6-1. Accuracy of piecewise-linear approximation.


-3
Sample Points 319


B. Sample Point (and Newton Step) Specification Syntax
Sample points (and also Newton steps) can be defined in either of two ways, and will always be
applied in the Control section of the template. For example, lets say we wanted to specify the
sample points for a model as follows: when the independent variable, vin is between -100 and -10,
sample by 10; when it is between -10 and 0, sample by 1; and when vin is between 0 and 10, sample
by 0.2. This could be implemented in a MAST template as follows:
sample_points(vin,[-100,10,-10,1,0,0.2,10,0])
The sample point definition is given in a breakpoint (bp), increment (inc) format:
sample_points(independent_variable(s),[bp,inc,bp,inc,...bp,inc,bp,0])
The specification must always end with a zero increment.
An optional implementation approach is to declare the sample points as an array of structures, with
each structure containing one breakpoint/increment pair. The array of structures would be declared
in the local declarations section, and applied in the Control section. Using this approach, the
previous example could be implemented as follows:
In the local declarations section:
struc {number bp, inc;} sp[*] = [(-100,10), (-10,1), (0,0.2), (10,0)]
In the Control section:
sample_points(vin,sp)
Here, the contents of the sp array are applied to the independent variable, vin.
This same approach can be used for Newton steps as well. For example, the Newton step
specification for the mos model in Chapter 12 was originally given as:
control_section {
newton_step(v,[b/2/a, -1.9*b/2/a, -b/2/a, 0])
}
But it could also have been specified using an array of structures. This is done by first declaring an
array of structures which defines the limiting region:
struc {number bp, inc;} nsv[*] = [(b/2/a, -1.9*b/2/a), (-b/2/a, 0)]
As with the sample point example, each of these structures is specified using a breakpoint,
increment syntax, where the breakpoints define the regions of interest, and the increments define
how within each region the Newton step limiting is to be applied. In this example, there are two
breakpoints, b/2/a and -b/2/a. Within the range of these breakpoints, the maximum Newton step
increment is -1.9*b/2/a. This information is stored in the array, nsv.
The second step is to then apply the specified array to the independent variable(s) of interest. This
is again done in the Control section. In this example, the independent variable is the voltage, v. We
could then apply the Newton step array, nsv, to v as follows:
320 Appendix BMAST Supplement

control_section {
newton_step(v,nsv)
}
The array of structures implementation approach is most often used for both sample point and
Newton step specifications.


appendix C
Glossary of Terms
Some of the VHDL definitions in the following glossary were reprinted from "IEEE
Std-1076-1993, IEEE Standard VHDL Language Reference Manual," Copyright 1993 by the
Institute of Electrical and Electronics Engineers, Inc. The IEEE disclaims any responsibility or
liability resulting from the placement and use in the described manner. Information is reprinted
with the permission of the IEEE. VHDL terms taken from the IEEE standard are specifically
labeled VHDL Term - IEEE.
Sources for this glossary include:
Guide to Writing MAST Templates (manual from Synopsys Corporation).
Richard C. Dorf: The Electrical Engineering Handbook, CRC Press, 1993.
IEEE Standard Dictionary of Electrical and Electronics Terms.
The glossary is divided into the following topics:
"General Terms."
"VHDL-AMS Terms."
C.1. General Terms
analog simulation
Calculating the response of system models to an input stimulus. This response can be in either the
time domain or the frequency domain. All system variables change in a continuous manner, thus
requiring the simulator to solve simultaneous differential equations.
behavioral model
A model that describes the behavior of a system with an appropriate set of equations, algorithms,
building blocks and parameters. The behavioral method does not regard how the system is, or
might be, physically constructed. Also see "structural model ."
322 Appendix CGlossary of Terms

block
VHDL Term - IEEE
The representation of a portion of the hierarchy of a design. A block is either an external block or
an internal block.
bottom-up design approach
The process of designing and connecting low-level physical components together to create a design
that achieves a desired system-level behavior. This is contrasted with the "top-down desi gn
approach."
characteristic equations
A collection of mathematical equations that together with connection semantics describe the
behavior of a piecewise continuous model.
component
The model of a subsystem.
design file
VHDL Term - IEEE
One or more design units in sequence.
digital simulation
Simulation in which the models respond to scheduled events at their inputs, and whose outputs
assume only a finite number of values from a predefined set of discrete states. These discrete states
are usually referred to as logic levels.
instance
VHDL Term - IEEE
A subcomponent of a design entity whose prototype is a component declaration, design entity, or
configuration declaration. Each instance of a component may have different actuals associated
with its local ports and generics. A component instantiation statement whose instantiated unit
denotes a component creates an instance of the corresponding component. A component
VHDL-AMS Terms 323


instantiation statement whose instantiated unit denotes either a design entity or a configuration
declaration creates an instance of the denoted design entity.
mixed-signal
The common term for simulation of digital and analog electrical models in the same circuit.
mixed technology
Any combination of differing technologies, such as electronic, electrical, mechanical, or hydraulic.
model
VHDL Term - IEEE
The result of the elaboration of a design hierarchy. The model can be executed in order to simulate
the design it represents.
structural model
A model that describes a system as a hierarchical decomposition of constituent building blocks,
each of which represents intended or actual physical implementation. Also see "behavi oral
model ."
test bench
A design used to parameterize and exercise a specified block of design functionality.
top-down design approach
The process of creating a design by starting with the appropriate set of equations, algorithms and
parameters to describe the desired circuit behavior. As the design process progresses, the design is
refined until a physical description is achieved that meets the original objectives. This is contrasted
with the "bottom-up desi gn approach."
C.2. VHDL-AMS Terms
across and across quantity
The keyword across follows an identifier in either a nature definition or a branch quantity
declaration. In the case of a nature definition, the identifier must name a floating point type that
324 Appendix CGlossary of Terms

represents the driving force of the nature; in electrical systems this represents voltage. In the case of
a branch quantity declaration, the identifier names a quantity that represents the driving force
between the two terminals named in the branch quantity declaration; in electrical systems an across
quantity represents the voltage between two terminals.
architecture
An architecture body (also referred to as an architecture) is a fundamental building block for
models in VHDL/VHDL-AMS. An architecture represents the implementation of a model and can
provide either behavioral or structural descriptions for the implementation. Every architecture has a
related entity declaration (also referred to as an entity) that describes connections and parameters to
the model.
assert
An assert statement allows the modeler to specify a condition that must hold at the time that the
statement is evaluated. An assert statement may either occur within a process in which case it is
evaluated each time the statement is encountered in the process actions, or may occur in an
architecture in which case it is evaluated any time a signal changes that could effect the condition
specified in the assert statement. If the assert condition is false, a message is printed and simulation
may terminate depending on the action specified in the assert statement.
constant
A constant is a value that has been given a name. The value of a constant cannot change once it has
been defined.
dot
The attribute dot is used in the form qdot for some quantity, q. The attribute is itself a quantity
and reflects the derivative with respect to time of the quantity q.
entity
An entity declaration (also referred to as an entity) is a fundamental building block for models in
VHDL/VHDL-AMS. An entity represents the interface to a model or set of models. An entity
describes parameters (generics) that can be used to configure the behavior of an instance of the
model and connections (ports) that determine the simulated physical connections of an instance of
the model to other models in the system.
VHDL-AMS Terms 325


event
The attribute event is used in the form sevent for some signal, s. The attribute is a value of type
Boolean that is true if there has been a change in the value of s at the current simulation time.
generic
The keyword generic occurs in the definition of an entity and indicates that any instance of the
model can be configured based on the listed set of parameters. Typically, generic parameters are
used to describe model characteristics; in the case of an analog resistor model, resistance might be a
generic model characteristic that can be configured for each instance of the resistor. Generic
parameters may not change during simulation; their values are determined when an instance is
created and may not change after that point.
generic map
A generic map is used as part of a statement that creates an instance of a model that permits model
characteristics to be specified. A generic map provides a configuration value for each of the model
characteristics that, along with the implementation of the model, determine the behavior of the
instance of the model.
high
The attribute high is used in the form thigh for some type, t, or in the form ahigh for some array
a. In the case of simple ordered types such as real, integer, or any enumerated type, attribute high
produces the largest value representable within the type. For an array, high produces the largest
valid index for a specified dimension of the array.
library
A design library in VHDL or VHDL-AMS is a named collection of models. All models, when
compiled, reside in some library. All user-defined models go into a special library named work. It
is important to note that a library is an abstract name for a collection of models and may not
correspond to a file name in the operating system; the relationship between library names in VHDL
or VHDL-AMS source code and files in the operating system used to represent a library is not
defined by the language and is dependent on the simulator.
natural
VHDL-AMS provides the predefined type called natural, which is visible in any model consisting
of the integer values between 0 and the largest integer value for the simulator (e.g. integerhigh).
326 Appendix CGlossary of Terms

nature
A nature is a description of the types of values that are used to describe some physical domain. A
nature consists of an across aspect that represents the driving force in the domain (such as voltage,
temperature, or illuminance) and a through aspect that represents the force being driven in the
domain (such as current, heat flow, or optic flux). Additionally, each nature has a reference aspect
that names the reference node in the physical domain (such as ground for electrical systems).
now
The function now returns the current simulation time. The function is overloaded to return either a
value of type real, which represents the simulation time in seconds, or a value of type time, which
reports the current simulation time as an integer multiple of the simulators smallest discrete time
step, generally femto-seconds.
port
The keyword port occurs in the declaration of an entity and describes the simulated physical
connections to an instance of the model. Port declarations may describe signal, terminal, or quantity
connections to the rest of the system.
port map
A port map is used as part of a statement that creates an instance of a model and describes the
connections between the model creating the new instance and the new instance itself.
process
A process is a section of sequentially-evaluated code that describes transitions within an instance of
a model based on the state of the instance and the connections to the instance. A process may wait
for events, perform calculations, print information, or take many other kinds of actions. Each
process automatically loops over the entire set of sequential statements in the process for as long as
the simulation proceeds.
quantity
A quantity is an unknown in a system of equations that describes the behavior of the analog aspects
of a model. The value of a quantity is determined by the simulator by simultaneously solving the
system of equations formed by the simultaneous statements (equations) in the model and implicit
equations that result from conservation laws and the interconnection of the models.
VHDL-AMS Terms 327


range
The range attribute represents the entire range of valid values of some type. In the case of arange
where a is an array, the range attribute represents the range of valid index values of a specified
dimension of the array. This is particularly useful when used in conjunction with unconstrained
array port connections or generic parameters that do not have definite bounds that the model
knows. Using the range attribute, the model can be written in such a way that it does not need to
assume what constitutes the valid index values for the array.
reference
The reference aspect of a nature definition provides a name for a terminal in the nature that always
represents the node against which all across values are calculated. For example, in electrical
systems, across values represent voltages and are calculated as a difference with respect to ground,
which has the assumed voltage level of 0.0.
report
A report statement takes a string literal or string expression and prints the string to the simulation
output.
return
A return statement is used in a function to terminate the evaluation of the function and to specify
the result value of the function. In a procedure, which doesnt return a value, a return statement
simply terminates the evaluation of the procedure.
signal
A signal is used to describe event-driven behavior in a model. A signal can also represent
connections between components in a system or within a component. Because a signal is
event-driven, its value changes in a discrete manner; a signal holds a value for some period of time
and then changes immediately and discontinuously to a new value.
simultaneous statements
Simultaneous statements are used to define the continuous-time behavior of a model. Simple
simultaneous statements are the basic equations that define relationships between quantities,
signals, and constants which in turn determine the set of equations for which the simulator must
find a simultaneous solution. A simultaneous if statement is a variant of a normal sequential if
statement but is used in describing sets of equations that form part of the analog aspect of a model.
328 Appendix CGlossary of Terms

A simultaneous if statement allows for simulation time replacement of equations in the system of
equations and can be used to represent analog behavior that changes between various regions of
operation that may depend on discrete events, on analog values, or on model configuration.
STD_LOGIC
STD_LOGIC is a nine-valued logic type defined as part of the IEEE Standard Multivalue Logic
System for VHDL Model Interoperability (Std_Logic_1164). It is used to represent states of digital
systems including representations for high impedance, weak, and forcing values.
terminal
A terminal is an analog connection point or pin that corresponds to a physical connection point in
some domain in the system. A terminal is defined to be of some nature that defines the properties of
the physical domain. In electrical terms, a terminal can be understood to be a physical connection
point at which voltage and current can be measured.
through and through quantity
The keyword through follows an identifier in either a nature definition or a branch quantity
declaration. In the case of a nature definition, the identifier must name a floating point type that
represents the driven force of the nature; in electrical systems this represents current. In the case of
a branch quantity declaration, the identifier names a quantity that represents the driven force
through that point in the system; in electrical systems a through quantity represents the current
through the connection point.
use
A use clause is associated with a model to indicate that the model needs access to declarations
contained in a package. A use clause is required in order to be able to access declarations in
packages (other than for package Std.Standard, which is automatically used in every design). A use
clause relates to only the model immediately following the clause even if there are additional
models later in the file containing the VHDL-AMS source code for the model.
work
The identifier work is the name of a predefined library into which all user models are entered by
default. It is up to the simulation system to define a mechanism for creating new libraries and for
managing library contents; VHDL-AMS has no requirements regarding the creation of new
libraries.


appendix D
References
Simulation
[1] J. Vlach and K. Singhal, Computer Methods for Circuit Analysis and Design, Van Nostrand
Reinhold, New York, NY, 1983.
[2] R. Kielkowski, Inside SPICE: Overcoming the Obstacles of Circuit Simulation, McGraw-Hill,
New York, NY, 1994.
MAST Modeling
[3] A. Mantooth and M. Fiegenbaum, Modeling with an Analog Hardware Description Language,
Kluwer, Dordrecht, The Netherlands, 1995.
[4] Synopsys documentation and training material:
Saber MAST Reference Manual
Saber MAST Language User Guide, Book 1 & 2
Introduction to MAST Modeling (Training course)
Advanced Saber/MAST Modeling (Training course)
Hydraulic Simulation with Saber (Training course)
Mechanical Simulation with Saber (Training course)
VHDL (-AMS) Modeling
[5] P. J. Ashenden, The Designers Guide to VHDL, Morgan Kaufmann, San Francisco, CA, 1996.
[6] Synopsys documentation and training material:
Guide to Mixed-Signal Simulation: Book One: VHDL-AMS
[7] E. Christen, K. Bakalar, A. Dewey, E. Moser, Analog and Mixed-Signal Modeling Using the
VHDL-AMS Language, 36
th
Design Automation Conference, New Orleans, 1999.
330 Appendix DReferences



appendix E
Index
A
above attribute. See attributes (V)
accumulator. See hydraulic modeling
accuracy 318
across and across quantity (V)
definition of 48, 323
across variables 71
actuator, spring acting extend. See hydraulic
modeling
ai_standard.vhd. See packages (V)
ambient_temperature (V) 87, 113
analog simulation 7
definition of 321
anti-lock brake system. See hydraulic
modeling
architecture (V) 44
definition of 324
argbp. See bullet-proofing, functions (M)
argrngbp. See bullet-proofing, functions (M)
argsbp. See bullet-proofing, functions (M)
argument checking (M) 98
error function 99
instance function 99
message function 98
warning function 99
argument checking (V) 97
assert 97
definition of 324
report 97
severity 97
assert. See argument checking (V)
attributes (V) 48
composing 92, 148
qabove 49, 168
shigh 49, 176
simage 49
slow 49, 176
srange 49, 209
timage 97
See also implicit quantities
B
backward Euler. See numerical integration
techniques
behavioral model
definition of 321
behavioral model (M)
definition of 53
overview 62
behavioral model (V)
definition of 37
overview 43
bilinear transform 213
block
definition of 322
bottom-up design
definition of 322
bp, breakpoint (M) 263
branch statement (M) 62, 119
break on statement (V) 119, 181
bullet-proofing
definition of 95
examples

1. Suffix (V) indicates the given subject applies only to VHDL-AMS; suffix (M) indicates the given subject applies
only to MAST.
1
332 Appendix EIndex
op amp 100
resistor 96
functions (M) 313
argbp 313
argrngbp 314
argsbp 314
ratingbp 311
techniques
divide by zero 95
negative values 95
range of operation 96
bullet-proofing techniques
range of operation 95
resistor example 95
C
capacitor
linear 77
with ESR and leakage 88
case statement (V) 176, 194
characteristic equations
definition of 322
clock, implementation (M) 173
combination, linear. See sampled data
modeling
comments (M) 64
comparator. See mixed-signal modeling
compensator, lead-lag. See signal flow
modeling
component
definition of 322
conservation laws 72
constant (V)
declaration 50
definition of 324
consts.sin (M) 86
control section. See sections (M)
convergence
discontinuous first derivatives 267
discontinuous functions 264
Newton damping 260
numerical divergence 260
numerical oscillation 259
zero slope regions 271
converter, 8-bit A/D. See mixed-signal
modeling
converter, 8-bit D/A. See mixed-signal
modeling
corrector 29, 296
current source
constant 73
voltage-controlled 80
D
d_by_dt (M) 78
damper, translational. See mechanical
modeling
dc_domain simvar. See simulator variables
(M)
dc_done simvar. See simulator variables (M)
dc_init simvar. See simulator variables (M)
dc_start simvar. See simulator variables (M)
declarations (M) 66
delay. See sampled data modeling
delayed attribute. See implicit quantities (V)
density 26
derivatives, how to define multiple (M) 86
deschedule event (M) 308
design file
definition of 322
differential-algebraic equation (DAE) 7
differentiator
double. See signal flow modeling
single. See signal flow modeling
digital simulation
definition of 322
diode, ideal piecewise linear 120
distfunc, distribution function (M) 315
divide by zero. See bullet-proofing,
techniques
dot attribute. See implicit quantities (V)
dsp_systems.vhd. See packages (V)
duty cycle, calculation 172
E
electrical
across and through variables 72
entity (V) 44
definition of 324
Appendix EIndex 333
equations section. See sections (M)
error function. See argument checking (M)
event_on (M) 181, 306
exponential source. See source modeling
external variables (M) 88
F
filter
general purpose 2nd order. See signal
flow modeling
lowpass. See sampled data modeling
two pole. See signal flow modeling
fluid chamber. See hydraulic modeling
fluidic terminal type. See hydraulic pin type
227
foreign subroutines (M) 136
passing numbers 137
passing strings 138
passing structures 137
foreign subroutines (V) 135
forward Euler. See numerical integration
techniques
freq simvar. See simulator variables (M)
freq_domain simvar. See simulator variables
(M)
freq_mag simvar. See simulator variables
(M)
freq_phase simvar. See simulator variables
(M)
function (M)
thermal_par_value 115
function (V)
thermal_par_value 114
function, user-defined (M) 115
function, user-defined (V) 102, 113, 195,
238
G
gain. See signal flow modeling
Gear 2. See numerical integration techniques
generic (V)
declaration 50
definition of 325
generic map (V)
definition of 325
global temperature
See ambient_temperature (V)
See header.sin (M)
granularity 318
H
hard stop. See mechanical modeling
header.sin (M) 88
temp, global temperature 88
high attribute. See attributes (V)
hyd_mks (M). See hydraulic pin type
hydraulic (fluidic) across and through
variables 72
hydraulic modeling
accumulator 232
actuator, spring acting extend 229
anti-lock brake system 222
fluid chamber 225
valve, 2-way 235
hydraulic pin type
fluidic (V) 227
hyd_mks (M) 228
I
identifiers (M) 64
ieee.math_real.all. See packages (V)
if statement (M) 99, 302
for piecewise linear models 119
if statement (V) 103
for piecewise linear models 118
image attribute. See attributes (V)
implicit quantities (V) 48
qabove 118, 165
qdelayed 49
qdot 48, 78, 324
qinteg 48, 150
qltf 49, 156
qramp 127
qzoh 49
qztf 49
sramp 48, 184, 185
sslew 48
See also attributes
in, input quantity (V)
port declarations 145
334 Appendix EIndex
inc, increment (M) 263
include files (M) 86
inductor, linear 78
initialization, of pin values (M) 150
input pin (M)
declarations 146
instance
definition of 322
instance function. See argument checking
(M)
integ attribute. See implicit quantities (V)
integrator. See signal flow modeling
interface model
A/D. See mixed-signal modeling
D/A. See mixed-signal modeling
J
Jacobian matrix 24, 27, 290, 297
L
library (V)
definition of 325
light
across and through variables 72
limit, step size (V) 131
limiter
non-conserved. See signal flow
modeling
voltage 117
line continuation (M) 63
linear algebraic equations. See simulation
linear differential-algebraic equations. See
simulation
linearization
piecewise linear approximation 25
piecewise linear evaluation 26
taking the slope 24
logic_4, pin type (M) 169
low attribute. See attributes (V)
ltf attribute. See implicit quantities (V)
M
macromodel (M)
definition of 53
example 56
op amp 58
VCVS 60
macromodeling (M)
limitations 4
See also structural modeling
magnetic
across and through variables 72
mass, translational. See mechanical modeling
math_2_pi. See packages (V)
math_real
math_pi (M) 86
mathematical functions (M) 302
mathematical operators (M) 301
mechanical modeling
across and through variables
rotational 72
translational 72
anti-lock brake system 241
damper, translational 247
hard stop 248
mass, translational 244
overview 241
spring, nonlinear translational 245
mechanical pin type (M)
rotational_vel 253
translational_pos 228
message function. See argument checking
(M)
mixed technology
definition of 323
mixed-signal
definition of 323
mixed-signal modeling
analog threshold detecting 164
comparator 167
continuous analog transitions 182
converter
8-bit A/D 173
8-bit D/A 187
dc initialization 163
definition of 161
digital event
detecting 180
scheduling 166
Appendix EIndex 335
digital/analog signal synchronizing 181
interface models 192
A/D 193
D/A 198
modulator, pulsewidth 170
switch, digitally-controlled 184
timestep control 164
mixed-signal modeling (M) 304
mixed-technology modeling
motor, DC 251
pump 253
See also hydraulic modeling
model
defining the scope of 72
definition of 71
definition of (V) 323
parameterizing (M) 54
parameterizing (V) 37, 38
modeling, steps for 81
modulator, pulsewidth. See mixed-signal
modeling
motor, DC. See mixed-technology modeling
N
natural (V)
definition of 325
nature (V) 47
definition of 326
negative values. See bullet-proofing,
techniques
netlist (M) 56
netlist section. See sections (M)
Newton step (M)
specification syntax 319
Newton-Raphson method 19
next_time simvar. See simulator variables
(M)
nonlinear algebraic equations. See simulation
nonlinear differential-algebraic equations.
See simulation
now, predefined function (V) 123, 131
definition of 326
numerical integration techniques
backward Euler 14, 296
forward Euler 14, 295
Gear 2 15
trapezoid rule 15
O
op amp
ideal 81
with input/output effects 89
out (output) quantity (V)
port declarations 145
output pin (M)
declarations 146
P
packages (V) 45
ai_standard.vhd 87
dsp_systems.vhd 176
ieee.math_real.all 85
math_real 46
parameters section. See sections (M)
port (V)
definition of 326
port_map (V)
definition of 326
predictor 29, 294, 295
process (V) 127
definition of 326
pulse source. See source modeling
pump. See mixed-technology modeling
Q
quantity (V) 47
definition of 326
port declarations 145
R
ramp attribute. See implicit quantities (V)
range attribute. See attributes (V)
range of operation. See bullet-proofing,
techniques
ratingbp. See bullet-proofing, functions (M)
real_table, std_logic array type (V) 199
real_vector, array type (V) 156, 210
reference (V)
definition of 327
report (V)
definition of 327
336 Appendix EIndex
See also argument checking
resistor
linear 76
with temp. dependency 86
return (V)
definition of 327
rotational_v terminal type (V) 252
rotational_vel. See mechanical pin type (M)
S
sample points (M) 26
accuracy 318
considerations 317
density 317
selecting 317, 318
specification syntax 319
sample/hold. See sampled data modeling
sampled data modeling
characteristics of 203
combination, linear 207
delay 209
filter, lowpass 212
from s-domain 212
create difference equations 214
create models 215
transform lowpass filter 212
sample/hold 204
schedule_event (M) 166, 307
schedule_next_time function (M) 129, 133,
308
sections (M)
control 68, 150
equations 68, 86
header 66
netlist 67, 232
parameters 66, 86
values 67
when (statements) 67
sensitivity, of process (V) 180
severity. See argument checking (V)
signal (V)
definition of 327
pin type
real 206
std_logic 168
signal flow modeling
characteristics of 144
compensator, lead-lag 150
differentiator, double 148
differentiator, single 147
filter, general purpose 2nd order 157
filter, two pole 155
gain 145
integrator 149
limiter 152
summer, 2-input 146
simulation
defined, for digital computer 8
flow, time-domain analysis 8
of linear algebraic equations 10, 279
of linear DAEs 13, 283
of nonlinear algebraic equations 19, 288
of nonlinear DAEs 29, 292
resolution 318
simulator variables (M) 134, 305
dc_domain 134, 305
dc_done 305
dc_init 305
dc_start 305
freq 306
freq_domain 306
freq_mag 134, 306
freq_phase 134, 306
next_time 133, 306
statistical 306
step_size 306
time 123, 132, 306
time_domain 134, 305
time_init 306
time_step_done 306
tr_done 306
tr_start 306
simultaneous statements (V) 49
definition of 327
sin, sinusoidal function (M) 132
sin, sinusoidal function (V) 131
sinusoidal source. See source modeling
Appendix EIndex 337
slew attribute. See implicit quantities (V)
small-signal AC (M) 133
small-signal AC (V) 131
solvability conditions (M) 63
solvability conditions (V) 46
source modeling
exponential 122
pulse 124
sinusoidal 129
spring, nonlinear translational. See
mechanical modeling
state, pin type (M) 169, 207
statistical modeling (M) 315
statistical simvar. See simulator variables
(M)
std_logic (V)
definition of 328
subtype 168
std_logic_byte (V) 176, 188
std_logic_vector (V) 176, 188
step_size simvar. See simulator variables (M)
step_size, limiting (M) 132, 133
stress analysis modeling (M) 310
structural modeling (V)
defined 37
definition of 323
example 39
limitations 4
op amp 40
VCVS 42
See also macromodeling
structures (M) 133
subtype (V) 168
summer, 2-input. See signal flow modeling
switch, digitally-controlled. See
mixed-signal modeling
syntax (M) 63
T
temp, global temperature (M). See header.sin
template structure (M) 65
terminal (V) 47
definition of 328
test bench (V)
definition of 37, 323
example 51, 215
test circuit (M)
definition of 53
example 69
thermal
across and through variables 72
threshold function (M) 309
through and through quantity (V)
definition of 48, 328
through variables 71
time simvar. See simulator variables (M)
time_domain simvar. See simulator variables
(M)
time_init simvar. See simulator variables (M)
time_step_done simvar. See simulator
variables (M)
timestep 8, 13, 29
definition of 9
in pulse source 124
in sinusoidal source 129
top-down design 2, 141
definition of 323
tr_done simvar. See simulator variables (M)
tr_start simvar. See simulator variables (M)
translational terminal type (V) 227
translational_pos. See mechanical pin type
(M)
trapezoid rule. See numerical integration
techniques
type (V)
user-defined example 176
U
undef, intrinsic number (M) 105
undef, predefined constant (V) 103
units.sin, pin unit definitions (M) 169, 228
use clause (V)
definition of 328
with if statements 239
V
values section (M) 93, 200, 276
values section. See sections (M)
valve, 2-way. See hydraulic modeling
338 Appendix EIndex
var (M) 86
variable (V) 114, 176, 194
variable types (M) 304
voltage source, constant 74
W
wait for (V) 127
wait on (V) 127, 180, 194
warning function. See argument checking
(M)
when statement (M)
defined 304
example, pulse source 129
when statements. See sections (M)
work (V)
definition of 328
Z
zoh attribute. See implicit quantities (V)
ztf attribute. See implicit quantities (V)

Potrebbero piacerti anche