problems - skolan för datavetenskap och kommunikation | · pdf fileanswers to the...

25
Course 2D1213, Lab work 1: Becoming comfortable with MATLAB Michael Hanke 25th August 2003 Part I Problems 1 General Description And Aims Numerical methods are one of the basic tools in engineering practice, especially in electrical engineering. Therefore, any engineer must be fluent in using and developing numerical tools for solving their own problems. The present course is tailored exactly to meet these requirements: numerical methods and ideas are presented in lectures; but their efficient use is taught through hands-on exercises. It is the practical activities which are decisive for passing the course. The first lab work is intended for you to become fluent in developing programs and algorithms in MATLAB, as well as using and modifying given routines. MAT- LAB is a problem solving environment tailored to fast prototyping of numerical algorithms. You will write a program for the DC and AC analysis of RLC circuits. Your second task is the use and enhancement of a simple electrical circuit simula- tor which is written in MATLAB. It resembles the well-known SPICE simulator only for passive (linear) RLC-networks. 2 Preparations 1. Repeat the basics of MATLAB. This includes the repetition of the material presented during the first year. Moreover, you should become comfortable with starting the MATLAB user interface (MATLAB console, MATLAB editor, MATLAB debugger). 1

Upload: buicong

Post on 13-Mar-2018

219 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

Course 2D1213, Lab work 1:Becoming comfortable with MATLAB

Michael Hanke

25th August 2003

Part I

Problems

1 General Description And Aims

Numerical methods are one of the basic tools in engineering practice, especiallyin electrical engineering. Therefore, any engineer must be fluent in using anddeveloping numerical tools for solving their own problems. The present courseis tailored exactly to meet these requirements: numerical methods and ideas arepresented in lectures; but their efficient use is taught through hands-on exercises.It is the practical activities which are decisive for passing the course.

The first lab work is intended for you to become fluent in developing programsand algorithms in MATLAB, as well as using and modifying given routines. MAT-LAB is a problem solving environment tailored to fast prototyping of numericalalgorithms. You will write a program for the DC and AC analysis of RLC circuits.Your second task is the use and enhancement of a simple electrical circuit simula-tor which is written in MATLAB. It resembles the well-known SPICE simulatoronly for passive (linear) RLC-networks.

2 Preparations

1. Repeat the basics of MATLAB. This includes the repetition of the materialpresented during the first year. Moreover, you should become comfortablewith starting the MATLAB user interface (MATLAB console, MATLABeditor, MATLAB debugger).

1

Page 2: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

The choice of the operating system is up to you, although I am mainly us-ing Linux. I propose to use MATLAB from the KTHCD. All MATLABversions 5.x and 6.x should work.

2. Read the basic ideas of the Modified Nodal Analysis (MNA). Nodal analysiswill be presented in the course “Analog Electronics”. The facts necessaryfor this lab are summarized in Part 2. The jω-method is introduced in thecourse “Complex Numbers”.

3. Understand the SPICE language used for describing electric circuits. De-tails are given in the course “Analog Electronics”. The subset implementedby me is presented in Part 2.

3 Problems

3.1 DC Analysis

1. Write a MATLAB function dc_anal which implements the MNA analy-sis!

It is convenient to use the following calling sequence:

[e,iV] = dc_anal(AR,AV,AI,R,V,I).

The meaning of the parameters is as follows:

• AR, AV, AI are the incidence matrices of the resistive, voltage source,and current source branches, respectively.

• R, V, I are the vectors of the values of the resistors, voltage sources,and current sources, respectively.

• e is the vector of node voltages (excluding the ground node), and iVis the vector of currents through the voltage source branches.

Let n+1 be the number of nodes in the circuit. Then number the nodes from1 to n + 1 with the ground node being node number n + 1. If the number ofresistive branches is bR, the number of voltage source branches bV , and thenumber of current source branches bI , then the matrices and vectors havethe following dimensions

2

Page 3: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

Figure 1: Circuit for the DC analysis problem

matrix dimensionAR n × bR

AV n × bV

AI n × bI

R bR

V bV

I bI

e niV bV

What happens if some of the branches are missing? Assume that our circuitdoes not include current sources. Then, bI = 0. Hence, the matrix AI hasdimension n×0. In the MATLAB language, this represents a (dimensioned)empty matrix. This is completely consistent with MATLAB’s interpretationof matrices. Similarly, the vector I has dimension 0 × 1.

Hint: You may have use of the following MATLAB commands: diag,zeros, \ (backslash; solution of linear systems of equations), : (colon;extracting sub-matrices and sub-vectors).

2. Consider the electric circuit given in Figure 1. The given quantities are thevoltage of the source E, as well as the values of the resistors Rs, Ra, Rb, Rc, Rd

and Rg. The problem consists of computing the current through the resistorRg as a function of Rg.

3

Page 4: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

(a) The values of the elements are as follows:

E = 10V, Rs = 0.001Ω, Ra = 100Ω, Rb = Rc = Rd = 10Ω.

The resistor Rg shall vary between 10Ω and 200Ω.

(b) Derive the necessary incidence matrices and vectors describing thecircuit and compute the current Ig through Rg for sufficiently manyvalues of that resistor by your function dc_anal. Plot a graph pre-senting Ig as a function of Rg. Do not forget to add correct denotationsto the axis (values, units etc.)!

Hint: Have a look at the following MATLAB commands: plot,semilogx, semilogy, title, xaxis, yaxis.

(c) Write a spicy input file in order to solve problem (b)! Run it andcompare the results to those of your implementation!

3. What is the resistance of a cube?We consider a circuit which is constructed as follows:

(a) Draw the lattice of a cube (that is, all 12 edges).

(b) Every edge is replaced by a resistor with a resistance of 1Ω.

(c) The nodes of the circuit are represented by the corners of the cube.

How large is the resistance between two corners which are located diago-nally opposite to each other in the cube lattice?

3.2 AC Analysis

In this problem, we are interested in the computation of transfer curves of RLCcircuits. The method of choice is the jω-method. This approach makes the analy-sis mathematically similar to the DC case.

1. Write a MATLAB function ac_anal which implements the jω-method!

The appropriate calling sequence for the function might be:

[e,iV] = ac_anal(AR,AC,AL,AV,AI,R,C,L,V,I,omega).

2. In earlier days of the music business, the black vinyl disks played the role ofwhat the CD is today. For mechanical reasons, the low-frequency electricalsignal was not modulated linearly to mechanical vibrations on the vinylrecord. Instead, higher frequencies were amplified while lower frequencies

4

Page 5: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

Figure 2: RIAA equalization circuit

were damped. Waves at 1 kHz were neither amplified nor damped. Theexact amplification curve (RIAA curve) is defined by a reference circuit.The opposite effect in a phono player is called RIAA equalization. Therespective circuit is sketched in Figure 2. The physical parameters are asfollows:

R1 = 1Ω, R1A = 212.8mΩ, C1 = 3.528mF, C1A = 352.8µF.

The circuit is valid for a frequency f of E1 between 20Hz and 20kHz. Forsimplicity choose an effective voltage of 1V.

Compute and plot the equalization curve! The x-axis shall be the frequencyf , while the y-axis is the quotient of the effective voltage v5(f) at node 5and v5(1kHz) (measured in dB)! Do not forget to add correct denotationsto the plot!

3.3 Optional Problems

If you are interested in writing a more advanced version of spicy, you couldconsider the following tasks. I propose to contact me in advance before you try tosolve these problems.

1. The present implementation of dc_anal discards all capacitors and induc-tors. This is obviously physically wrong. What would be the correct way ofhandling these elements? Modify the function dc_anal in this respect!

5

Page 6: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

2. Implement the ac_anal program in spicy!

3. The present implementation does not allow for controlled sources, i.e., sourceswhose gain depends on branch voltages or branch currents somewhere elsein the circuit. Therefore, transformers and active elements are not possible.Try to implement such elements! This problem is nontrivial.

4. Other enhancements are welcome!

4 Evaluation

1. The lab can be done in groups with at most two members.

2. At the end of period 1, a lab report has to be handed in. It shall include theanswers to the problems as well as all of your code (such that I can run it onmy machine). Due date for the report: Monday, October 27, 2003.

3. In order to pass the lab assignment, the DC analysis problem must be solved.

4. In order to obtain a mark of 5, the AC analysis problem must be solved.

5. If one of the optional tasks is solved successfully, bonus credits will beearned for use in later parts of the course.

Part II

ExplanationsThe following explanations base on material taken from:

1. Caren Tischendorf: Coupled systems of differential algebraic and partialdifferential equations in circuit and device simulation. Berlin: HumboldtUniv., Habilitationsschrift 2003

2. Paul W. Tuinenga: SPICE: A guide to circuit simulation and analysis usingPSpice. Englewood Cliffs: Prentice Hall 1995 (3rd edition)

6

Page 7: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

Figure 3: A sample circuit: Schematic of a low-pass filter

5 The Modified Nodal Analysis (MNA)

The numerical simulation of electric networks is closely related to the networkmodeling. A well established approach is the description of the network by agraph with branches and nodes. Each branch represents an electric element whoseterminals are coupled together at the nodes. (See the simple example in Figure 3.)The simplest network elements are fully described by a relation between a singlebranch current and the respective branch voltage (e.g., resistors, capacitors, induc-tors, (independent) voltage and current sources). The describing current-voltagerelations are called characteristic equations.

The state of the network at any given time is now completely described byall branch voltages, branch currents, and node potentials. The node potentialsare only defined up to a constant. Therefore, one node is assigned the voltage(potential) 0V. This node is called the mass (or, ground) node. The other nodepotentials are given with respect to this reference node (this way being unique).

In order to complete the network model, the topology of the elements (i.e.,their mutual interconnections) has to be taken into account. Assuming the electri-cal connections between circuit elements to be ideally conducting and the nodes

7

Page 8: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

to be ideal, the topology can be described by Kirchhoff’s laws.Thus, the network modeling consists of two steps:

1. Describe the network elements.

2. Apply Kirchhoff’s laws.

5.1 Network elements

In order to make the presentation as simple as possible, I will only consider un-controlled, two-terminal elements. Moreover, the elements will be assumed to belinear. The respective branch voltage will be denoted by v while the branch cur-rent is i. Note that both can be positive or negative depending on the orientationof the branch.

5.1.1 Passive Elements

In network modeling one distinguishes three different types of passive elements:resistors, capacitors, and inductors. Its characteristic equations can be describedas follows:

Resistors limit, or resist, the flow of electrical current, following the law v = Ri.R is the resistance value. Sometimes this relation is written as i = Gvwhere G = 1/R is called conductivity.

Capacitors store energy in an electrostatic field following the law q = Cv whereq is the electric charge. C is the capacitance value. The voltage-currentcharacteristics is given by i = d

dtq = C dv

dt(if C is constant).

Inductors store energy in an electromagnetic field following the law Φ = Liwhere Φ is the magnetic flux. L is the self-inductance value. The voltage-current characteristic is given by v = d

dtΦ = L di

dt(if L is constant).

5.1.2 Independent Sources

Again for the sake of simplicity, independent sources will be the only active ele-ments we consider. The generalization to controlled elements is straightforward.

Voltage source The current-voltage characteristic is given by v = E with E be-ing the strength of the source. Note that v does not depend on the branchcurrent i.

Current source The current-voltage characteristic is given by i = I with I beingthe strength of the source. Note that i does not depend on the branch voltagev.

8

Page 9: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

5.2 Kirchhoff’s Laws

The electrical behavior of the network is completely described by Kirchhoff’slaws.

Considering one node with branch currents i1, . . . , il entering this node wemay describe Kirchhoff’s current law (KCL) as i1 + · · · + il = 0, that means, thesum of all branch currents entering a node equals zero.

If we consider a loop with the branch voltages v1, . . . , vm, then we may for-mulate Kirchhoff’s voltage law (KVL) as v1 + · · ·+ vm = 0, that means, the sumof all branch voltages in a loop equals zero.

In a practical network there are very many nodes and loops. In order to de-scribe the topology of the circuit, one must write down KCL and KVL for eachof them. It becomes obvious that ones needs a systematic way to derive all theseequations for a given network. Fortunately, there is a very elegant descriptionof all these individual equations. The magic happens if one uses the (reduced)incidence matrix A of the circuit.

Assume that we have a circuit with n + 1 nodes and b branches. Number thenodes and branches accordingly. The ground node is omitted here. For everybranch, define an orientation, that is, one node of the branch is assumed to be the“starting” node, the other one is the “end” node. The reduced1 incidence matrixdescribes which nodes belong to which branch:

aij =

1, if branch j has start node i−1, if branch j has end node i

0, else.

It is now convenient to collect all branch currents into one vector2 i = [i1, i2, . . . , ib]′.

Then, the compact notation of KCL is

Ai = 0.

The incidence matrix allows, additionally, a simple description of the relation be-tween node potentials and branch voltages of the network. If v = [v1, v2, . . . , vb]

is the vector of all branch voltages and e = [e1, e2, . . . , en]′ denotes the vector ofall node potentials (excluding the reference (mass) node), then the relation

v = A′e

is satisfied.1The notion “reduced” comes from the fact that the ground node is left out.2By convention, all our vectors are assumed to be column vectors. In order to come as close as

possible to the MATLAB notation, I will use the apostrophe for denoting the transpose of a matrixor vector: AT

= A′.

9

Page 10: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

5.3 Network Analysis

As introduced previously, let i be the vector of all branch currents, v be the vectorof all branch voltages, and e be the vector of all node potentials. The first stepconsists of writing down the network equations and the characteristic equations ofall network elements as described in the previous subsections. This gives rise to asystem of dimension 2b+n for the unknowns i, v, e. The approach leading to thissystem is called sparse tableau analysis.

The so-called modified nodal analysis (MNA) requires a much smaller num-ber of unknowns. In this case, one replaces the branch currents of all currentdefining elements (conductors, resistors3, current sources) by their characteristicequation, and all branch voltages by node voltages. For a convenient descriptionof this approach, it is appropriate to decompose the incidence matrix accordingto the element types of their branches. By definition of the incidence matrix, ev-ery column of A corresponds to one branch. We assume that the branches areenumerated in the following order: first all resistive branches, then all capacitivebranches, then all inductive branches, then all voltage source branches, and finallyall current source branches. Then A can be decomposed into block form:

A = [AR, AC , AL, AV , AI ],

where the index stands for resistive, capacitive, inductive, voltage source, and cur-rent source branches, respectively. Using the characteristic equations as indicatedabove, we obtain the following system:

AC

d

dtCA′

Ce + ARGA′

Re + ALiL + AV iV = −AII,

d

dtLiL − A′

Le = 0,

A′

V e = V.

Here, we have used the following denotations:

• iV is the vector of all branch currents through voltage sources.

• iL is the vector of all branch currents of inductive branches.

• I is the vector of the values of all current sources.

• V is the vector of the values of all voltage sources.

• C is the diagonal matrix containing all capacities.

3via conductance formulation!

10

Page 11: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

• G is the diagonal matrix containing all conductances (inverses of the resis-tances).

• L is the diagonal matrix containing all inductivities.

The unknowns in the classical MNA system are the node voltages e, the currentsthrough voltage sources iV , and the currents through inductors iL. Thus, the num-ber of unknowns has reduced drastically. In matrix notation, the system can bewritten down as

ACCA′

C 0 00 L 00 0 0

d

dt

eiLiV

+

ARGA′

R AL AV

−A′

L 0 0A′

V 0 0

eiLiV

=

−AII0V

.

This system consists of differential equations (for e4 and iL) and additional equa-tions which do not contain any derivatives of the unknown functions. Such asystem is called a differential-algebraic equation. It will play a key role not onlyin circuit simulation.

5.3.1 DC Analysis

When performing a DC analysis we assume that the network consists only of re-sistors, current and voltage sources. Capacitors and inductors have to be replacedby its DC equivalents: a capacitor is a perfect insulator while an inductor is a per-fect conductor. In order to simplify the notation assume that the network does notcontain any capacitors or inductors. Therefore, the matrix in front of the deriva-tives is a zero matrix. Hence the MNA equations reduce to

[

ARGA′

R AV

A′

V 0

] [

eiV

]

=

[

−AIIV

]

.

This is a linear system of equations. Under some assumptions on the networktopology, the system matrix is nonsingular such that the system has a unique so-lution.

Example Consider the electrical circuit given in Figure 4. According to our con-vention, we will count the resistive branches first, then the voltage source branch,and finally the current source branch. Let branch number i be the branch throughresistor Ri, for i = 1, 2, 3, 4. Branch 5 is the voltage source, branch 6 consists ofthe current source. This provides us with the incidence matrices

4More precisely, since ACCA′

Cis a singular matrix, not all node voltages are really determined

by differential equations. This will need some more detailed investigation during the course.

11

Page 12: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

Figure 4: A resistive network

AR =

+1 +1 0 00 −1 +1 +10 0 −1 0

, AV =

00

+1

, AI =

0−1

0

,

Let for simplicity all resistances being equal to 1Ω. The resulting system is then

2 −1 0 0−1 3 −1 0

0 −1 2 10 0 1 0

e1

e2

e3

iV

=

0−1

09

.

5.3.2 AC Analysis

For the purposes of this project, we will assume that all sources are harmonic andhave the same frequency f , i.e., they follow the relations

v(t) = V sin ωt, i(t) = I sin ωt

where ω = 2πf . Instead of using the amplitudes it is common to work further onwith the effective values

V = V /√

2, I = I/√

2.

12

Page 13: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

Under these assumptions it is very convenient to use complex quantities. In-stead of the trigonometric functions, complex exponentials are applied. By usingMoivre’s law, the time-dependent voltages and currents can be identified as thereal (or imaginary) part of an exponential ejωt scaled by V and I , respectively.Since

d

dtejωt = jωejωt,

the differential law describing the capacitors and resistors, respectively, reduce tosimple algebraic relations

v = Zi,

which formally resemble Ohm’s law for resistors. The complex equivalent of theresistance is called impedance. The systematic use of this equivalence in analyz-ing RLC networks is called jω-method.

The value of the impedance is easily computed from the technical parameters:

Resistor Z = R

Capacitor Z = 1

jωC

Inductor Z = jωL

Let us now come back to the MNA equations. Inductive and capacitive branchescan now be handled in the same way as resistive branches where the impedancereplaces the resistance. The inverses of the impedances Z are called admittancesY . Let YR, YC, YL denote diagonal matrices which contain the admittances of theresistive, capacitive and inductive branches, respectively.5 Then it holds

[

ARYRA′

R + ACYCA′

C + ALYLA′

L AV

A′

V 0

] [

eiV

]

=

[

−AIIV

]

.

The vector of voltages and currents contain now the effective values.

Example Consider the RLC network of Figure 5. Let the branches be orderedaccording to our convention. Then we obtain the following incidence matrices:

AR =

+1 00 +10 0

, AC =

+1−1

0

, AL =

0+1−1

, AV =

00

+1

, AI =

0−1

0

,

and

ZR =

[

1/R1 00 1/R4

]

, ZC = [jωC] , ZL = [1/(jωL)] .

5In particular, YR = G.

13

Page 14: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

Figure 5: A simple RLC circuit

6 Description of Electrical Circuits in SPICE

This section contains a quick “getting started” guide for those features of SPICEwhich are implemented in the quick-and-dirty implementation using MATLAB.The resulting program is called spicy. Its detailed description can be found inthe next section.6

6.1 A Small Circuit

The best way to learn a circuit simulator id to “do” simulations. Running anysimulation requires several basic accomplishments. It requires that you

• create the input file, or “circuit file,”

• run the simulator, without error(s),

• find where the output went, and

• inspect the output.

6The following subsections are almost verbatim taken from the above mentioned PSpice intro-duction.

14

Page 15: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

Figure 6: Schematic for a small circuit example

Naturally, you would start with a small circuit that you know, by inspection, willwork. We will use the circuit shown in Figure 6 for starting out. The circuit filefor simulating this circuit is

* Resistor divider circuitVIN 1 0 3.0voltR1 1 2 1.0ohmR2 2 0 2.0ohm.DC

How to run the simulation will be described in detail in section 7. You need toprepare the circuit file using any text editor (for instance, MATLAB’s own editor).Since spicy is implemented as a MATLAB function, the output is returned tothe user via the output argument list, or printed and plotted.

6.2 The Input File

Now to describe, and explain, the circuit file. spicy always expects the first lineof the circuit file to be a title line. You can leave it blank, but circuit descriptioncannot start until the second line of the file. After the first line, the circuit file maybe in almost any order.

All of the circuit elements, or devices, in the circuit file are connected (in thesense that you would solder their leads together) by circuit nodes. You may thinkof these nodes as connecting wires, or lines, in a circuit schematic. In SPICE2these nodes are positive integers, including 0 (zero), which is reserved to mean“ground.” spicy does not require that you will use integers (any text stringwill do) but 0 is still “ground.” Every circuit must have a grounded node, as a

15

Page 16: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

Form meaning

ELEMENTMono-spaced type indicates a keyword that you mustuse. This type is also used in the text for examples andfragments of spicy input and output files.

placeholder Italic type indicates an item that you must supply, suchas a name or a value.

[[option]] Items inside double square-brackets are optional.

repeat...A horizontal ellipsis (...) following an item indicates thatmore items having the same form may appear.

this|thatCurly brackets and a vertical bar indicate a choice be-tween two or more items. You must choose one of theitems.

Table 1: Syntax description for spicy

reference, and every other node in the circuit file must have a DC current path toground. This is one of the requirements of the algorithms.

Along with requiring a ground node, spicy also requires that all terminals beconnected to at least one other terminal. This is a precaution against danglingwires.

The circuit file for our example uses only two-terminal devices — a voltagesource and the resistors. A separate line is used to describe each element in thecircuit. The basic syntax is

name startnode endnode value

where the syntax forms used in the text are described in Table 1.Note that there are only two-terminal devices in spicy. The device value is a

number, either decimal or floating point, that describes the size of the device. Youwill see later that there are a variety of ways to express the same value, includinga metric suffix. After the value you may include a unit such as volt or ohm,for your own use; spicy actually ignores these (to the extent that they are notconfused with one of the metric suffixes).

Any line may be a comment line by starting it with “*” in the first column.This allows you to document your circuit files for others, unfamiliar with thecircuit file, or for yourself when, after some time, you too will be unfamiliar withthe circuit file. Blank lines are ignored; use them to separate sections of yourcircuit file.

spicy allows you to insert comments on any line by starting the commentwith a semicolon. Everything on the line after the semicolon is ignored; for ex-ample:

Rbias 2 3 45 ; this is crazy!

16

Page 17: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

A second class of lines in the circuit file are command lines. They start with a fullstop in the first position and contain the command and optional parameters to thatcommand. In the example above, the command is

.DC

and indicates that a DC analysis for the given device had to be made. There canbe any number of commands in the circuit file. They will be carried out in orderafter the complete circuit file had been read.

6.3 The Output

The output of spicy is controlled by commands. There are two of them avail-able: .PRINT and .PLOT. Not very surprising, they do what they seem to. Letus add an output statement to our simple circuit example:

* Resistor divider circuitVIN 1 0 3.0voltR1 1 2 1.0ohmR2 2 0 2.0ohm.DC.PRINT V(1) V(2) I(VIN)

The last statement requires that the node voltages at the nodes 1 and 2 as well asthe current through the voltage source are to be printed. The following excerptcontains the sample output:

*** SPICY results displayed ***-------------------------------

* Resistor divider circuit

Results for variable node 10 3

Results for variable node 20 2

Results for variable voltage source VIN0 -1

Done!

17

Page 18: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

We can infer immediately that the node voltages at nodes 1 and 2 are 3V and 2V,respectively. Moreover, the current through the voltage source is -1A. The minussign appears due to technical convention: External to a voltage source, currentis assumed to be positive if it is floating from “+” to “-”. Therefore, inside thecurrent source, the current is counter-current.

In front of the voltages and currents, an index appears. In the present casewhere we do not make any parameter study, this index amounts to 0. In case ofparameter studies, the value of the respective parameter is given. This is the reasonwhy it does not make sense to provide an example for the .PLOT command. Thiscommand is intended for displaying results of parameter studies.

6.4 Component Values

All quantities, or values, in spicy may be expressed as decimal or floating pointvalues traditionally used by computer programs. The decimal numbers should befamiliar; for example:

3.14 -13.7 .0045

Floating point values scale a decimal number by a power of ten, where the letter“E” (for “exponent”) separates the decimal number from the start of the integerexponent, so that .0045 can be written 4.5E-3, which means 4.5 × 10−3. In-stead of the letter “E”, the letter “D” can be used.

Also, spicy lets you use a metric-like suffix to express a value. These suf-fixes multiply the number they follow by a power of ten, except for MIL. Usingthe suffix notation allows values written into the circuit file to look like values ona circuit schematic. This is a great convenience that removes a source for mostsimulation errors: using wrong component values.

The following are the power-of-ten suffix values, used by spicy, along withthe metric prefixes and scale factors they represent:

F femto- 10−15

P pico- 10−12

N nano- 10−9

U micro- 10−6

M milli- 10−3

K kilo- 103

MEG mega- 106

G giga- 109

T tera- 1012

MIL (0.001”) 25.4 × 10−6

18

Page 19: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

where the last suffix, MIL, provides an English-to-metric conversion of integratedcircuit device sizes.

Using the exponential and suffix notation lets you express the same value manyways; for example:

1050000 1.05E6 1.05MEG 1.05E3K .00105G

all represent the same value to spicy.Note that spicy does nowhere distinguish between capital letters and small

letters. They are taken to be identical. This feature requires the use of MEG fordenoting mega-.

Other letters that are not suffixes may be used with any number, but these areignored. Thus you may write

10 10volts 10ohms 10oHmS

to make your circuit file easier to understand without changing the meaning of thevalue. Moreover, once a valid suffix is read by spicy, the remaining letters areignored. You may also write

10pF 10picoamps 10picoseconds

These will all represent the value 10 × 10−12.

6.5 Passive Devices

The passive devices are resistors, capacitors, and inductors.7 You can specifythese devices merely by using the appropriate letter as the first letter of the devicename:

Rxxx for resistorLxxx for inductorCxxx for capacitor

The xxx represent any other letters or numbers you want to use to finish the nameof the device. Note that spicy does not distinguish between small and capitalletters.

To specify the device in the circuit file we include the name of the device, howit is connected into the circuit, and its value. spicy uses the basic electrical unitsfor voltage (volts) and current (amps) and uses the basic electrical units for devicevalues: ohms, farads, and henries. Here are some example devices:

7As before, we assume ideal elements. Real hardware devices must be replaced by sub-circuitsfor the sake of network modeling.

19

Page 20: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

R12 5 2 15k is a 15-kiloohm resistorCin N1 3 1.8u is a 1.8-microfarad capacitorLres 7 6 10m is a 10-millihenry inductor

6.6 Independent Sources

To simulate your circuits you will need some way to tell spicywhat is “exciting”or supplying electrical power to the circuit. For this we use independent sourcesthat supply a fixed voltage level or current flow. We specify these sources in a waythat is similar to the passive devices described earlier: name, connecting nodes,value. As you might have guessed

Vxxx is a voltage source, andIxxx is a current source.

Remember, spicy uses the basic electrical units for values so the following exam-ples are easy to understand:

VIN 3 0 1.2K is a 1.2-kilovolt sourceI4 12 2 15m is a 15.milliamp source.

In the context of the jω-method in the AC analysis, the values given are effectivevalues.

A voltage source is like a battery. Using the positive current convention, cur-rent flows out from the positive terminal (first node), through the circuit, and theninto the negative terminal (second node). This is the conventional current flowtaught to students. But why, in our first example, did spicy calculate the supplycurrent as a negative value? Because whenever you ask spicy to print the valueof a current through a device, “through” means into the first terminal and out ofthe second terminal. In this case the current was flowing out of the positive (first)terminal, so the current has a negative value.

A current source provides a fixed value of current to the circuit. However, itscurrent flows (again using positive current) into the positive terminal (first node),through the source, and then out of the negative terminal (second node). This isthe opposite direction of the voltage source, but is consistent with reporting thecurrent through the device.

6.7 Commands

After having described the circuit, some calculations can be done. These includesimple DC and AC analysis as well as parametric studies. The results of these cal-culations can be printed or plotted by using appropriate commands. The detaileddescription of all commands follows below.

20

Page 21: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

6.7.1 Commands For Calculations

DC Analysis The general syntax of the DC analysis command is

.DC [[ element range ]]

If the optional argument is not given, the node voltages and currents throughvoltage sources are computed.8

If the optional argument is used, a parameter study is carried out. element in-dicates the name of a resistor9 whose value is changes according to the descriptionin range. More precisely, for each value in range, the value of element is set tothis value and the circuit equations are solved. The result is a matrix containingthe node voltages and currents through voltage sources for each value in range.

The syntax of range is given as follows:

LIN | DEC | OCT points value1 value2

value1 and value2 are the first and the last value of the range. The numberof values between these two limiting values (and including them) is given by thepositive integer points. By the first token you select how the intermediate valuesare distributed between the limits:

LIN The intermediate values are linearly distributed, i.e., the distance betweenneighboring values is constant.

DEC Logarithmic sweep. The value is incremented logarithmically, by decades,from value1 to value2, and points is the number of steps per decade.

OCT Logarithmic sweep. The value is incremented logarithmically, by octaves,from value1 to value2, and points is the number of steps per octave.

AC Analysis The syntax of the AC analysis command is

.AC [[ range ]]

The range argument contains the value of ω for which the circuit shall beevaluated. If it is left blank, the frequency is set to 1 kHz, hence ω = 2π ∗ 1000.The syntax and meaning of the range argument is the same as for the DC analysiscommand.

8These are exactly the unknowns used in the MNA!9In a DC analysis it doesn’t make sense to vary values of capacitors or inductors. Changing

the values of independent sources is presently not implemented.

21

Page 22: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

6.7.2 Output Commands

You can print or plot the results of the DC and AC analyzes. According to theproperties of the MNA, node voltages and currents through voltage sources areavailable. The syntax of both commands can be summarized as follows:

.PRINT quantity...

.PLOT quantity...

The quantity argument selects the specific voltage or current to be printed/plotted.If you want to print/plot a node voltage, you should use the syntax V(node).Here, node is the name of the node. Similarly, the current through the voltagesource source can be selected by using the quantity description I(source).

If your previous computation was not a parameter study (that is, the rangeargument was not used), there is exactly one voltage or current for each node andvoltage source branch, respectively, available. It is therefore not very useful toplot such a result. If you made a parameter study instead, the selected quantitiesfor all parameter values are printed or plotted thus giving rise to a real curve.

It remains to resolve a problem which is connected with the properties ofMNA. There are only some currents available for output. Nevertheless, the stateof the network can be derived completely from the computed quantities. In partic-ular, we might be interested in knowing the value of the current through a resistivebranch. It is not immediately available. But there is a simple trick: put a voltagesource with value of 0V in series with the resistor! This voltage source does notchange anything in the network. On the other hand, we introduced a device wherethe current is available. According to KCL, the current through the voltage sourceis the same as that through the resistor. Hence, voltage sources with 0V are ourampere meters.

7 Using The MATLAB Implementation

The easiest way of using spicy consists of writing an input file describing thecircuit and calling spicy. The results will be printed or plotted according to thecommands contained in the input file. If you are interested in making use of thecapabilities of spicy in your own programs, some of the internal subroutines(“functions” in the MATLAB language) may be of interest for you. These includethe functions parse, incidence, dc_anal.

spicy This is the main module for creating a circuit simulation. It reads a circuitfile and executes the commands in the file.

22

Page 23: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

Syntax ok = spicy(circuit_file)

Example ok = spicy(’test.cir’)

Description The parameter circuit_file gives the file name of theinput file. The result is 1 if the file could be correctly executed. Oth-erwise, the result is 0.

parse This function reads a circuit file, parses its contents, and generates a num-ber of data structures which can be conveniently used for carrying out thecircuit simulation.

Syntax [title,restab,captab,indtab,voltab,curtab,cmds,nnodes,intdata] = parse(circuit_file)

Example [title,restab,captab,indtab,voltab,curtab,cmds,nnodes,intdata] = parse(’test.cir’)

Description The following table contains a short description of the param-eters:

parameter type explanation

circuit_file string name of the input filetitle string first line of the input filerestab matrix description of resistive branchescaptab matrix description of capacitive

branchesindtab matrix description of inductive

branchesvoltab matrix description of voltage source

branchescurtab matrix description of current source

branchescmds structure description of the command se-

quencennodes integer number of nodes n disregarding

the ground nodeintdata structure internal data, contains the ele-

ment names

The value of the title argument can be used for title printing, forexample. The description of the branches in the xxxtab variables isa table with three columns. Each row describes one branch: the firstcolumn contains the start node, the second one the end node, the thirdone the value. For that purpose, parse has enumerated all nodesconsecutively with the exception of the ground node.

23

Page 24: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

The cmds data structure contains an easily interpretable descriptionof the command sequence contained in the circuit file. A descriptionof the contents of cmds and intdata can be obtained on demand.

incidence This function computes the incidence matrix based on the branchdescriptions contained in the xxxtab tables which are output from parse.

Syntax Ai = incidence(element_tab,nodes)

Example AR = incidence(restab,nnodes)

Description The input arguments are provided by parse. The output is theincidence matrix.

dc_anal Makes a DC analysis of a circuit by only considering resistors, voltagesources and current sources. The value of a single resistor can be changedtemporarily to a certain value.

Syntax x = dc_anal(nnodes,restab,voltab,curtab,ires,value)

Example vi = dc_anal(nnodes,restab,voltab,curtab,0,0)

Description The meaning of the parameters is contained in the followingtable:

parameter type explanation

nnodes integer number of nodesrestab matrix description of resistive branchesvoltab matrix description of voltage source

branchescurtab matrix description of current source

branchesires integer index of the resistor whose value

should be changedvalue real new value for that resistorx vector vector of node voltages and volt-

age branch currents

The nnodes, restab, voltab, and curtab arguments are takenfrom parse. The (internal) resistor number ires is matched byparse and contained in the cmds structure. If ires is 0, no changesare taking place. value contains the new value for that resistor. Notethat this resistor value is not changed outside of dc_anal.

24

Page 25: Problems - Skolan för datavetenskap och kommunikation | · PDF fileanswers to the problems as well as all of your code ... or resist, the flow of electrical current, following the

The output argument contains the results of the MNA analysis. Thetop part x(1:nnodes) are the node voltages e while the remainingpart x(nnodes+1:end) are the voltage branch currents iV .

25