best practices for compact modeling in verilog-a

14
Received 21 May 2015; revised 26 June 2015; accepted 6 July 2015. Date of publication 10 July 2015; date of current version 21 August 2015. The review of this paper was arranged by Editor M. Chan. Digital Object Identifier 10.1109/JEDS.2015.2455342 Best Practices for Compact Modeling in Verilog-A COLIN C. MCANDREW 1 (Fellow, IEEE), GEOFFREY J. CORAM 2 (Senior Member, IEEE), KIRAN K. GULLAPALLI 3 , J. ROBERT JONES 4 (Senior Member, IEEE), LAURENCE W. NAGEL 5 (Life Fellow, IEEE), ANANDA S. ROY 6 (Member, IEEE), JAIJEET ROYCHOWDHURY 7 (Fellow, IEEE), ANDRIES J. SCHOLTEN 8 (Senior Member, IEEE), GEERT D. J. SMIT 9 , XUFENG WANG 10 (Member, IEEE), AND SADAYUKI YOSHITOMI 11 (Member, IEEE) 1 Freescale Semiconductor, Inc., Tempe, AZ 85284, USA 2 Analog Devices, Inc., Wilmington, MA 01887, USA 3 Freescale Semiconductor, Inc., Austin, TX 78735, USA 4 Raytheon, Andover, MA 01810, USA 5 Omega Enterprises Consulting, Kensington, CA 94708, USA 6 Intel Corporation, Hillsboro, OR 97124, USA 7 School of Electrical and Computer Engineering, University of California, Berkeley, CA 94720, USA 8 NXP Semiconductors, Eindhoven 5656 AE, The Netherlands 9 NXP Semiconductors, Nijmegen 6534 AE, The Netherlands 10 School of Electrical and Computer Engineering, Purdue University, West Lafayette, IN 47907, USA 11 Semiconductor and Storage Products Company,Toshiba Corporation, Tokyo 105-0023, Japan CORRESPONDING AUTHOR: C. C. MCANDREW (e-mail: [email protected]) This work was supported in part by the IEEE Electron Devices Society Technical Area Committee on Compact Modeling, in part by the NSF/SRC Nano-Engineered Electronic Device Simulation Project, and in part by the Compact Model Coalition. ABSTRACT Verilog-A is the de facto standard language that the semiconductor industry uses to define compact models. Unfortunately, it is easy to write models poorly in Verilog-A, and this can lead to unphysical model behavior, poor convergence, and difficulty in understanding and maintaining model codes. This paper details best practices for writing compact models in Verilog-A, to try to help raise the quality of compact modeling throughout the industry. INDEX TERMS SPICE, semiconductor device modeling, integrated circuit modeling, circuit simulation. I. INTRODUCTION Compact models are the models of circuit components (field-effect transistors, bipolar transistors, resistors, capac- itors, etc.) that are used within circuit simulators; they are the means by which the electrical behavior of a component is represented for circuit design. Historically, compact models: were written in FORTRAN or C, com- prising up to tens of thousands of lines of code for a complex model; were “built-in” to, and tightly coupled to the numerical algorithms used in, simulators; and required explicit hand-coding of derivatives with respect to the system unknowns (generally node voltages), which is a tedious and error-prone task. Starting in the late 1980’s, it became apparent, although not widely appreciated, that there were significant advantages in separating model definitions from simulators [1]–[3]. Besides decoupling models from numerical algorithms, it enabled the use of symbolic differentiation to automate the generation of derivatives, at one fell swoop eliminating the primary source of coding errors in models. It also became clear that having a standard language for defining compact models would be of great benefit, and that the hardware description languages VHDL-AMS [4] and Verilog-A, the analog only subset of Verilog-AMS [5], originally intended for behavioral modeling of analog and mixed-signal sys- tems, were good candidates to be appropriated for that purpose. Despite significant initial resistance, Verilog-A has emerged as the de facto standard language for defining and distributing compact models. It is a “natural” language to use to write compact models, and in 2004 constructs explic- itly for the purpose of compact modeling were added [6]. A compact model written in Verilog-A: requires of the order of one tenth as many lines of code as an implementation in C (primarily because it automatically generates derivatives, so does not require them to be explicitly hand-coded, and 2168-6734 c 2015 IEEE. Translations and content mining are permitted for academic research only. Personal use is also permitted, but republication/redistribution requires IEEE permission. VOLUME 3, NO. 5, SEPTEMBER 2015 See http://www.ieee.org/publications_standards/publications/rights/index.html for more information. 383

Upload: others

Post on 20-Nov-2021

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Best Practices for Compact Modeling in Verilog-A

Received 21 May 2015; revised 26 June 2015; accepted 6 July 2015. Date of publication 10 July 2015; date of current version 21 August 2015.The review of this paper was arranged by Editor M. Chan.

Digital Object Identifier 10.1109/JEDS.2015.2455342

Best Practices for Compact Modeling in Verilog-ACOLIN C. MCANDREW1 (Fellow, IEEE), GEOFFREY J. CORAM2 (Senior Member, IEEE), KIRAN K. GULLAPALLI3,

J. ROBERT JONES4 (Senior Member, IEEE), LAURENCE W. NAGEL5 (Life Fellow, IEEE),ANANDA S. ROY6 (Member, IEEE), JAIJEET ROYCHOWDHURY7 (Fellow, IEEE),

ANDRIES J. SCHOLTEN8 (Senior Member, IEEE), GEERT D. J. SMIT9,XUFENG WANG10 (Member, IEEE), AND SADAYUKI YOSHITOMI11 (Member, IEEE)

1 Freescale Semiconductor, Inc., Tempe, AZ 85284, USA2 Analog Devices, Inc., Wilmington, MA 01887, USA

3 Freescale Semiconductor, Inc., Austin, TX 78735, USA4 Raytheon, Andover, MA 01810, USA

5 Omega Enterprises Consulting, Kensington, CA 94708, USA6 Intel Corporation, Hillsboro, OR 97124, USA

7 School of Electrical and Computer Engineering, University of California, Berkeley, CA 94720, USA8 NXP Semiconductors, Eindhoven 5656 AE, The Netherlands9 NXP Semiconductors, Nijmegen 6534 AE, The Netherlands

10 School of Electrical and Computer Engineering, Purdue University, West Lafayette, IN 47907, USA11 Semiconductor and Storage Products Company,Toshiba Corporation, Tokyo 105-0023, Japan

CORRESPONDING AUTHOR: C. C. MCANDREW (e-mail: [email protected])

This work was supported in part by the IEEE Electron Devices Society Technical Area Committee on Compact Modeling, in part by the NSF/SRC

Nano-Engineered Electronic Device Simulation Project, and in part by the Compact Model Coalition.

ABSTRACT Verilog-A is the de facto standard language that the semiconductor industry uses to definecompact models. Unfortunately, it is easy to write models poorly in Verilog-A, and this can lead tounphysical model behavior, poor convergence, and difficulty in understanding and maintaining modelcodes. This paper details best practices for writing compact models in Verilog-A, to try to help raise thequality of compact modeling throughout the industry.

INDEX TERMS SPICE, semiconductor device modeling, integrated circuit modeling, circuit simulation.

I. INTRODUCTIONCompact models are the models of circuit components(field-effect transistors, bipolar transistors, resistors, capac-itors, etc.) that are used within circuit simulators; theyare the means by which the electrical behavior of acomponent is represented for circuit design. Historically,compact models: were written in FORTRAN or C, com-prising up to tens of thousands of lines of code for acomplex model; were “built-in” to, and tightly coupled tothe numerical algorithms used in, simulators; and requiredexplicit hand-coding of derivatives with respect to the systemunknowns (generally node voltages), which is a tedious anderror-prone task.Starting in the late 1980’s, it became apparent, although

not widely appreciated, that there were significant advantagesin separating model definitions from simulators [1]–[3].Besides decoupling models from numerical algorithms, itenabled the use of symbolic differentiation to automate the

generation of derivatives, at one fell swoop eliminating theprimary source of coding errors in models. It also becameclear that having a standard language for defining compactmodels would be of great benefit, and that the hardwaredescription languages VHDL-AMS [4] and Verilog-A, theanalog only subset of Verilog-AMS [5], originally intendedfor behavioral modeling of analog and mixed-signal sys-tems, were good candidates to be appropriated for thatpurpose.Despite significant initial resistance, Verilog-A has

emerged as the de facto standard language for defining anddistributing compact models. It is a “natural” language touse to write compact models, and in 2004 constructs explic-itly for the purpose of compact modeling were added [6].A compact model written in Verilog-A: requires of the orderof one tenth as many lines of code as an implementation in C(primarily because it automatically generates derivatives,so does not require them to be explicitly hand-coded, and

2168-6734 c© 2015 IEEE. Translations and content mining are permitted for academic research only.Personal use is also permitted, but republication/redistribution requires IEEE permission.

VOLUME 3, NO. 5, SEPTEMBER 2015 See http://www.ieee.org/publications_standards/publications/rights/index.html for more information. 383

Page 2: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

eliminates simulator interface code); is independent of thedata structures and numerical algorithms used in a particularsimulator; and is standardized. These attributes lead to com-pact model codes that can be much more easily implemented,ported between different simulators, understood, and main-tained than if they were written in C, which in turn leads tosignificantly improved model quality.Early Verilog-A compilers were not consistent in inter-

pretation of the language reference manual (LRM) andimplemented different subsets of the LRM, so sometimesdifferent Verilog-A code was required for the same modelto run in different simulators. As the language and compil-ers have matured, these differences have mostly disappeared,and the promise of portability is becoming a reality. Initially,Verilog-A compilers could be slow, and the code theygenerated had run times during transient simulations thatwere roughly 100 times longer than if a model was handcoded in C. However, some years ago there was a signif-icant advance in the efficiency of Verilog-A compilers inboth proprietary and commercial simulators and run timesfor complex models defined in Verilog-A are now withinabout a factor of 2 of those of hand-coded C, and usu-ally only 5–20% slower. There are even examples wherethe run times of Verilog-A models are comparable to orslightly faster than C coded models [7], [8], and contin-ued development of compilers will drive these run timesstill lower.However, even though Verilog-A is ideally suited for com-

pact modeling and precludes some coding mistakes it, likeall programming languages, does not prevent people fromwriting models that are challenging to read, difficult to con-verge, inefficient, and/or fundamentally poor. History showsthat many compact models written in Verilog-A are not par-ticularly good; even experienced compact model developerscan make subtle, and sometimes not-so-subtle, mistakes.Guidelines on how to write good models in Verilog-A,detailing both pitfalls to avoid and best practices to fol-low, have been published [9]–[14]; however, these are oftenoverlooked. Even people who could best benefit from follow-ing them (and not just by following the guidelines blindly,but rather learning why they were explicitly pointed out aspractices to either adopt or avoid, thereby better knowinghow Verilog-A, and circuit simulators, work) do not complywith the guidelines, as they are unaware of them or do notunderstand them properly.Here, we assemble best practices for writing compact

models in Verilog-A. We use examples derived from realmodels to explain these recommendations. These guidelinesdraw heavily on the prior material reported in [9]–[14].As companion material we provide: useful generic Verilog-A macros and pn−junction charge and current Verilog-Abuilding blocks [15]; and an example Verilog-A model [16],the R3 model for poly resistors, diffused resistors, andJFETs, that is neither too simple to be of practical usenor so complex that it obfuscates the underlying codingpractices.

This paper is not a tutorial on Verilog-A; it assumes thatreaders have a basic knowledge of Verilog-A.

II. CIRCUIT SIMULATIONTo understand how to best define a compact model it isessential to understand how circuit simulators work. A cir-cuit simulator predicts the behavior of an electronic circuit byconstructing and numerically solving a mathematical modelof the circuit. This model consists of the topological connec-tivity, and compact models, of the components that comprisethe circuit, including unintended elements such as parasiticcapacitance, resistance, and inductance.The mathematical model of the circuit is a system of

nonlinear, coupled, differential algebraic equations (DAEs)

F(x, x, t) = 0 (1)

where x are the system unknowns to be solved for andx = dx/dt. Since the advent of SPICE [17] the most commonformulation for circuit simulators has been modified nodalanalysis (MNA). For nodal analysis x are the voltages of,and F are Kirchhoff’s current law (KCL) at, each node ofthe equivalent network of the circuit. For nodal analysis (1)can be written in a more specific way [12]

f [x(t)] + d

dtq [x(t)] = u(t) (2)

where f are the currents flowing in static branches of theequivalent network, dq/dt are the (capacitive) currents flow-ing in time-dependent branches of the equivalent network,and u is a vector of stimuli.Two major, common types of components do not naturally

fit into this paradigm [17]: voltage sources and inductors.For such an element x must be augmented with the value ofthe current through the element, and the equation to includein F (the branch constitutive relation BCR) is the voltagerelationship for the element; hence the “modified” qualifierin MNA.Therefore, to best fit in with the nodal formulation on

which circuit simulators are based, and to minimize thenumber of extra variables included in x, compact modelsshould be based on voltage-controlled current elements I(V)

and the time derivative of voltage-controlled charge elementsdq(V)/dt. This is not always possible for every element inthe equivalent network of a compact model, but where amodel can be formulated in that way it should be: Do notuse the advanced capabilities of Verilog-A to write a com-pact model; use I(V), dq(V)/dt, and only where absolutelynecessary V(I) and dI/dt type branches.

Verilog-A is not defined solely in terms of electrical vari-ables, but allows arbitrary physical disciplines to be defined.These definitions specify a potential (or across variable) anda flow (or through variable). The former obey the generalloop extension of Kirchhoff’s voltage (potential) law, thelatter obey the broadening of KCL to a general flow conser-vation law. Any discipline in which it is possible to formulate

384 VOLUME 3, NO. 5, SEPTEMBER 2015

Page 3: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

FIGURE 1. Using SPICE to solve equations.

a model in terms of conserved through variables as functionsof across variables can be handled by Verilog-A1.

Note that SPICE and other circuit analysis programs arenot “just” circuit simulators. They are nonlinear, coupledDAE solvers that happen to have been targeted to solvingelectrical network problems. During development of a modelyou may have a situation where you need to numericallysolve some equation as part of a model, and thinking ofthe simulator as just a program that solves (2) can helpto formulate your problem in an appropriate manner. Forexample, to solve

h(Vx,V1,V2, . . .) = 0 (3)

for a scalar quantity Vx (here assumed to be voltage), defineVx as the potential on a node that is internal to a modeland set up a single current contribution of value h flowinginto (or out of, it does not matter which) that node, seeFig. 1. This in essence adds h(Vx,V1,V2, . . .) = 0 as oneof the nonlinear algebraic equations that the simulator mustself-consistently solve, and leverages the advanced solutionalgorithms that are implemented in a simulator to solve yourequation.You need to be careful when “requesting” that the simula-

tor solve such a nonlinear equation to ensure that the functionand its derivatives are numerically well behaved for all valuesof Vx,V1,V2, . . . , that the function is scaled appropriatelyfor the simulator convergence tolerances, and that it has a sin-gle solution that can be found reliably by Newton’s method.Some simulators may complain about floating nodes if youuse the topology on the left of Fig. 1; in that case use thetopology on the right, with h = h1 + h2, and declare eachbranch to have a different name. Also, if you require anequation to be solved to a tighter tolerance than the conver-gence criteria set for the simulator then you need either tosolve it yourself or to define a new nature with appropriateconvergence tolerances.Circuit simulators do not solve Maxwell’s equations, they

solve Kirchhoff’s current law and assume the circuit com-ponents interact via perfectly conducting wires, with nofields internal to one component directly interacting withthe fields internal to another component. Gauss’s Law inintegral form is ∫∫

SE · dA =

∫∫∫V

ρ

εdV, (4)

1. Verilog-A can of course handle more general model formulations.

FIGURE 2. ddt() currents should not be referenced to ground. The ellipserepresents a device, with ports 1, 2, and 3 from left to right.

where S is the closed surface encompassing a volume V , E iselectric field, ρ is the charge density per unit volume, whichcan vary with position within V , and ε is the permittivity.Because fields external to a device are assumed not to affectthe internal state of a device, the integral on the left handside of (4) is zero; therefore the right hand side must alsobe zero. But integrating the charge density on the right handside gives the total charge qtot within a region, therefore

qtot = 0 (5)

must hold for a compact model2.

III. COMPACT MODEL FORMULATIONThis section details best practices related to fundamentalphysical requirements and alignment with circuit simulatoroperation.Verilog-A is a rich language. You can define models in

terms of Laplace and Z-transform functions, define actionsto happen on specific events, such as a voltage level crossinga certain value, and implement ideal delays. These capabili-ties can be exceedingly useful for implementing an abstractbehavioral model of an analog circuit block in a manner thatenables it to be efficiently simulated at the full IC or sys-tem level. But they have no place in a compact model andmay be non-causal or otherwise break the laws of physics.The first rule for defining a compact model in Verilog-A is:do not do anything complex. To reiterate from the previoussection, circuit simulators are based on nodal analysis usingnode voltages as variables, so formulate a compact modelusing I(V) and dq(V)/dt wherever possible, and V(I) anddI/dt where necessary.

Circuit simulators are primarily DAE solvers, so (see (2))formulate compact models using the time derivative operatorddt() but do not use the time integral operator idt(). Youcan convert the latter into the former by explicitly addingan extra system unknown. For example, for an inductor

IL =∫

VLLdt (6)

2. We are glossing over details of work function potential and permit-tivity differences between different portions of a device; they do not affectthe result that a region for which a compact model is to be developed mustbe charge neutral.

VOLUME 3, NO. 5, SEPTEMBER 2015 385

Page 4: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

and this can be transformed from an integral BCR to aderivative BCR by including IL as a system unknown, then

VL = LdILdt

. (7)

In Verilog-A a current is automatically added as a systemunknown when you reference it using the access functionI(branch) on the right hand side of an expression, so allyou have to do is code your model as

V(branch) <+ ddt(L*I(branch));

or to include a nonlinearity formulate in terms of ddt() ofmagnetic flux phi(I(branch)).

The currents and charges in a device do not change ifthe same, but arbitrary, value is added to the potential of allexternal ports (i.e., terminals). Therefore, the formulation of acompact model should be independent of, and not reference,the ground node3.Static currents flow in branches between nodes, but

charges are associated with individual nodes, not withbranches. This has led some models to be formulated withddt() of the nodal charges referenced to ground, as in theleft equivalent circuit of Fig. 2. The dq1/dt current can beequivalently represented as flowing from port 1 to port 2and then from port 2 to ground (this manipulation adds nonet current to port 2), and similarly for dq3/dt, which givesthe equivalent circuit in the middle of Fig. 2. But from (5)the sum of all charges in a device must be zero, hence somust d(q1 + q2 + q3)/dt, leading to the equivalent represen-tation on the right of Fig. 2. So although compact modelsare formulated in terms of nodal charges, the ddt() cur-rents associated with those charges should be implementedas branch currents, n− 1 of them for an n−port device withno internal nodes, referenced to an arbitrary reference port.Other basic requirements for compact models are:• They should be passive, i.e., they should not generateenergy (although they can store energy in electric andmagnetic fields).

• They should have zero current flow when no bias isapplied.

• They should be smooth, preferably C∞ continuous.• They should generate reasonable values for unreason-able applied biases (the iterative numerical proceduresused in circuit simulators can generate completelyunrealistic values for x while converging to a solution).

• They should embody the physical symmetries of thedevice being modeled.

In some cases, for example for computational efficiencywhen protecting against extreme bias values, it may notbe reasonable to require C∞ continuity. However, all modelexpressions should be at least C1 continuous, to work prop-erly with the iterative solution methods used by most circuit

3. Exceptions: For models that include self-heating the local temperaturerise above ambient is what is usually calculated and this implicitly has areference value of zero, so is formulated with respect to the ground node;When using SPICE to solve a numerical equation internal referencing tothe ground node, as in Fig. 1, is necessary.

simulators, and note that accurate modeling of kth orderdistortion, e.g., to model the 3rd harmonic intercept pointIP3 which is an important figure of merit for RF poweramplifiers, requires Ck order continuity for all core modelequations.If benchmarks have been defined for models of the type of

device you are modeling, e.g., see [18], [19] for collationsof benchmarks for MOS transistors, make sure your modelpasses all of them.If your model can have high impedance nodes, either

internal to itself or when used in typical circuits, addgmin conductances to appropriate branches, otherwise thesimulator may not be able to properly converge (if thecurrents flowing into a node are a lot less than the sim-ulator KCL convergence tolerance then there is a widerange of values of voltages that control those currentsover which the simulator determines that KCL is sat-isfied, so there is not a well defined solution). Settingto $simparam("gmin",defaultGmin) leverages thegmin-stepping solution algorithms that are implemented inmany simulators.

IV. VERILOG-A BEST PRACTICESThe title of this section is perhaps a little less dictatorialthan it should be: Consider these practices to be mandatoryand do not violate them.Use standard macros and analog functions wherever possi-

ble. Some generally useful macros, and building block analogfunctions for pn−junction modeling, are available at [15].Different simulators use different values for physical con-

stants, so explicitly define the physical constants you use inyour model; NIST [20] collates best known values, from theCommittee on Data for Science and Technology (CODATA).The values for measured constants change over time, so ver-sion your defined constants with a suffix, like

‘define QQ_NIST2004 1.60217653e-19‘define KB_NIST2004 1.3806505e-23

(for the magnitude of the electronic charge and Boltzmann’sconstant, respectively) to indicate their origin. Sinceversion 2.4 of the Verilog-A LRM multiple NIST-versionspecific values for physical constants have been defined, sowe recommend you use those; there are _SPICE, _OLD,_NIST1998, and _NIST2010 versions for each of ‘P_Q(the elementary charge, a.k.a. the magnitude of the elec-tron charge), ‘P_K (the Boltzman constant), ‘P_H (thePlanck constant) and ‘P_EPS0 (the electric constant, a.k.a.the vacuum permittivity). The Verilog-A physical constants‘P_CELSIUS0 (zero Celsius in Kelvin), ‘P_U0 (magneticconstant, a.k.a. the vacuum permeability) and ‘P_C (speedof light in vacuum), are defined (i.e., exact), not derived.However, what are defined and what are derived constantshas changed over time, and may change in the future, so itis best to always use versioned physical constants.Use the mathematical constants that are defined in the

Verilog-A standard constants.vams, e.g., ‘M_PI is π .

386 VOLUME 3, NO. 5, SEPTEMBER 2015

Page 5: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

If you need additional constants, declare them to 17or more digits of precision (double precision arithmeticon most computers is accurate to about 16 decimalplaces).Specify appropriate limits for parameters. These should

restrict the range of usage to where the model has beenverified, and avoid values that can cause numerical evaluationproblems. In particular, parameters that must physically benon-negative (e.g., resistances) should be restricted to therange [0:inf), and those that appear in the denominatorof an expression should be prevented from being zero.Always declare branches and use only those defined

branches as the argument to access functions. For exam-ple, use

branch (a,b) b_cond;I(b_cond) <+ g*V(b_cond);

(where g is conductance) rather than

I(a,b) <+ g*V(a,b);

(the b_ prefix is intended to make it more obvious that thisis a defined branch, but is not mandatory). If you accessa port current, for example to print as part of operatingpoint information, remember to access it via the port accessfunction I(<port>) rather than the branch access func-tion I(port) as the latter effectively shorts the port toground [12], which is likely not what was intended.Formulate models in terms of the proper discipline

(i.e., physical variables); even though you can, do not mapnon-electrical disciplines (e.g., temperature and heat flow,for thermal modeling) into voltage and current. This isbecause the scale of typical values for a discipline maybe different from the electrical discipline, hence the electri-cal discipline convergence criteria may not be appropriate.In Verilog-A different disciplines have different convergencecriteria.Where possible, use current contributions (not voltage con-

tributions) and avoid unnecessary current probes, to minimizethe number of added system unknowns; see [12] and thediscussion in Sections II and III.At first sight it appears that capacitive currents could be

written in one of three ways:

q = f(V(b_cap));I(b_cap) <+ ddt(q);

(i.e., based directly on charge),

C = f(V(b_cap));I(b_cap) <+ C*ddt(V(b_cap));

(i.e., based directly on capacitance), or

C = f(V(b_cap));I(b_cap) <+ ddt(C*V(b_cap));

(i.e., by computing charge as q = C · V), and all of theseforms have been used in one or more existing models.However, only the first of these should be used.

FIGURE 3. Capacitances from dq/dt, C·dV/dt, and d(C·V)/dt.

The last form is wrong if the capacitance is nonlinear:

d

dt[C(V) · V] = C

dV

dt+ V

dC

dt�= C

dV

dt. (8)

Some models, and most experimental data, are in terms ofC(V) so it is tempting to use the last Verilog-A form above;however, this is incorrect.Pedantically the first and second forms are equivalent,

dq(V)

dt= dq

dV

dV

dt= C

dV

dt, (9)

however the second form should not be used. In [12] it wasnoted that such branch-ddt equations do not align with thebasic KCL nodal formulation and cause an extra systemunknown to be added. They also can require special han-dling for harmonic balance analysis, especially for oscillatoranalysis. Modeling a general n-terminal device with no inter-nal nodes requires (n − 1)2 capacitances, cf. n − 1 chargesfor the first form, which increases the model developmenteffort, increases model evaluation time as the derivatives ofeach capacitance have to be evaluated, and makes it moredifficult to guarantee that a model is charge conserving.Fig. 3 shows simulated capacitances for the model

C(V) = 10−6(1+V2) for each of the above capacitance for-mulations (integrated for the q(V) form of course). Clearly,as expected, the third form is wrong, and the first two formsare equivalent. Fig. 4 shows results from transient simu-lations with the three models; the stimulus was a train of1 V amplitude pulses, the current into each model was inte-grated to give charge, and the envelope of the upper andlower extremes of the integrated charge for each pulse cyclewas calculated. Again, clearly the d(C·V)/dt model gets theamplitude wrong, however the net flow of charge into thedevice does integrate to zero over a cycle, as it should. Incontrast, the C·dV/dt form does not properly balance theflow of charge during simulation.The drift over time of the C·dV/dt form in Fig. 4 is a

numerical, not formulation, problem, and can be reduced

VOLUME 3, NO. 5, SEPTEMBER 2015 387

Page 6: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

FIGURE 4. Pulse envelope responses from dq/dt, C·dV/dt, and d(C·V)/dt.The lower limit of first and last forms overlap.

(but not eliminated) by tightening the simulator conver-gence tolerances. Nevertheless, to quote [21] for a 3-terminaldevice:

“The best way to guarantee conservation at thecommon terminal in a model is to use and fit asingle charge function Q(v1, v2). That is, formulatethe model to be charge based.”

If you have nonlinear C(V) data or have a model in termsof C(V), integrate to reformulate as q(V)4.

Avoid using variables that depend on ddt() in condition-als, as this causes an extra branch equation to be created [12].Instead of

Qbd_ddt = ddt(Qbd);Qbs_ddt = ddt(Qbs);if (V(b_ds) >= 0.0) begin

Ibdx_ddt = Qbd_ddt;Ibsx_ddt = Qbs_ddt;

end else beginIbdx_ddt = Qbs_ddt;Ibsx_ddt = Qbd_ddt;

endI(b_bd) <+ Ibdx_ddt;I(b_bs) <+ Ibsx_ddt;

move the ddt() arguments into the conditional blocks

if (V(b_ds) >= 0.0) beginQbdx = Qbd;Qbsx = Qbs;

end else beginQbdx = Qbs;Qbsx = Qbd;

endI(b_bd) <+ ddt(Qbdx);I(b_bs) <+ ddt(Qbsx);

4. In some cases, e.g., MOS transistors with nonuniform laterally channeldoping, it is not possible to qualitatively model some observed devicebehaviors with terminal charges [22], [23]; this can be overcome by usingmulti-section models with internal nodes.

Conditional code based on different physical approxima-tions, analyses, and expressions for different bias valuesshould be avoided, e.g., having separate calculations forMOS transistor operation in weak, moderate, and stronginversion. This is because C∞ continuity is invariably lost atthe boundaries between regions that have different modelingexpressions.Conditionals based on parameter values, to avoid evaluat-

ing parts of model that would have no effect, are obviouslygood for computational efficiency.Conditionals to make evaluations numerically robust

should be used. For example the commonly used smoothingfunction

ylim = 1.0

Aln

(1.0 + eAy

)(10)

can cause an exponential overflow for large positive y. Fory > 0 this should be evaluated as

ylim = y+ 1.0

Aln

(1.0 + e−Ay

)(11)

which is numerically identical to (10) but has no prob-lem with exponential overflow5. Note that even though an“if” condition is used to switch between (10) and (11)the resulting computation is still C∞ continuous. For moreinformation on smoothing functions see [24], [25].As noted previously, if limiting is used to restrict quantities

to a reasonable range, to prevent numerical evaluation prob-lems, then computationally-efficient C1 continuous limitingcan be preferable to computationally-expensive C∞ contin-uous limiting, because by definition the latter affects modelcalculations, and adds computational cost, in the regionwhere it should have no effect. The macro

‘define CLIPB1p0(Tc,T,Tmin,Tmax) \if ((T)<((Tmin)+1.0)) begin \

Tc = (Tmin)+$exp((T)-(Tmin)-1.0); \end else if ((T)>((Tmax)-1.0)) begin \

Tc = (Tmax)-$exp((Tmax)-(T)-1.0); \end else begin \

Tc = (T); \end

is effective for limiting the temperature and avoiding poten-tial numerical evaluation problems in code for temperaturemappings (this macro can be written more succinctly, in asingle line, using the ternary operator ?:, see [15], but thatform does not fit the width of a column). For T within therange Tmin+1.0 to Tmax−1.0 it requires no exponentialevaluation and does not have any effect on model calcula-tions. The macro has continuity of function and derivativeat T=Tmin+1.0 and T=Tmax-1.0.Do not use analysis or event statements [9]. The for-

mer are not defined for all analysis types available in allsimulators, and can lead to inconsistencies between different

5. For computational efficiency, for y > ln(1017)/A (11) should beevaluated as y and for y < ln(10−17)/A (10) evaluated as 0.0.

388 VOLUME 3, NO. 5, SEPTEMBER 2015

Page 7: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

simulation types (e.g., large-signal and small-signal). Eventstatements are intended for behavioral modeling, not compactmodeling.Ensure that each usage of a macro argument in the body of

the macro has parentheses () around the argument. Macroexpansion is lexical, i.e., involves text substitution, it is notlike a function call where arguments are evaluated and passedas individual quantities. Instantiations of macros can haveexpressions for arguments and the order of operator evalua-tions can get messed up if parentheses are not added whenthe arguments are used. For example if the macro

‘define myatan2(y,x) atan(y/x)

is instantiated via

‘myatan2(a+b,c+d)

it will be resolved as

atan(a+b/c+d)

which is most likely not what was intended. The macroshould be defined as

‘define myatan2(y,x) atan((y)/(x))

which will resolve to the desired calculation.Use analog functions in preference to complex, multi-

line macros. They are more readable as they do not needparentheses () around argument usage or continuation \characters at the end of each line. They also allow locallyscoped variables without the need to use named blocks,and avoid inadvertent name collisions with module scopedvariables.In Verilog-A, both potential (voltage) and flow (current)

contributions can be defined for a particular branch, and thecontributions are additive. However, if the type of contribu-tion changes then any accumulated value from the oppositecontribution type is discarded. So be careful not to inadver-tently switch contribution types, e.g., having a static currentcontribution for a branch but then switching to a voltagecontribution for noise.Ensure that all potential numerical problems (division by

zero, square root of a negative number, exponential overflow,etc.) are thought of and protected against. Your model codeshould work robustly for any applied port biases; during iter-ative solution simulators can sometimes generate completelyunrealistic bias values, and your model must handle these.Remember that Verilog-A code involves automatic derivativegeneration, so although

√V is defined for V = 0 its deriva-

tive 0.5/√V is not. This is true for Vn where 0<n<1. The

derivative of the absolute value function |V| is not definedat V = 0 so avoid using absolute values.

Do not try to be efficient by using a conditional that has ahard-coded value for a specific bias value, e.g., zero chargefor zero applied voltage. While the value may be correct itsderivative will not [9].Always write real values as such, i.e., 2.0 and not 2

without the decimal. Not only is it an explicit visual clue as

to the data type, but in Verilog-A 1/2 will be interpreted asan integer divide and will return a value of zero, not 0.5 [10].Make sure your model has no “hidden states” [26].

Initialize all variables (do not code a model so it inheritsvalues from the previous iteration, which Verilog-A stores),and if there are separate sets of interdependent conditionalblocks at different parts of the mode code, make sure allquantities used in all branches of a conditional are definedin all branches of a conditional block that it depends on; thecompiler does not know that your execution logic may besuch that only results from part A of one conditional blockare used in part A of a second conditional block, and onlyresults of part B of the first block are used in part B ofthe second block. Define an initial value for such variablesoutside the conditional blocks, to guarantee that there are nounintentional hidden states. Hidden states cause problemsfor some advanced RF analyses, like periodic steady-state(PSS) analysis, but not for all analyses. So make sure yourun a PSS analysis to test your model, to verify that it hasno hidden states.A model whose potentials and/or flows can take on val-

ues significantly different from those of “normal” simulationvariables can give rise to numerical problems. In some casesthis can be addressed by defining a discipline with appropri-ate absolute tolerance. However, some quantities like mobilecarrier densities can span such large numerical ranges thata small value is, to machine precision, zero compared to alarge value. Transform such quantities so that they have wellscaled numerical values, e.g., use quasi-Fermi levels ratherthan mobile carrier densities, which in effect is a logarithmictransformation.Ensure that large-signal and small-signal models are con-

sistent. This means that the latter must be a linearizedversion of the former (this can be verified, by comparingsmall amplitude harmonic balance simulations to ac analy-sis simulations [19]; they should match). This is automaticin Verilog-A, as long as you avoid conditionals based onanalysis statements. Models defined in terms of fre-quency can be non-causal or have no exact equivalent inthe time domain, so are not allowed in Verilog-A (exceptfor noise).Partition your code into functional blocks:

• initializations dependent on model parameters• initializations dependent on instance parameters• calculations related to static contributions• calculations related to time dependent contributions• contribution statements for static elements• contribution statements for time dependent elements• noise calculations and contributions statements• calculations of quantities for printing operating pointinformation

This is not required by Verilog-A itself, but it makes codemore readable and aligns with code partitioning for effi-cient implementation (although that should be handled bythe compiler). If a model contains repetitive use of the same

VOLUME 3, NO. 5, SEPTEMBER 2015 389

Page 8: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

calculation sequence, e.g., for the surface potential for aMOS transistor model, or has a complex sequence of cal-culations for a part of the model, formulate the calculationas an analog function and place it in a separate file, then‘include that file in the Verilog-A module that definesthe main model. This separates low-level, detailed physicsfrom the high-level model definition and makes the lattereasier to read.An exception to code partitioning is that in “building

block” macros it can be useful to include code for two ormore of the functional types listed in the previous paragraph.Although this means that there are statements of more thanone functional type where the macro is instantiated in thetop-level model code it makes the macro itself, and its usage,simpler and more self-contained. For example, a macro thathandles small and large valued resistances is

‘define myResistor(b_r,r) \

if ((r)>1.0e-3) begin \

I(b_r) <+ V(b_r)/(r); \

I(b_r) <+ white_noise(4.0*‘KB_NIST2004 \

*$temperature/(r)); \

end else begin \

V(b_r) <+ I(b_r)*(r); \

V(b_r) <+ white_noise(4.0*‘KB_NIST2004 \

*$temperature*(r)); \

end

(this macro is overly simplistic, a more practical macro isavailable in [15]). This macro mixes static and noise con-tribution statements, but eliminates the possibility of havinginconsistencies between the two in the top-level model code.Hand partitioning of code into functional blocks is also

not possible in a model that includes switchable depen-dencies. For example, if a model includes self-heating thatcan be turned off or on, for the former any temperaturedependencies do not depend on the biases and can be doneas initialization steps whereas for the latter they must bedone as part of calculations that depend on the systemunknowns. Compilers should automatically handle the parti-tioning; the code should be written to maximize readability(which here should place the temperature dependence codein contribution calculations, not initializations).Some models include ports that are optional to connect

when the model is instantiated. A port is indicated as beingoptional when it is referenced in the module code as anargument to the $port_connected() function. AlthoughVerilog-A no longer includes a null statement, conditionalscan include null branches. So if you do not want to actu-ally take any specific action if a port is connected or not,for example for a local temperature rise port dt that maybe connected to the local temperature rise port of adjacentdevices as part of a multi-device electrothermal simulation,or not connected if a single device self-heating simulationis desired, then include the statement

if ($port_connected(dt));

TABLE 1. Mathematical function.

in the module. This flags dt as being optional to connectin a netlist.Place initialization statements in an analog_initial

block (although not all compilers yet recognize thatdirective).

V. RECOMMENDATIONSThe items detailed in this section are perhaps not as importantto adhere to as strictly as those covered in the previoussection, and there may be good reasons for not following therecommendations in some specific circumstances. However,if you can follow these recommendations you should; violatethem only if you really, really have to.

• Use begin and end around a conditional code blockeven if it consists of just a single statement.

• Where possible, avoid the use of implicit expressions.• Since version 2.3 of the LRM “users are encouraged”to use the IEEE standard 1364-2005 Verilog HDL stylecalls for mathematical functions (see Table 1). If pos-sible do this, however be aware that not all Verilog-Acompilers are fully compliant with that standard yet;if you do use the “old” style functions remember thatlog() is logarithm to the base 10, use ln() for naturallogarithm.

• Protect arguments to functions so they do notcause numerical overflows; this may be done usinglimexp() for exponentials, although exactly how thatfunction limits the exponential is not defined so itcan be preferable to do your own explicit limiting.For example, for a pn−junction current modeled asIS(eV/(nφt) − 1.0), where V is the voltage across thejunction, IS is the saturation current for the diode,n is the ideality factor, and φt is the thermal volt-age, if a limiting current Im is defined then thisoccurs at a voltage Vm = nφt ln(1.0+Im/IS). Thejunction current becomes linear, rather than exponen-tial, for V>Vm if evaluated as IS(eL − 1.0) whereeL = V<Vm?eV/(nφt) : eVm/(nφt)[1.0+(V − Vm)/(nφt)].

• Minimize the use of computationally expensive func-tions, such as $exp(), $ln(), and $pow().

• Use ddx() for calculation of (small-signal) quantitiesfor operating point information printing, but not foractual model calculations.

• If you define your own macros and they use intermedi-ate variables, either embed the calculations in a namedblock and declare any intermediate variables as local to

390 VOLUME 3, NO. 5, SEPTEMBER 2015

Page 9: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

that block, to avoid conflicts with module scoped vari-ables, or if possible define and use an analog functioninstead.

• Use SI units as much as possible. Sometimes using nmor μm for a dimension for a model parameter can beconvenient, and mobility is almost universally specifiedas cm2/(V·s), but minimize such deviations from SIunits. Instance parameters should always be in SI units.

• Run a model through as many different Verilog-A com-pilers as you can, and eliminate any errors and minimizethe number of warnings. Although Verilog-A compil-ers are now more consistent than in the past there arestill some differences; making your model run cleanlythrough multiple compilers will help make it as robustas possible.

Always using begin and end, even around single state-ments, gives consistency of style (you have to use beginand end if there is more than one statement), makes moreobvious the statement that is to be conditionally executed,and avoids the problem of adding a $strobe before orafter a single conditional statement for diagnostic purposesduring model debugging but forgetting to include beginand end around the block.Implicit expressions can be necessary in places, for exam-

ple where you want to have the simulator solve an equationsuch as (3) for you. And it may seem that

I(b_d)<+IS*(exp((V(b_d)-I(b_d)*R)/$vt)-1.0)

(b_d is the branch defined for the diode and IS is a satura-tion current parameter) is an “elegant” way to include seriesresistance in simple diode I(V) model, and it is allowed inVerilog-A. Explicitly adding an internal node, and havingseparate BCRs for the series resistance and for the idealdiode, seems less elegant and introduces an extra systemunknown to be added to x. However, the implicit formula-tion also causes an extra system unknown to be added, thecurrent through the diode, does not align to the I(V) nodalformulation, and can complicate explicit limiting of the expo-nential to aid convergence. Do not use implicit expressionsunless absolutely necessary.Ensure that macros do not reference any module level

variables; this makes them self-contained and avoids anyinadvertent misuse or overwriting of variables. Explicitlydefine all input variables used by a macro as arguments, anddo not modify their value within a macro. As noted previ-ously, if a macro becomes too complex or involves locallyscoped variables, use an analog function instead (where pos-sible, analog functions cannot use access functions or containcontribution statements).

VI. CONVERGENCEAs noted previously, a key feature of Verilog-A is that itdecouples a model definition from simulation algorithms,so in some respects convergence is a simulator, not model,responsibility. Nevertheless, poorly formulated models cansignificantly compromise reliable and efficient convergence,

so a good compact model must be written with convergencein mind. To provide the most reliable convergence a modelshould:

• Have smooth core model equations, preferably C∞continuous but at least C1 continuous.

• Restrict biases, temperature, and internal model quanti-ties to prevent excessive values that cause numericalevaluation problems (keeping in mind that what is“excessive” may depend on device type, differingbetween a power MOS transistor and a FinFET, soshould be definable via model parameters); use at leastC1 continuous limiting.

• Ensure that all expressions that depend on systemunknowns have well defined derivatives, e.g., evalu-ate 3

√x, where x depends on bias, as (4×104/3 −

1016x2/3) · x for |x|<10−6; this modification preservesC1 continuity and avoids division by zero in evaluationof the derivative.

• Linearize exponentials for large argument values.• For large values of system unknowns ensure the signsof derivatives cause Newton’s method to adjust thevalues in the proper direction. If necessary, reformu-late an expression for large or small argument values,e.g., see (10) and (11), to ensure that evaluation ofboth the expression value and its derivative are numer-ically stable and do not involve numerical “noise” oroverflow.

• Judiciously add gmin conductances to branches thatconnect to possible high impedance nodes.

• Avoid excessively large capacitances and excessivelysmall resistances; if the latter must be introducedimplement as V(branch)<+R*I(branch).

Historically, a key to good convergence was the devel-opment of algorithms that intelligently initialize branchvoltages for devices with a near exponential dependenceof currents on voltages, including MOS transistors in weakinversion, and limited (within a model) the change in thosevoltages between Newton iterations [17]. Such limiting isavailable in Verilog-A via the $limit() function. Verilog-A models that follow the recommendations listed abovegenerally converge well in modern simulators without theuse of $limit(). If your model is causing convergencedifficulties consider using $limit(). Be aware that devel-oping robust limiting algorithms takes significant effort andthat the Verilog-A LRM does not specify how, or eventhat, $limit() should be handled by a simulator, onlythat it is a “method to indicate these nonlinearities to thesimulator.”

VII. EFFICIENCY BEST PRACTICESIn general, you should write Verilog-A code to be cleanand readable, and expect the compiler to optimize numer-ical evaluations for run-time efficiency. However, differentcompilers can have different levels of capability for gen-erating computationally-efficient models. To help minimize

VOLUME 3, NO. 5, SEPTEMBER 2015 391

Page 10: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

computation time, irrespective of compiler, the followingrecommendations may be useful.

• If you have to divide by a quantity many times, such asby the thermal voltage φt = kT/q, compute its recip-rocal once and then multiply by the reciprocal instead;this can be computationally more efficient.

• Similarly, use 0.5*x rather than x/2.0.• If you have several calls to $pow() with the same firstargument, replace $pow(x,y) with $exp(y*ln_x),where ln_x=$ln(x) is computed once.

• Evaluate polynomials using Horner’s method

a0+x*(a1+x*(a2+x*(a3+...)))

rather than

a0+a1*x+a2*x*x+a3*x*x*x+...

or, even worse,

a0+a1*x+a2*$pow(x,2)+a3*$pow(x,3)+...

as Horner’s rule is more efficient.Although model developers bear some responsibility for

the computational efficiency of their code, Verilog-A com-pilers have the primary responsibility for minimizing modelevaluation time [9]. Compilers should eliminate commonsub-expressions, automatically collapse nodes where pos-sible, not re-evaluate constant expressions, etc. Verilog-Acompilers have significantly advanced over the past decadeand we hope will continue to do so: improving the codingof one Verilog-A model benefits that model; enhancing aVerilog-A compiler benefits all compact models.

VIII. SOFTWARE BEST PRACTICESAlthough derived from, and an embodiment of, devicephysics, in the end a compact model is code. Compactmodel development should therefore adhere to known goodpractices for software development. Although targeted atMATLAB R© much of the advice in [27] is generic, and itis recommended that you follow the guidelines espousedtherein. Other standard practices are listed here.

• Use source code revision control.• Use versioning for official releases, and never releasetwo different codes under the same revision number, nomatter how small the update or bug-fix.

• Develop regression tests in parallel with model develop-ment, and automatically run and verify regression testresults after any code modification.

• Properly and fully document a model. Sections andimportant equations should be cross-referenced, andconsistent, between the source code and all externaldocumentation.

• Hold code reviews, with experts.• Write legible code.

– use indenting for blocks, using spaces (4 is a goodnumber) and not tabs

– align vertically on the equal signs and contributionoperators in assignments

– make your code simple and transparent, not com-plex and opaque

– use the simplest, and most readable, constructspossible

• Use meaningful names for intermediate variables (nottmp1, tmp2, t0, t1, ...).

NXP Semiconductors have proposed a version numberingsystem that we recommended you follow [28]; this systemhas been adopted by both NEEDS and the CMC. The releaseis V.S.R where V is the version number, S is the subversionnumber, and R is the revision number. The version number isincremented by 1, and the subversion and revision numbersare both reset to zero, for a major model formulation changethat requires new model parameter sets (i.e., is not backwardcompatible). The subversion number is incremented by 1, forthe same version number, and the revision number is reset tozero, when there is a minor model formulation change thatdoes not require new model parameter sets (i.e., is backwardcompatible; minor model features can have been added thatare controlled by extra model parameters, but if the defaultvalues of those parameters “turn off” the added features, sothat simulations with existing parameter sets give the sameresults as the previous release, then no increment in theversion number is necessary). The revision number is incre-mented by 1, for the same version and subversion numbers, ifthere are updates to address issues like convergence, numer-ical evaluation problems, etc. but no changes in the basicmodel equations. There are situations in practice where theline between these alternatives is not perfectly clear; makethe best choice, factoring in that it is desirable to have as fewupdates to the version number as possible. For pre-releaseversions for testing, add further identifiers such as .alpha,.beta, and .beta2 etc. (and of course drop this extrarelease identifier tag for the official release, once testing iscomplete).Regression tests are life-savers: They should test all

aspects of a model, including the influence of all parameters.This can be a daunting task once a model is complete—hencethe recommendation above to develop regression tests inparallel with development of a model. You will have datathat you use to guide and verify development of differentparts of a model; use those data as the basis for regressiontests. Regression tests also are the basis for verifying cor-rect implementation of a model, so they should be deliveredalong with model code.It may be impractical to check every possible combination

of conditional blocks within a model, but every “sub-effect”model should have a test, preferably both stand-alone (i.e.,with other sub-effect models turned off) and in combinationwith other sub-effect models. Tests should exercise at leastdc, small-signal, and noise behavior, over bias, temperature,and geometry. If a model should have symmetry between twoports (such as the source and drain of a MOS transistor) thenthis should be tested. If a model can flip polarity, e.g., foran n−type or p−type structure, then both polarities should

392 VOLUME 3, NO. 5, SEPTEMBER 2015

Page 11: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

FIGURE 5. Circuit for automated testing of polarity and symmetry.

TABLE 2. Controlled source configuration for Fig. 5.

be tested. Fig. 5 and Table 2 show a simulation set upthat enables this to be done automatically; a single set ofreference results, for n polarity with source and drain notflipped, can be used to test simulation of all configurationslisted in Table 26. This is important in practice; since errorsin hand-coded derivatives are eliminated when a model isdefined in Verilog-A some of the most common causes oferrors in models are incorrect handling of polarity flippingor incorrect handling of symmetric pin flipping (Appendix Bshows one way to implement these flips properly).

IX. ENFORCEMENT OF BEST PRACTICESWe have presented do’s and don’ts for writing compact mod-els in Verilog-A, but also noted that previous appeals to adoptbest practices [9]–[14] are often ignored: What is differentthis time?The Nano-Engineered Electronic Device Simulation

(NEEDS) project is making an ongoing effort to createan automatic syntax checker, called VAlint, to “encourage”good Verilog-A practices [29]. VAlint accepts compact mod-els defined in Verilog-A and returns recommendations forimprovements based on the practices detailed here. Thisis done via a web browser, so there is no need for localinstallation of the checker code. The checker is based onADMS [30], [31] and is enhanced to comply with version2.4.0 of the Verilog-A LRM [5]. In addition, it has a “pretty-print” capability that reformats Verilog-A code to conformto good coding standards; e.g., tabs are replaced by spaces,lines are automatically indented, etc.

6. To simplify automated testing of polarity flipping, a model should nothave internal constants that are hard-coded to be different between n−typeand p−type polarities but should have such quantities able to be set viaparameters, with different defaults for n−type and p−type polarities. Somemodels may have different calculations for n−type and p−type polarities;again, rather than being hard-coded based on polarity the selection of whichcode block to execute should be based on a parameter that has a differentdefault for the different polarities.

We hope that in the future a gate for release for a compactmodel is that it cleanly pass the rules that are embedded inVAlint [29].

X. CONCLUSIONVerilog-A has revolutionized compact model developmentand implementation: it reduces model code size to about 10%of that of an equivalent model coded in C, and gets rid of themost common source of implementation errors—incompleteor incorrect derivatives. However, Verilog-A has significantlylowered the bar to becoming a compact model developer,and our experience over the past decade is that many com-pact models written in Verilog-A do not follow known goodsoftware practices, often violate requirements dictated bybasic physics, and ignore previously published “how to”recommendations on writing compact models in Verilog-A.Despite the last of these, we hope that the best practicesespoused here, and embodied in the web-based Verilog-A checker VAlint of [29], along with the general andpn−junction macros and analog function building blocksavailable at [15] and the example R3 model code of [16],can help raise the standard of compact models writtenin Verilog-A.

ACKNOWLEDGMENTThe authors would like to thank M. Kole of NXPSemiconductors for providing insightful comments and rec-ommendations based on an earlier version of this paper.They would also like to thank the anonymous reviewersfor recommendations that helped clarify and improve thecontent.

APPENDIX ACHECK LISTTo help evaluate whether a Verilog-A model adheres tothe best practices detailed above we provide a succinctcheck list.

� is passive, so does not generate energy� has

∑portsQ = 0 and

∑ports I = 0

� all port currents are zero when the applied portvoltages are all the same

� model formulation passes all applicable bench-marks

� limits are defined for all parameters� is referenced to a port, not the ground node� formulated as I(V) and dq(V)/dt (exception: induc-

tors and low value resistors)� avoids implicit expressions� enables reliable simulator convergence� behaves reasonably for unreasonable biases (with

smooth limiting)� does not use abs()� includes a gmin current for high impedance nodes� uses standard macros and analog functions� uses versioned physical constants� uses standard Verilog-A mathematical constants

VOLUME 3, NO. 5, SEPTEMBER 2015 393

Page 12: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

� access functions and contributions only referencenamed branches

� uses the appropriate disciplines (e.g., thermal forself-heating)

� avoids ddt() variables in conditionals� does not use analysis() or event statements� encapsulates use of all macro arguments in ()� uses analog functions for building blocks for

models� does not use integers where values are real� has no hidden states, verified by PSS analysis� had functionally partitioned code� signals optional ports with

$port_connected()� uses begin/end even for one conditional

statement� is written legibly� is under revision control� has a full QA regression test suite defined� has been run through the Verilog-A checker of [29]

APPENDIX BSOURCE-DRAIN AND DEVICE TYPE POLARITY REVERSALFor field-effect transistors, models are usually formulatedfor n−channel devices for VDS≥0. Polarity and terminalflipping are necessary to handle p−channel devices andVDS<0. We have seen problems with the implementationof these operations in some models, and other modelswhere separate codes, with substantial duplication, havebeen generated, which complicates code maintenance.This appendix provides pseudo-code to show one way toimplement these operations, where the parameter type is−1 for n−body and +1 for p−body, and gmin shouldbe derived from the minimum conductance simulatorvariable.inout d, g, s, b;electrical d, g, s, b;

branch (d, s) b_ds;branch (g, s) b_gs;branch (b, s) b_bs;

parameter integer type=-1from[-1:1] exclude 0;

analog begin: myModelreal sVds,Vds,Vgs,Vbs,Ids,Qd,Qg,Qb;

Vds = -type*V(b_ds);Vgs = -type*V(b_gs);Vbs = -type*V(b_bs);if (Vds>=0.0) begin

sVds = 1.0;end else begin

sVds = -1.0;Vgs = Vgs-Vds;

Vbs = Vbs-Vds;Vds = -Vds;

end

Ids = calculations;Qd = calculations;Qg = calculations;Qb = calculations;

if (sVds<0.0) beginQd = -Qd-Qg-Qb;

end

I(b_ds) <+ -type*sVds*Ids;I(b_ds) <+ gmin*V(b_ds); // no flipI(b_ds) <+ ddt(-type*Qd);I(b_gs) <+ ddt(-type*Qg);I(b_bs) <+ ddt(-type*Qb);

end

REFERENCES[1] S. Liu, K. C. Hsu, and P. Subramaniam, “ADMIT-ADVICE modeling

interface tool,” in Proc. IEEE Cust. Integr. Circuits Conf., Rochester,NY, USA, 1988, pp. 6.6.1–6.6.4.

[2] M. Vlach, “Modeling and simulation with Saber,” in Proc. 3rd Annu.ASIC Sem. Exhibit., Rochester, NY, USA, 1990, pp. T11.1–T11.9.

[3] E. McReynolds, “Personal communication,” 1995.[4] E. Christen and K. Bakalar, “VHDL-AMS—A hardware descrip-

tion language for analog and mixed-signal applications,” IEEE Trans.Circuits Syst. II, Analog Digit. Signal Process., vol. 46, no. 10,pp. 1263–1272, Oct. 1999.

[5] Verilog-AMS Language Reference Manual. [Online]. Available:http://www.accellera.org/downloads/ standards/v-ams, accessedJun. 2015.

[6] L. Lemaitre, G. Coram, C. McAndrew, and K. Kundert, “Extensionsto Verilog-A to support compact device modeling,” in Proc. IEEEBehav. Model. Simulat. Workshop, San Jose, CA, USA, Oct. 2003,pp. 134–138.

[7] L. Zhou, B. P. Hu, B. Wan, and C.-J. R. Shi, “Rapid BSIM modelimplementation with VHDL-AMS/Verilog-AMS and MCAST com-pact model compiler,” in Proc. IEEE Int. SOC Conf., Portland, OR,USA, Sep. 2003, pp. 285–286.

[8] G. Coram and M. Ding, “Recent achievements in Verilog-A compactmodeling,” in MOS-AK Workshop, Baltimore, MD, USA, Dec. 2009.

[9] G. Coram, “How to (and how not to) write a compact model inVerilog-A,” in Proc. IEEE Behav. Model. Simulat. Workshop, San Jose,CA, USA, Oct. 2004, pp. 97–106.

[10] G. Coram and C. C. McAndrew, “Verilog-A for compact model-ing: Best practices for high-quality model authoring,” in WorkshopCompact Model. RF, Santa Barbara, CA, USA, Sep. 2005.

[11] G. Coram, “Verilog-A: An introduction for compact modelers,” inMOS-AK Workshop, Montreux, Switzerland, Sep. 2006.

[12] M. Mierzwinski, P. O’Halloran, and B. Troyanovsky, “Developing andreleasing compact models using Verilog-A,” in MOS-AK Workshop,San Francisco, CA, USA, Dec. 2008.

[13] G. Depeyrot and F. Poullet, “Guidelines for Verilog-A compact modelcoding,” in MOS-AK Workshop, Athens, Greece, Sep. 2009.

[14] M. Mierzwinski, P. O’Halloran, and B. Troyanovsky, “Practical consid-erations for developing, debugging, and releasing Verilog-A models,”in MOS-AK Workshop, Baltimore, MD, USA, Dec. 2009.

[15] C. C. McAndrew and G. Coram, General and Junction Primitivesfor Verilog-A Compact Models, nanoHUB, West Lafayette, IN, USA,2015.

[16] C. C. McAndrew, R3, nanoHUB, West Lafayette, IN, USA, 2014.[17] L. W. Nagel, “SPICE2: A computer program to simulate semicon-

ductor circuits,” Dept. Electr. Eng. Comput. Sci., Univ. California,Berkeley, CA, USA, Tech. Rep. ERL-M520, May 1975.

394 VOLUME 3, NO. 5, SEPTEMBER 2015

Page 13: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

[18] X. Li, W. Wu, G. Gildenblat, C. C. McAndrew, andA. J. Scholten, “Benchmark tests for MOSFET compact models,”in Compact Modeling: Principles, Techniques and Applications,G. Gildenblat, Ed., London, U.K.: Springer, 2010, pp. 75–104.

[19] Y. Tsividis and C. McAndrew, Operation and Modeling of the MOSTransistor, 3rd ed. New York, NY, USA: Oxford Univ. Press, 2011.

[20] The NIST Reference on Constants, Units, and Uncertainty.[Online]. Available: http://physics.nist.gov/cuu/Constants/Citations/Search.html, accessed Jun. 2015.

[21] A. Parker, “Getting to the heart of the matter,” IEEE Microw. Mag.,vol. 16, no. 3, pp. 76–86, Apr. 2015.

[22] H. K. Dirks, “Kapazitätskoeffizienten nichtlinearer dissipativer sys-teme,” Habilitation thesis, Fakultät für Elektrotechnik, RWTH AachenUniv., Aachen, Germany, 1998.

[23] A. C. T. Aarts et al., “New fundamental insights into capacitance mod-eling of laterally nonuniform MOS devices,” IEEE Trans. Electron.Dev., vol. 53, no. 2, pp. 270–278, Feb. 2006.

[24] C. C. McAndrew, “Practical modeling for circuit simulation,” IEEEJ. Solid-State Circuits, vol. 33, no. 3, pp. 439–448, Mar. 1998.

[25] C. C. McAndrew, “Useful numerical techniques for compact model-ing,” in Proc. IEEE ICMTS, Cork, Ireland, Apr. 2002, pp. 121–126.

[26] K. Kundert. (Jun. 2015). Hidden State in SpectreRF. [Online].Available: http://www.designers-guide.org/analysis/hidden-state.pdf

[27] R. K. Johnson, The Elements of MATLAB R© Style, New York, NY,USA: Cambridge Univ. Press, 2011.

[28] M. Driessen and D. B. M. Klaassen, “Personal communication,” 2006.[29] Nano-Engineered Electronic Device Simulation Node. [Online].

Available: https://nanohub.org/groups/needs, accessed Jun. 2015.[30] L. Lemaitre, C. C. McAndrew, and S. Hamm, “ADMS-automated

device model synthesizer,” in Proc. IEEE CICC, Orlando, FL, USA,May 2002, pp. 27–30.

[31] ADMS Code. [Online]. Available: http://sourceforge.net/projects/mot-adms/, accessed Jun. 2015.

COLIN C. MCANDREW (S’82–M’84–SM’90–F’04) received the B.E. (Hons.) degree in electricalengineering from Monash University, Melbourne,Australia, in 1978, and the M.A.Sc. and Ph.D.degrees in systems design engineering from theUniversity of Waterloo, Canada, in 1982 and 1984,respectively. From 1987 to 1995, he was at AT&TBell Laboratories, Allentown, PA. Since 1995, hehas been with Freescale Semiconductor (formerlyMotorola Semiconductor Products Sector), Tempe,AZ, where he is currently a Freescale Fellow.

Dr. McAndrew was a recipient of the Best Paper Award from ICMTSin 1993 and 2012 and from CICC in 2002, the BCTM Award in 2005, andthe SRC Mahboob Khan Outstanding Mentor Award in 2007. He was anEditor of the IEEE TRANSACTIONS ON ELECTRON DEVICES from 2001to 2010. He has been an Editor of the IEEE JOURNAL OF THE ELECTRON

DEVICES SOCIETY since 2013. He is or has been on the Technical ProgramCommittee for the IEEE BCTM, ICMTS, CICC, and BMAS conferences.

GEOFFREY J. CORAM (S’97–M’00–SM’09)received the B.A. degree (cum laude) in physicsand mathematics and the master of electrical engi-neering degree from Rice University, Houston,TX, in 1993, and the Ph.D. degree in electricalengineering from the Massachusetts Institute ofTechnology in 2000, with a thesis on thermody-namics and noise modeling in circuits. Since 2000,he has been working with Analog Devices, Inc., ontheir internal circuit simulator. In 2004, he led theAccellera Verilog-AMS subcommittee’s work in

adding compact modeling extensions to that modeling language in LanguageReference Manual version 2.2. He is an active participant of the CompactModeling Coalition, leading the subcommittee on Verilog-A recommendedpractices and reviewing the Verilog-A implementation of essentially everystandard compact model.

KIRAN K. GULLAPALLI received the B.Tech.degree in electrical engineering from the IndianInstitute of Technology, Chennai, India, in 1989,and the M.S. and Ph.D. degrees in electricaland computer engineering and the M.B.A. degreefrom the University of Texas at Austin, in 1991,1994, and 2009, respectively. He joined the CircuitSimulation Group, Motorola in 1994 and has beenworking on various aspects of circuit simulationever since. He worked on Motorola’s in-housecircuit simulator, Mica, with a focus on device

models and RF simulation. In 2002, he joined Synopsys, where he workedon improving the performance of fast-SPICE techniques for the Customsim-XA product. In 2005, he joined the Circuit Simulation Group, Freescale,where he significantly improved the capability of Mica to address thegrowing demand for speed without trading off accuracy. His work hasallowed previously impossible simulations to be routinely performed withoutsacrificing accuracy.

J. ROBERT JONES received the B.S., M.S., andPh.D. degrees in electrical engineering from theUniversity of Virginia in 1990, 1992, and 1996,respectively. He worked at a variety of smalland large companies, including IBM, Multilink,Anadigics, and SiOnyx, as both Manager andTechnical Contributor with a focus on semicon-ductor device development, characterization, andcompact modeling as well as design kit devel-opment and foundry relations for a wide rangeof CMOS, BiCMOS, and compound semicon-

ductor technologies. In 2009, he joined Raytheon and since then hasbeen the Technical Lead for compact modeling activities including activeand passive modeling for GaN, GaAs, Si-based, and heterogeneouslyintegrated technologies as well as custom Verilog-A compact model devel-opment. He is a Senior Principal Engineer with the Department ofMicroelectronics Engineering and Technology, Raytheon Integrated DefenseSystems, Andover, MA, focusing on device modeling and foundry services.He has over 25 technical publications. He has participated in CompactModel Council standardization activities while at Raytheon and IBM, andhas served on the Technical Program Committee for the IEEE CICC andCSICS conferences.

LAURENCE W. NAGEL (M’75–SM’03–F’05–LF’12) received the B.S., M.S., and Ph.D. degreesin electrical engineering and computer sciencefrom the University of California, Berkeley, in1969, 1970, and 1975, respectively. His Ph.D. dis-sertation involved developing the SPICE program.He is currently an Independent Consultant in theSan Francisco Bay Area, and an Adjunct Professorwith Chabot College, Hayward, CA. He worked invarious areas of integrated circuit engineering withBell Laboratories, New Jersey and Pennsylvania,

for 20 years. He then joined Anadigics, New Jersey, for three years, afterwhich he founded Omega Enterprises Consulting, to consult on analog cir-cuit design, circuit simulation, and semiconductor device modeling, andas an expert witness in patent litigation and trade secret misappropriationmatters. Dr. Nagel was an IEEE EDS Distinguished Speaker from 2006 to2008. He is or has been on the Technical Program Committee for the IEEEBCTM, CICC, and BMAS conferences.

VOLUME 3, NO. 5, SEPTEMBER 2015 395

Page 14: Best Practices for Compact Modeling in Verilog-A

MCANDREW et al.: BEST PRACTICES FOR COMPACT MODELING IN VERILOG-A

ANANDA S. ROY received the B.E. degree inelectronics and telecommunications engineeringfrom Jadavpur University, Kolkata, India, in 2001,the M.Tech. degree in microelectronics from theIndian Institute of Technology, Bombay, India, in2003, and the Ph.D. degree in microelectronicsand microsystems from the Swiss Federal Instituteof Technology in Lausanne (EPFL), Lausanne,Switzerland, in 2007. He currently develops com-pact models at Intel Corporation, Hillsboro, OR.He has contributed over 30 publications on com-

pact device modeling. Dr. Roy was a recipient of the G. N. RavenkarAward from the Indian Institute of Technology in 2003 and a Fellowshipfrom EPFL in 2004.

JAIJEET ROYCHOWDHURY (S’85–M’87–SM’06–F’09) received the B.Tech. degree inelectrical engineering from the Indian Institute ofTechnology Kanpur, Kanpur, India, in 1987, andthe Ph.D. degree in electrical engineering andcomputer science (EECS) from the Universityof California, Berkeley, (UC Berkeley) in 1993.He is currently a Professor of EECS with UCBerkeley. From 1993 to 1995, he was with AT&TBell Laboratories, Allentown, PA. From 1995 to2000, he was with the Communication Sciences

Research Division, Bell Laboratories, Murray Hill, NJ. From 2000 to 2001,he was with CeLight, Inc., Silver Spring, MD. From 2001 to 2008, hewas with the Department of Electrical and Computer Engineering and theDigital Technology Center, University of Minnesota, Minneapolis. He wasan Officer of CANDE. His current research interests include the analysis,simulation, and design of electronic, biological, and mixed-domainsystems. He has authored or co-authored seven best or distinguishedpapers at ASP-DAC, DAC, and ICCAD. He was cited for extraordinaryachievement by Bell Laboratories in 1996. Dr. Roychowdhury was anIEEE Circuits and Systems Society Distinguished Lecturer from 2003 to2005 and served as the Program Chair of the IEEE CANDE and BMASWorkshops in 2005. He has served on the Technical Program Committeeof ICCAD, DAC, DATE, ASP-DAC, and other EDA conferences, theExecutive Committee of ICCAD, and the Nominations and AppointmentsCommittee of CEDA.

ANDRIES J. SCHOLTEN received the M.Sc.and Ph.D. degrees in experimental physicsfrom Utrecht University, The Netherlands, in1991 and 1995, respectively. In 1996, hejoined Philips Research Laboratories (now NXPSemiconductors), Eindhoven, The Netherlands,where he has worked on compact MOS modelingfor circuit simulation, with a focus on the modelingof thermal noise and non-quasi-static effects. Hehas contributed to the development and industrial-ization of well-known compact MOSFET models

such as MOS model 9, MOS model 11, and the world-standard PSP model.His current research is directed toward RF CMOS and HBT reliability andreliability simulation.

GEERT D. J. SMIT received the M.Sc. degrees inexperimental physics and mathematics from theUniversity of Utrecht, The Netherlands, in 1998and 1999, respectively, and the Ph.D. degree inexperimental physics from the Delft Universityof Technology, The Netherlands, in 2004. Hejoined Philips Research Laboratories, Eindhoven,The Netherlands, in 2004, and moved to NXPSemiconductors when it was founded in 2006. Hehas worked on several aspects of compact model-ing, with a focus on CMOS and related devices.

He is one of the key developers of the CMC-standardized PSP MOSFETmodel.

XUFENG WANG (S’08–M’15) received the B.S.,M.S., and Ph.D. degrees in electrical engineer-ing from Purdue University, West Lafayette,IN, in 2008, 2010, and 2014, respectively. Hiswork at Purdue was part of the network forphotovoltaic technology and focused on elec-tronic transport and optics coupling in high-performance thin-film solar cells. In 2015, hebecame the Technical Director of the Nano-Engineered Electronic Devices Simulation Center,Purdue University.

SADAYUKI YOSHITOMI received the B.E., M.E,and Ph.D. degrees from Yokohama NationalUniversity, Yokohama, Japan, in 1988, 1990, and1993, respectively. In 1993, he joined the Researchand Development Center, Toshiba Corporation,Kawasaki, Japan. He was engaged in the researchand development of RF-BiCMOS device tech-nologies. Since he moved to Mixed Signal ICDesign Division in 1998, he has been work-ing on the development of process design kitsfor RFCMOS technologies and compact model-

ing standardization. In 2014, he was a member of 76 GHz AutomobileRadar Licensing Committee of the Japanese Ministry of Internal Affairsand Communications.

396 VOLUME 3, NO. 5, SEPTEMBER 2015