# Control Systems/Sampled Data Systems

## Ideal Sampler

In this chapter, we are going to introduce the ideal sampler and the
**Star Transform**. First, we need to introduce (or review) the
**Geometric Series** infinite sum. The results of this sum will be very
useful in calculating the Star Transform, later.

Consider a sampler device that operates as follows: every *T* seconds,
the sampler reads the current value of the input signal at that exact
moment. The sampler then holds that value on the output for *T* seconds,
before taking the next sample. We have a generic input to this system,
*f(t)*, and our sampled output will be denoted *f\*(t)*. We can then
show the following relationship between the two signals:

$$f^{\,*}(t)=f(0)\big(\mathrm{u}(t\,-\,0)\,-\,\mathrm{u}(t\,-\,T)\big)\,+\,f(T)\big(\mathrm{u}(t\,-\,T)\,-\,\mathrm{u}(t\,-\,2T)\big)\,+\;\cdots\;+\,f(nT)\big(\mathrm{u}(t\,-\,nT)\,-\,\mathrm{u}(t\,-\,(n\,+\,1)T)\big)\,+\;\cdots$$

Note that the value of *f^\*^* at time *t* = 1.5 *T* is the same as at
time *t = T*. This relationship works for any fractional value.

Taking the Laplace Transform of this infinite sequence will yield us
with a special result called the **Star Transform**. The Star Transform
is also occasionally called the \"Starred Transform\" in some texts.

## Geometric Series

Before we talk about the Star Transform or even the Z-Transform, it is
useful for us to review the mathematical background behind solving
infinite series. Specifically, because of the nature of these
transforms, we are going to look at methods to solve for the sum of a
**geometric series**.

A geometric series is a sum of values with increasing exponents, as
such:

$$\sum_{k=0}^{n} ar^k = ar^0+ar^1+ar^2+ar^3+\cdots+ar^n \,$$

In the equation above, notice that each term in the series has a
coefficient value, a. We can optionally factor out this coefficient, if
the resulting equation is easier to work with:

$$a \sum_{k=0}^{n} r^k = a \left(r^0+r^1+r^2+r^3+\cdots+r^n \,\right)$$

Once we have an infinite series in either of these formats, we can
conveniently solve for the total sum of this series using the following
equation:

$$a \sum_{k=0}^{n} r^k = a\frac{1-r^{n+1}}{1-r}$$

Let\'s say that we start our series off at a number that isn\'t zero.
Let\'s say for instance that we start our series off at *n = 1* or *n =
100*. Let\'s see:

$$\sum_{k=m}^{n} ar^k = ar^m+ar^{m+1}+ar^{m+2}+ar^{m+3}+\cdots+ar^n \,$$

We can generalize the sum to this series as follows:

$$\sum_{k=m}^n ar^k=\frac{a(r^m-r^{n+1})}{1-r}$$

With that result out of the way, now we need to worry about making this
series converge. In the above sum, we know that n is approaching
infinity (because this is an *infinite sum*). Therefore, any term that
contains the variable n is a matter of worry when we are trying to make
this series converge. If we examine the above equation, we see that
there is one term in the entire result with an *n* in it, and from that,
we can set a fundamental inequality to govern the geometric series.

$$r^{n+1} < \infty$$

To satisfy this equation, we must satisfy the following condition:

$$r \le 1$$ {{-}} Therefore, we come to the final result: **The
geometric series converges if and only if the value of *r* is less than
one.**

## The Star Transform

The **Star Transform** is defined as such:

$$F^*(s) = \mathcal{L}^*[f(t)] = \sum_{k = 0}^\infty f(kT)e^{-skT}$$

The Star Transform depends on the sampling time *T* and is different for
a single signal depending on the frequency at which the signal is
sampled. Since the Star Transform is defined as an infinite series, it
is important to note that some inputs to the Star Transform will not
converge, and therefore some functions do not have a valid Star
Transform. Also, it is important to note that the Star Transform may
only be valid under a particular **region of convergence**. We will
cover this topic more when we discuss the Z-transform.

### Star ↔ Laplace

The Laplace Transform and the Star Transform are clearly related,
because we obtained the Star Transform by using the Laplace Transform on
a time-domain signal. However, the method to convert between the two
results can be a slightly difficult one. To find the Star Transform of a
Laplace function, we must take the residues of the Laplace equation, as
such:

$$X^*(s) = \sum \bigg[ \text{residues of } X(\lambda)\frac{1}{1-e^{-T(s-\lambda)}}\bigg]_{\text{at poles of E}(\lambda)}$$

This math is advanced for most readers, so we can also use an alternate
method, as follows:

$$X^*(s)=\frac{1}{T}\sum_{n=-\infty}^\infty X(s+jm\omega_s)+\frac{x(0)}{2}$$

Neither one of these methods are particularly easy, however, and
therefore we will not discuss the relationship between the Laplace
transform and the Star Transform any more than is absolutely necessary
in this book. Suffice it to say, however, that the Laplace transform and
the Star Transform *are related* mathematically.

### Star + Laplace

In some systems, we may have components that are both continuous and
discrete in nature. For instance, if our feedback loop consists of an
Analog-To-Digital converter, followed by a computer (for processing),
and then a Digital-To-Analog converter. In this case, the computer is
acting on a digital signal, but the rest of the system is acting on
continuous signals. Star transforms can interact with Laplace transforms
in some of the following ways:

### Convergence of the Star Transform

The Star Transform is defined as being an infinite series, so it is
critically important that the series converge (not reach infinity), or
else the result will be nonsensical. Since the Star Transform is a
geometic series (for many input signals), we can use geometric series
analysis to show whether the series converges, and even under what
particular conditions the series converges. The restrictions on the star
transform that allow it to converge are known as the **region of
convergence** (ROC) of the transform. Typically a transform must be
accompanied by the explicit mention of the ROC.

## The Z-Transform

Let us say now that we have a discrete data set that is sampled at
regular intervals. We can call this set *x\[n\]*:

`x[n] = [ x[0] x[1] x[2] x[3] x[4] ... ]`

we can utilize a special transform, called the Z-transform, to make
dealing with this set more easy:

$$X(z) = \mathcal{Z}\left\{x[n]\right\} = \sum_{n = -\infty}^\infty x[n] z^{-n}$$

Like the Star Transform the Z Transform is defined as an infinite series
and therefore we need to worry about convergence. In fact, there are a
number of instances that have identical Z-Transforms, but different
regions of convergence (ROC). Therefore, when talking about the Z
transform, you must include the ROC, or you are missing valuable
information.

{{-}}

### Z Transfer Functions

Like the Laplace Transform, in the Z-domain we can use the input-output
relationship of the system to define a **transfer function**.

![](Z_Block.svg "Z_Block.svg"){width="400"}

The transfer function in the Z domain operates exactly the same as the
transfer function in the S Domain:

$$H(z) = \frac{Y(z)}{X(z)}$$

$$\mathcal{Z}\{h[n]\} = H(z)$$

Similarly, the value *h\[n\]* which represents the response of the
digital system is known as the **impulse response** of the system. It is
important to note, however, that the definition of an \"impulse\" is
different in the analog and digital domains.

### Inverse Z Transform

The **inverse Z Transform** is defined by the following path integral:

$$x[n] = Z^{-1} \{X(z) \}= \frac{1}{2 \pi j} \oint_{C} X(z) z^{n-1} dz \$$

Where *C* is a counterclockwise closed path encircling the origin and
entirely in the region of convergence (ROC). The contour or path, *C*,
must encircle all of the poles of *X(z)*.

This math is relatively advanced compared to some other material in this
book, and therefore little or no further attention will be paid to
solving the inverse Z-Transform in this manner. Z transform pairs are
heavily tabulated in reference texts, so many readers can consider that
to be the primary method of solving for inverse Z transforms. There are
a number of Z-transform pairs available in table form in **The
Appendix**.

### Final Value Theorem

Like the Laplace Transform, the Z Transform also has an associated final
value theorem:

$$\lim_{ n\to \infty} x[n] = \lim_{z \to 1} (z - 1) X(z)$$

This equation can be used to find the steady-state response of a system,
and also to calculate the steady-state error of the system.

## Star ↔ Z

The Z transform is related to the Star transform though the following
change of variables:

$$z = e^{sT}$$

Notice that in the Z domain, we don\'t maintain any information on the
sampling period, so converting to the Z domain from a Star Transformed
signal loses that information. When converting back to the star domain
however, the value for *T* can be re-insterted into the equation, if it
is still available.

Also of some importance is the fact that the Z transform is bilinear,
while the Star Transform is unilinear. This means that we can only
convert between the two transforms if the sampled signal is zero for all
values of *n \< 0*.

Because the two transforms are so closely related, it can be said that
the Z transform is simply a notational convenience for the Star
Transform. With that said, this book could easily use the Star Transform
for all problems, and ignore the added burden of Z transform notation
entirely. A common example of this is Richard Hamming\'s book
\"Numerical Methods for Scientists and Engineers\" which uses the
Fourier Transform for all problems, considering the Laplace, Star, and
Z-Transforms to be merely notational conveniences. However, the Control
Systems wikibook is under the impression that the correct utilization of
different transforms can make problems more easy to solve, and we will
therefore use a multi-transform approach.

### Z plane

*z* is a complex variable with a real part and an imaginary part. In
other words, we can define *z* as such:

$$z = \operatorname{Re}(z) + j\operatorname{Im}(z)$$

Since *z* can be broken down into two independent components, it often
makes sense to graph the variable *z* on the **Z-plane**. In the
Z-plane, the horizontal axis represents the real part of *z*, and the
vertical axis represents the magnitude of the imaginary part of *z*.

Notice also that if we define *z* in terms of the star-transform
relation:

$$z = e^{sT}$$

we can separate out *s* into real and imaginary parts:

$$s = \sigma + j\omega$$

We can plug this into our equation for *z*:

$$z = e^{(\sigma + j\omega)T} = e^{\sigma T} e^{j\omega T}$$

Through **Euler\'s formula**, we can separate out the complex
exponential as such:

$$z = e^{\sigma T} (\cos(\omega T) + j\sin(\omega T))$$

If we define two new variables, *M* and φ:

$$M = e^{\sigma T}$$

$$\phi = \omega T$$

We can write *z* in terms of *M* and φ. Notice that it is Euler\'s
equation:

$$z = M\cos(\phi) + jM\sin(\phi)$$

Which is clearly a polar representation of *z*, with the magnitude of
the polar function (*M*) based on the real-part of *s*, and the angle of
the polar function (φ) is based on the imaginary part of *s*.

### Region of Convergence

To best teach the region of convergance (ROC) for the Z-transform, we
will do a quick example.

{1-r}

`       = 1 \frac{1 - ((e^2z)^{-1})^{n+1}}{1 - (e^2z)^{-1}}``</math>`{=html}

Again, we know that to make this series converge, we need to make the r
value less than 1:

$$|(e^2z)^{-1}| = \left|\frac{1}{e^2z}\right| \le 1$$

$$|e^2z| \ge 1$$

And finally we obtain the region of convergance for this Z-transform:

$$|z| \ge \frac{1}{e^2}$$}}

### Laplace ↔ Z

There are no easy, direct ways to convert between the Laplace transform
and the Z transform directly. Nearly all methods of conversions
reproduce some aspects of the original equation faithfully, and
incorrectly reproduce other aspects. For some of the main mapping
techniques between the two, see the Z Transform Mappings
Appendix.

However, there are some topics that we need to discuss. First and
foremost, conversions between the Laplace domain and the Z domain *are
not linear*, this leads to some of the following problems:

1.  $\mathcal{L}[G(z)H(z)] \ne G(s)H(s)$
2.  $\mathcal{Z}[G(s)H(s)] \ne G(z)H(z)$

This means that when we combine two functions in one domain
multiplicatively, we must find a combined transform in the other domain.
Here is how we denote this combined transform:

$$\mathcal{Z}[G(s)H(s)] = \overline{GH}(z)$$

Notice that we use a horizontal bar over top of the multiplied
functions, to denote that we took the transform of the product, not of
the individual pieces. However, if we have a system that incorporates a
sampler, we can show a simple result. If we have the following format:

$$Y(s) = X^*(s)H(s)$$

Then we can put everything in terms of the Star Transform:

$$Y^*(s) = X^*(s)H^*(s)$$

and once we are in the star domain, we can do a direct change of
variables to reach the Z domain:

$$Y^*(s) = X^*(s)H^*(s) \to Y(z) = X(z)H(z)$$

Note that we can only make this equivalence relationship if the system
incorporates an ideal sampler, and therefore one of the multiplicative
terms is in the star domain.

### Example

## Z ↔ Fourier

By substituting variables, we can relate the Star transform to the
Fourier Transform as well:

$$e^{sT} = e^{j \omega}$$

$$e^{(\sigma + j \omega)T} = e^{j \omega}$$

If we assume that *T = 1*, we can relate the two equations together by
setting the real part of *s* to zero. Notice that the relationship
between the Laplace and Fourier transforms is mirrored here, where the
Fourier transform is the Laplace transform with no real-part to the
transform variable.

There are a number of discrete-time variants to the Fourier transform as
well, which are not discussed in this book. For more information about
these variants, see Digital Signal
Processing.

## Reconstruction

Some of the easiest reconstruction circuits are called \"Holding
circuits\". Once a signal has been transformed using the Star Transform
(passed through an ideal sampler), the signal must be \"reconstructed\"
using one of these hold systems (or an equivalent) before it can be
analyzed in a Laplace-domain system.

If we have a sampled signal denoted by the Star Transform $X^*(s)$, we
want to **reconstruct** that signal into a continuous-time waveform, so
that we can manipulate it using Laplace-transform techniques.

Let\'s say that we have the sampled input signal, a reconstruction
circuit denoted *G(s)*, and an output denoted with the Laplace-transform
variable *Y(s)*. We can show the relationship as follows:

$$Y(s) = X^*(s)G(s)$$

Reconstruction circuits then, are physical devices that we can use to
convert a digital, sampled signal into a continuous-time domain, so that
we can take the Laplace transform of the output signal.

### Zero order Hold

!Zero-Order Hold impulse
response

A **zero-order hold** circuit is a circuit that essentially inverts the
sampling process: The value of the sampled signal at time *t* is held on
the output for *T* time. The output waveform of a zero-order hold
circuit therefore looks like a staircase approximation to the original
waveform.

The transfer function for a zero-order hold circuit, in the Laplace
domain, is written as such:

$$G_{h0} = \frac{1 - e^{-Ts}}{s}$$

The Zero-order hold is the simplest reconstruction circuit, and (like
the rest of the circuits on this page) assumes zero processing delay in
converting between digital to analog.

center\|framed\|A continuous input signal (gray) and the sampled signal
with a zero-order hold (red)

### First Order Hold

!Impulse response of a first-order
hold.

The zero-order hold creates a step output waveform, but this isn\'t
always the best way to reconstruct the circuit. Instead, the
**First-Order Hold** circuit takes the derivative of the waveform at the
time *t*, and uses that derivative to make a guess as to where the
output waveform is going to be at time *(t + T)*. The first-order hold
circuit then \"draws a line\" from the current position to the expected
future position, as the output of the waveform.

$$G_{h1} = \frac{1 + Ts}{T} \left[ \frac{1 - e^{-Ts}}{s}\right]^2$$

Keep in mind, however, that the next value of the signal will probably
not be the same as the expected value of the next data point, and
therefore the first-order hold may have a number of discontinuities.

center\|framed\|An input signal (grey) and the first-order hold circuit
output (red)

### Fractional Order Hold

The Zero-Order hold outputs the current value onto the output, and keeps
it level throughout the entire bit time. The first-order hold uses the
function derivative to predict the next value, and produces a series of
ramp outputs to produce a fluctuating waveform. Sometimes however,
neither of these solutions are desired, and therefore we have a
compromise: **Fractional-Order Hold**. Fractional order hold acts like a
mixture of the other two holding circuits, and takes a fractional number
*k* as an argument. Notice that *k* must be between 0 and 1 for this
circuit to work correctly.

$$G_{hk} = (1 - ke^{-Ts}) \frac{1 - e^{-Ts}}{s} + \frac {k}{Ts^2} (1 - e^{-Ts})^2$$

This circuit is more complicated than either of the other hold circuits,
but sometimes added complexity is worth it if we get better performance
from our reconstruction circuit.

### Other Reconstruction Circuits

!Impulse response to a linear-approximation
circuit.

Another type of circuit that can be used is a **linear approximation**
circuit.

center\|framed\|An input signal (grey) and the output signal through a
linear approximation
circuit

## Further reading

-   Hamming, Richard. \"Numerical Methods for Scientists and Engineers\"

-   Digital Signal Processing/Z
    Transform
-   Complex Analysis/Residue
    Theory
-   Analog and Digital
    Conversion


# Control Systems/Z Transform Mappings

## Z Transform Mappings

There are a number of different mappings that can be used to convert a
system from the complex Laplace domain into the Z-Domain. None of these
mappings are perfect, and every mapping requires a specific starting
condition, and focuses on a specific aspect to reproduce faithfully. One
such mapping that has already been discussed is the **bilinear
transform**, which, along with prewarping, can faithfully map the
various regions in the s-plane into the corresponding regions in the
z-plane. We will discuss some other potential mappings in this chapter,
and we will discuss the pros and cons of each.

## Bilinear Transform

The Bilinear transform converts from the Z-domain to the complex W
domain. The W domain is not the same as the Laplace domain, although
there are some similarities. Here are some of the similarities between
the Laplace domain and the W domain:

1.  Stable poles are in the Left-Half Plane
2.  Unstable poles are in the right-half plane
3.  Marginally stable poles are on the vertical, imaginary axis

With that said, the bilinear transform can be defined as follows:

$$w = \frac{2}{T} \frac{z - 1}{z + 1}$$

$$z = \frac{1+(Tw/2)}{1-(Tw/2)}$$

Graphically, we can show that the bilinear transform operates as
follows:

![](Bilinear_Transform_Unwarped2.svg "Bilinear_Transform_Unwarped2.svg"){width="400"}

### Prewarping

The W domain is not the same as the Laplace domain, but if we employ the
process of **prewarping** before we take the bilinear transform, we can
make our results match more closely to the desired Laplace Domain
representation.

Using prewarping, we can show the effect of the bilinear transform
graphically:

![](Bilinear_Transform_Mapping.svg "Bilinear_Transform_Mapping.svg"){width="400"}

The shape of the graph before and after prewarping is the same as it is
without prewarping. However, the destination domain is the S-domain, not
the W-domain.

## Matched Z-Transform

If we have a function in the laplace domain that has been decomposed
using partial fraction expansion, we generally have an equation in the
form:

$$Y(s) = \frac{A}{s + \alpha_1} + \frac{B}{s + \alpha_2} + \frac{C}{s + \alpha_3} + ...$$

And once we are in this form, we can make a direct conversion between
the s and z planes using the following mapping:

$$s + \alpha = 1 - z^{-1}e^{-\alpha T}$$

Pro:A good direct mapping in terms of s and a single coefficient\
Con:requires the Laplace-domain function be decomposed using partial fraction expansion.

## Simpson\'s Rule

$$s = \frac{3}{T} \frac{z^2-1}{z^2+4z^1+1}$$

CON:Essentially multiplies the order of the transfer function by a factor of 2. This makes things difficult when you are trying to physically implement the system. It has been shown that this transform produces unstable roots (outside of unit unit circle).

## (w, v) Transform

Given the following system:

$$Y(s) = G(s, z, z^\alpha)X(s)$$

Then:

$$w = \frac{2}{T} \frac{z-1}{z+1}$$

$$v(\alpha) = 1 - \alpha(1 - z^{-1}) + \frac{\alpha(\alpha - 1)}{z}(1-z^{-1})^2$$

And:

$$Y(z) = G(w, z, v(\alpha))\left[X(z) - \frac{x(0)}{1 + z^{-1}}\right]$$

Pro:Directly maps a function in terms of z and s, into a function in terms of only z.\
Con:Requires a function that is already in terms of s, z and α.

## Z-Forms


# Control Systems/Physical Models

## Physical Models

This page will serve as a refresher for various different engineering
disciplines on how physical devices are modeled. Models will be
displayed in both time-domain and Laplace-domain input/output
characteristics. The only information that is going to be displayed here
will be the ones that are contributed by knowledgeable contributors.

## Electrical Systems

:   {\|class=\"wikitable\"

!Component \|\| Time-Domain \|\| Laplace \|\| Fourier \|- !Resistor \| R
\|\| R \|\| R \|- !Capacitor \| $i = C\frac{dv}{dt}$ \|\|
$G(s) = \frac{1}{sC}$ \|\| $G(j\omega) = \frac{1}{j\omega C}$ \|-
!Inductor \| $v = L\frac{di}{dt}$ \|\| $G(s) = sL$ \|\|
$G(j\omega) = j\omega L$ \|}

## Mechanical Systems

## Civil/Construction Systems

## Chemical Systems


# Control Systems/Transforms Appendix

## Laplace Transform

When we talk about the Laplace transform, we are actually talking about
the version of the Laplace transform known as the **unilinear Laplace
Transform**. The other version, the **Bilinear Laplace Transform** (not
related to the Bilinear Transform, below) is not used in this book.

The Laplace Transform is defined as:

$$F(s)
        = \mathcal{L}[f(t)]
        = \int_{-\infty}^\infty x(t)e^{-st}dt$$

And the Inverse Laplace Transform is defined as:

$$f(t)
        = \mathcal{L}^{-1} \left\{F(s)\right\}
        = \frac{1}{2\pi j} \int_{\sigma-j\infty}^{\sigma+j\infty} X(s)e^{st}ds$$

### Table of Laplace Transforms

This is a table of common Laplace Transforms.

:
### Properties of the Laplace Transform

This is a table of the most important properties of the laplace
transform.

:
### Convergence of the Laplace Integral

### Properties of the Laplace Transform

## Fourier Transform

The Fourier Transform is used to break a time-domain signal into its
frequency domain components. The Fourier Transform is very closely
related to the Laplace Transform, and is only used in place of the
Laplace transform when the system is being analyzed in a frequency
context.

The Fourier Transform is defined as:

$$F(j\omega)
        = \mathcal{F}[f(t)]
        = \int_0^\infty f(t) e^{-j\omega t} dt$$

And the Inverse Fourier Transform is defined as:

$$f(t)
        = \mathcal{F}^{-1}\left\{F(j\omega)\right\}
        = \frac{1}{2\pi}\int_{-\infty}^\infty F(j\omega) e^{-j\omega t} d\omega$$

### Table of Fourier Transforms

This is a table of common fourier transforms.

:
### Table of Fourier Transform Properties

This is a table of common properties of the fourier transform.

:
### Convergence of the Fourier Integral

### Properties of the Fourier Transform

## Z-Transform

The Z-transform is used primarily to convert discrete data sets into a
continuous representation. The Z-transform is notationally very similar
to the star transform, except that the Z transform does not take
explicit account for the sampling period. The Z transform has a number
of uses in the field of digital signal processing, and the study of
discrete signals in general, and is useful because Z-transform results
are extensively tabulated, whereas star-transform results are not.

The Z Transform is defined as:

$$X(z)
        = \mathcal{Z}[x[n]]
        = \sum_{n = -\infty}^\infty x[n] z^{-n}$$

### Inverse Z Transform

The inverse Z Transform is a highly complex transformation, and might be
inaccessible to students without enough background in calculus. However,
students who are familiar with such integrals are encouraged to perform
some inverse Z transform calculations, to verify that the formula
produces the tabulated results.

$$x[n] = \frac{1}{2 \pi j} \oint_C X(z) z^{n-1} dz$$

### Z-Transform Tables

## Modified Z-Transform

The Modified Z-Transform is similar to the Z-transform, except that the
modified version allows for the system to be subjected to any arbitrary
delay, by design. The Modified Z-Transform is very useful when talking
about digital systems for which the processing time of the system is not
negligible. For instance, a slow computer system can be modeled as being
an instantaneous system with an output delay.

The modified Z transform is based off the delayed Z transform:

$$X(z, m)
        = X(z, \Delta)|_{\Delta \to 1 - m}
        = \mathcal{Z} \left\{ X(s)e^{-\Delta T s} \right\}|_{\Delta \to 1 - m}$$

## Star Transform

The Star Transform is a discrete transform that has similarities between
the Z transform and the Laplace Transform. In fact, the Star Transform
can be said to be nearly analogous to the Z transform, except that the
Star transform explicitly accounts for the sampling time of the sampler.

The Star Transform is defined as:

$$F^*(s)
        = \mathcal{L}^*[f(t)]
        = \sum_{k = 0}^\infty f(kT)e^{-skT}$$

Star transform pairs can be obtained by plugging $z = e^{sT}$ into the
Z-transform pairs, above.

## Bilinear Transform

The bilinear transform is used to convert an equation in the Z domain
into the arbitrary W domain, with the following properties:

1.  roots inside the unit circle in the Z-domain will be mapped to roots
    on the left-half of the W plane.
2.  roots outside the unit circle in the Z-domain will be mapped to
    roots on the right-half of the W plane
3.  roots on the unit circle in the Z-domain will be mapped onto the
    vertical axis in the W domain.

The bilinear transform can therefore be used to convert a Z-domain
equation into a form that can be analyzed using the Routh-Hurwitz
criteria. However, it is important to note that the W-domain is not the
same as the complex Laplace S-domain. To make the output of the bilinear
transform equal to the S-domain, the signal must be prewarped, to
account for the non-linear nature of the bilinear transform.

The Bilinear transform can also be used to convert an S-domain system
into the Z domain. Again, the input system must be prewarped prior to
applying the bilinear transform, or else the results will not be
correct.

The Bilinear transform is governed by the following variable
transformations:

$$z = \frac{(T/2) + w}{(T/2) - w},\quad w = \frac{2}{T} \frac{z - 1}{z + 1}$$

Where T is the sampling time of the discrete signal.

Frequencies in the w domain are related to frequencies in the s domain
through the following relationship:

$$\omega_w = \frac{2}{T} \tan \left( \frac{ \omega_s T}{2} \right)$$

This relationship is called the **frequency warping characteristic** of
the bilinear transform. To counter-act the effects of frequency warping,
we can **pre-warp** the Z-domain equation using the inverse warping
characteristic. If the equation is prewarped before it is transformed,
the resulting poles of the system will line up more faithfully with
those in the s-domain.

$$\omega = \frac{2}{T} \arctan \left( \omega_a \frac{T}{2} \right).$$

Applying these transformations before applying the bilinear transform
actually enables direct conversions between the S-Domain and the
Z-Domain. The act of applying one of these frequency warping
characteristics to a function before transforming is called
**prewarping**.

## Wikipedia Resources

-   w:Laplace transform
-   w:Fourier transform
-   w:Z-transform
-   w:Star transform
-   w:Bilinear transform


# Control Systems/System Representations

## System Representations

This is a table of times when it is appropriate to use each different
type of system representation:

+-------------------------------------+--------------+-----------+-----------+
| Properties                          | State-Space\ | Transfer\ | Transfer\ |
|                                     | Equations    | Function  | Matrix    |
+=====================================+==============+===========+===========+
| Linear, Distributed                 | no           | no        | no        |
+-------------------------------------+--------------+-----------+-----------+
| Linear, Lumped                      | yes          | no        | no        |
+-------------------------------------+--------------+-----------+-----------+
| Linear, Time-Invariant, Distributed | no           | yes       | no        |
+-------------------------------------+--------------+-----------+-----------+
| Linear, Time-Invariant, Lumped      | yes          | yes       | yes       |
+-------------------------------------+--------------+-----------+-----------+

## General Description

These are the general external system descriptions. *y* is the system
output, *h* is the system response characteristic, and *x* is the system
input. In the time-variant cases, the general description is also known
as the convolution description.

  General Description
  ----------------------------
  Time-Invariant, Non-causal
  Time-Invariant, Causal
  Time-Variant, Non-Causal
  Time-Variant, Causal

## State-Space Equations

These are the state-space representations for a system. *y* is the
system output, *x* is the internal system state, and *u* is the system
input. The matrices A, B, C, and D are coefficient matrices.

  State-Space Equations
  -----------------------
  Time-Invariant
  Time-Variant

These are the digital versions of the equations listed above. All the
variables have the same meanings, except that the systems are digital.

  State-Space Equations
  -----------------------
  Time-Invariant
  Time-Variant

## Transfer Functions

These are the transfer function descriptions, obtained by using the
Laplace Transform or the Z-Transform on the general system descriptions
listed above. *Y* is the system output, *H* is the system transfer
function, and *X* is the system input.

  Transfer Function
  -------------------
  $Y(s) = H(s)X(s)$

  Transfer Function
  -------------------
  $Y(z) = H(z)X(z)$

## Transfer Matrix

This is the transfer matrix system description. This representation can
be obtained by taking the Laplace or Z transforms of the state-space
equations. In the SISO case, these equations reduce to the transfer
function representations listed above. In the MIMO case, ***Y***is the
vector of system outputs,***X***is the vector of system inputs,
and***H*** is the transfer matrix that relates each input X to each
output Y.

  Transfer Matrix
  ----------------------------------------------
  $\mathbf{Y}(s) = \mathbf{H}(s)\mathbf{X}(s)$

  Transfer Matrix
  ----------------------------------------------
  $\mathbf{Y}(z) = \mathbf{H}(z)\mathbf{X}(z)$


# Control Systems/Matrix Operations

## Laws of Matrix Algebra

Matrices must be compatible sizes in order for an operation to be valid:

Addition:Matrices must have the same dimensions (same number of rows, same number of columns). Matrix addition is commutative:

:

    :   $A + B = B + A$

Multiplication:Matrices must have the same inner dimensions (the number of columns of the first matrix must equal the number of rows in the second matrix). For instance, if matrix A is *n* × *m*, and matrix B is *m* × *k*, then we can multiply:

:

    :   $AB = C$

:   Where C is an *n* × *k* matrix. Matrix multiplication is not
    commutative:
    $$AB \ne BA$$

:   Because it is not commutative, the differentiation must be made
    between \"multiplication on the left\", and \"multiplication on the
    right\".

Division:There is no such thing as division in matrix algebra, although multiplication of the matrix inverse performs the same basic function. To find an inverse, a matrix must be nonsingular, and must have a non-zero determinant.

## Transpose Matrix

The transpose of a matrix, denoted by:

$$X^T$$

is the matrix where the rows and columns of X are interchanged. In some
instances, the transpose of a matrix is denoted by:

$$X'$$

This shorthand notation is used when the superscript T applied to a
large number of matrices in a single equation, and the notation would
become too crowded otherwise. When this notation is used in the book,
derivatives will be denoted explicitly with:

$$\frac{d}{dt}X(t)$$

## Determinant

The determinant of a matrix it is a scalar value. It is denoted
similarly to absolute-value in scalars:

$$|X|$$

A matrix has an inverse if the matrix is square, and if the determinant
of the matrix is non-zero.

## Inverse

The inverse of a matrix A, which we will denote here by \"B\" is any
matrix that satisfies the following equation:

$$AB = BA = I$$

Matrices that have such a companion are known as \"invertible\"
matrices, or \"non-singular\" matrices. Matrices which do not have an
inverse that satisfies this equation are called \"singular\" or
\"non-invertable\".

An inverse can be computed in a number of different ways:

1.  Append the matrix A with the Identity matrix of the same size. Use
    row-reductions to make the left side of the matrice an identity. The
    right side of the appended matrix will then be the inverse:
    $$[A|I] \to [I|B]$$
2.  The inverse matrix is given by the adjoint matrix divided by the
    determinant. The adjoint matrix is the transpose of the cofactor
    matrix.
    $$A^{-1} = \frac{\operatorname{adj}(A)}{|A|}$$
3.  The inverse can be calculated from the Cayley-Hamilton Theorem.

## Eigenvalues

The eigenvalues of a matrix, denoted by the Greek letter lambda λ, are
the solutions to the characteristic equation of the matrix:

$$|X - \lambda I| = 0$$

Eigenvalues only exist for square matrices. Non-square matrices do not
have eigenvalues. If the matrix X is a real matrix, the eigenvalues will
either be all real, or else there will be complex conjugate pairs.

## Eigenvectors

The eigenvectors of a matrix are the nullspace solutions of the
characteristic equation:

$$(X - \lambda_i I)v_i = 0$$

There is at least one distinct eigenvector for every distinct
eigenvalue. Multiples of an eigenvector are also themselves
eigenvectors. However, eigenvalues that are not linearly independent are
called \"non-distinct\" eigenvectors, and can be ignored.

## Left-Eigenvectors

Left Eigenvectors are the right-hand nullspace solutions to the
characteristic equation:

$$w_i(A - \lambda_i I) = 0$$

These are also the rows of the inverse transition matrix.

## Generalized Eigenvectors

In the case of repeated eigenvalues, there may not be a complete set of
*n* distinct eigenvectors (right or left eigenvectors) associated with
those eigenvalues. Generalized eigenvectors can be generated as follows:

$$(A -\lambda I)v_{n+1} = v_n$$

Because generalized eigenvectors are formed in relation to another
eigenvector or generalize eigenvectors, they constitute an ordered set,
and should not be used outside of this order.

## Transformation Matrix

The transformation matrix is the matrix of all the eigenvectors, or the
ordered sets of generalized eigenvectors:

$$T = [v_1 v_2 \cdots v_n]$$

The inverse transition matrix is the matrix of the left-eigenvectors:

$$T^{-1} = \begin{bmatrix}w_1' \\ w_2' \\ \cdots \\ w_n'\end{bmatrix}$$

A matrix can be diagonalized by multiplying by the transition matrix:

$$A = TDT^{-1}$$

Or:

$$T^{-1}AT = D$$

If the matrix has an incomplete set of eigenvectors, and therefore a set
of generalized eigenvectors, the matrix cannot be diagonalized, but can
be converted into Jordan canonical form:

$$T^{-1}AT = J$$

## MATLAB

The MATLAB programming environment was specially designed for matrix
algebra and manipulation. The following is a brief refresher about how
to manipulate matrices in MATLAB:

Addition:To add two matrices together, use a plus sign (\"+\"):

`C = A + B;`

Multiplication:To multiply two matrices together use an asterisk (\"\*\"):

`C = A * B;`

:   If your matrices are not the correct dimensions, MATLAB will issue
    an error.

Transpose:To find the transpose of a matrix, use the apostrophe (\" \' \"):

`C = A';`

Determinant:To find the determinant, use the **det** function:

`d = det(A);`

Inverse:To find the inverse of a matrix, use the function **inv**:

`C = inv(A);`

Eigenvalues and Eigenvectors:To find the eigenvalues and eigenvectors of a matrix, use the **eig** command:

`[E, V] = eig(A);`

:   Where E is a square matrix with the eigenvalues of A in the diagonal
    entries, and V is the matrix comprised of the corresponding
    eigenvectors. If the eigenvalues are not distinct, the eigenvectors
    will be repeated. MATLAB will not calculate the generalized
    eigenvectors.

Left Eigenvectors:To find the left eigenvectors, assuming there is a complete set of distinct right-eigenvectors, we can take the inverse of the eigenvector matrix:

`[E, V] = eig(A);`\
`C = inv(V);`

The rows of C will be the left-eigenvectors of the matrix A.

For more information about MATLAB, see the wikibook MATLAB
Programming.


# Control Systems/MATLAB

## MATLAB

**MATLAB** is a programming language that is specially designed for the
manipulation of matrices. Because of its computational power, MATLAB is
a tool of choice for many control engineers to design and simulate
control systems. This page is going to discuss using MATLAB for control
systems design and analysis. MATLAB has a number of plugin modules
called \"Toolboxes\". Nearly all the functions described below are
located in the **control systems toolbox**. If your system has the
control systems toolbox installed, you can get more information about
the toolbox by typing `help control` at the MATLAB prompt.

Also, there is an open-source competitor to MATLAB called **Octave**.
Octave is similar to MATLAB, but there are also some differences. This
page will focus on MATLAB, but another page could be added to focus on
Octave. As of Sept 10th, 2006, all the MATLAB commands listed below have
been implemented in GNU octave.

This page will use the  template to show
MATLAB functions that can be used to perform different tasks.

### Input-Output Isolation

In a MIMO system, typically it can be important to isolate a single
input-output pair for analysis. Each input corresponds to a single row
in the B matrix, and each output corresponds to a single column in the C
matrix. For instance, to isolate the 2nd input and the 3rd output, we
can create a system:

`sys = ss(A, B(:,2), C(3,:), D);`

This page will refer to this technique as \"input-output isolation\".

## Step Response

First, let\'s take a look at the classical approach, with the following
system:

$$G(s) = \frac{5s + 10}{s^2 + 4s + 5}$$

This system can effectively be modeled as two vectors of coefficients,
NUM and DEN:

`NUM = [5, 10]`\
`DEN = [1, 4, 5]`

Now, we can use the MATLAB **step** command to produce the step response
to this system:

`step(NUM, DEN, t);`

Where t is a time vector. If no results on the left-hand side are
supplied by you, the step function will automatically produce a
graphical plot of the step response. If, however, you use the following
format:

`[y, x, t] = step(NUM, DEN, t);`

Then MATLAB will not produce a plot automatically, and you will have to
produce one yourself.

Here is a sample screenshot:

```{=html}
<center>
```
Step_screen.jpg\|Step response

```{=html}
</center>
```
Now, let\'s look at the modern, state-space approach. If we have the
matrices A, B, C and D, we can plug these into the step function, as
shown:

`step(A, B, C, D);`

or, we can optionally include a vector for time, t:

`step(A, B, C, D, t);`

Again, if we supply results on the left-hand side of the equation,
MATLAB will not automatically produce a plot for us.

If we didn\'t get an automatic plot, and we want to produce our own, we
type:

`[y, x, t] = step(NUM, DEN, t);`

And then we can create a graph using the **plot** command:

`plot(t, y);`

y is the output magnitude of the step response, while x is the internal
state of the system from the state-space equations:

$$x' = Ax + Bu$$

$$y = Cx + Du$$

## Classical ↔ Modern

MATLAB contains features that can be used to automatically convert to
the state-space representation from the Laplace representation. This
function, **tf2ss**, is used as follows:

`[A, B, C, D] = tf2ss(NUM, DEN);`

Where NUM and DEN are the coefficient vectors of the numerator and
denominator of the transfer function, respectively.

In a similar vein, we can convert from the Laplace domain back to the
state-space representation using the **ss2tf** function, as such:

`[NUM, DEN] = ss2tf(A, B, C, D);`

Or, if we have more than one input in a vector u, we can write it as
follows:

`[NUM, DEN] = ss2tf(A, B, C, D, u);`

The u parameter must be provided when our system has more than one
input, but it does not need to be provided if we have only 1 input. This
form of the equation produces a transfer function for each separate
input. NUM and DEN become 2-D matricies, with each row being the
coefficients for each different input.

## z-Domain Digital Filters

Let us now consider a digital system with the following generic transfer
function in the Z domain:

$$H(z) = \frac{n(z)}{d(z)}$$

Where n(z) and d(z) are the numerator and denominator polynomials of the
transfer function, respectively. The **filter** command can be used to
apply an input vector x to the filter. The output, y, can be obtained
from the following code:

`y = filter(n, d, x);`

The word \"filter\" may be a bit of a misnomer in this case, but the
fact remains that this is the method to apply an input to a digital
system. Once we have the output magnitude vector, we can plot it using
our plot command:

`plot(y);`

To get the step response of the digital system, we must first create a
step function using the **ones** command:

`u = ones(1, N);`

Where N is the number of samples that we want to take in our digital
system (not to be confused with \"n\", our numerator coefficient). Once
we have produced our unit step function, we can pass this function
through our digital filter as such:

`y = filter(n, d, u);`

And we can plot y:

`plot(y);`

## State-Space Digital Filters

Likewise, we can analyze a digital system in the state-space
representation. If we have the following digital state relationship:

$$x[k + 1] = Ax[k] + Bu[k]$$

$$y[k] = Cx[k] + Du[k]$$

We can convert automatically to the pulse response using the **ss2tf**
function, that we used above:

`[NUM, DEN] = ss2tf(A, B, C, D);`

Then, we can filter it with our prepared unit-step sequence vector, u:

`y = filter(num, den, u)`

this will give us the step response of the digital system in the
state-space representation.

## Root Locus Plots

MATLAB supplies a useful, automatic tool for generating the root-locus
graph from a transfer function: the **rlocus** command. In the transfer
function domain, or the state space domain respectively, we have the
following uses of the function:

`rlocus(num, den);`

And:

`rlocus(A, B, C, D);`

These functions will automatically produce root-locus graphs of the
system. However, if we provide left-hand parameters:

`[r, K] = rlocus(num, den);`

Or:

`[r, K] = rlocus(A, B, C, D);`

The function won\'t produce a graph automatically, and you will need to
produce one yourself. There is also an optional additional parameter for
gain, K, that can be supplied:

`rlocus(num, den, K);`

Or:

`rlocus(A, B, C, D, K);`

If K is not supplied, MATLAB will supply an automatic gain value for
you.

Once we have our values \[r, K\], we can plot a root locus:

`plot(r);`

The **rlocus** command cannot be used with MIMO systems, so if your
system is a MIMO system, you must separate out your coefficient matrices
to isolate each separate Input-output pair, and graph each individually.

Here is a sample screenshot:

```{=html}
<center>
```
Rlocus_screen.jpg\|root-locus

```{=html}
</center>
```
## Digital Root-Locus

Creating a root-locus diagram for a digital system is exactly the same
as it is for a continuous system. The only difference is the
interpretation of the results, because the stability region for digital
systems is different from the stability region for continuous systems.
The same **rlocus** function can be used, in the same manner as is used
above.

## Bode Plots

MATLAB also offers a number of tools for examining the frequency
response characteristics of a system, both using Bode plots, and using
Nyquist charts. To construct a Bode plot from a transfer function, we
use the following command:

`[mag, phase, omega] = bode(NUM, DEN, omega);`

Or:

`[mag, phase, omega] = bode(A, B, C, D, u, omega);`

Where \"omega\" is the frequency vector where the magnitude and phase
response points are analyzed. If we want to convert the magnitude data
into decibels, we can use the following conversion:

`magdb = 20 * log10(mag);`

This conversion should be known well enough by now that it doesn\'t
require explanation.

When talking about Bode plots in decibels, it makes the most sense (and
is the most common occurrence) to also use a logarithmic frequency
scale. To create such a logarithmic sequence in omega, we use the
**logspace** command, as such:

`omega = logspace(a, b, n);`

This command produces n points, spaced logarithmicly, from $10^a$ up to
$10^b$.

If we use the bode command without left-hand arguments, MATLAB will
produce a graph of the bode phase and magnitude plots automatically.

The **bode** command, if used with a MIMO system, will use subplots to
produce all the input-output relationship graphs on a single plot
window. for a system with multiple inputs and multiple outputs, this can
become difficult to see clearly. In these cases, it is typically better
to separate out your coefficient matrices to isolate each individual
input-output pair.

Here is a sample screenshot:

```{=html}
<center>
```
Bode_screen.jpg\|Bode plot (Frequency response)

```{=html}
</center>
```
## Nyquist Plots

In addition to the bode plots, we can create nyquist charts by using the
**nyquist** command. The nyquist command operates in a similar manner to
the bode command (and other commands that we have used so far):

`[real, imag, omega] = nyquist(NUM, DEN, omega);`

Or:

`[real, imag, omega] = nyquist(A, B, C, D, u, omega);`

Here, \"real\" and \"imag\" are vectors that contain the real and
imaginary parts of each point of the nyquist diagram. If we don\'t
supply the right-hand arguments, the nyquist command automatically
produces a nyquist plot for us.

Like the **bode** command, the **nyquist** command will use subplots to
display the input-output relations of MIMO systems on a single plot
window. If there are multiple input-output pairs, it can be difficult to
see the individual graphs.

Here is a sample screenshot:

```{=html}
<center>
```
Nyquist_screen.jpg\|Nyquist plot

```{=html}
</center>
```
## Lyapunov Equations

## Controllability

A controllability matrix can be constructed using the **ctrb** command.
The controllability gramian can be constructed using the **gram**
command.

## Observability

An observability matrix can be constructed using the command **obsv**

## Empirical Gramians

Empirical gramians can be computed for linear and also nonlinear control
systems. The empirical gramian framework **emgr** allows the computation
of the controllability, observability and cross gramian; it is
compatible with **MATLAB** and **OCTAVE** and does not require the
*control systems toolbox*.

## Further reading

-   Ogata, Katsuhiko, \"Solving Control Engineering Problems with
    MATLAB\", Prentice Hall, New Jersey, 1994.

-   MATLAB Programming.
-   <http://octave.sourceforge.net/>
-   MATLAB Category on
    ControlTheoryPro.com
-   Empirical Gramian Framework


# Control Systems/Glossary

The following is a listing of some of the most important terms from the
book, along with a short definition or description.

## A, B, C

Acceleration Error:The amount of steady state error of the system when stimulated by a unit parabolic input.\
Acceleration Error Constant:A system metric that determines that amount of acceleration error in the system.\
Adaptive Control:A branch of control theory where controller systems are able to change their response characteristics over time, as the input characteristics to the system change.\
Adaptive Gain: when control gain is varied depending on system state or condition, such as a disturbance\
Additivity:A system is additive if a sum of inputs results in a sum of outputs.\
Analog System:A system that is continuous in time and magnitude.\
ARMA: Autoregressive Moving Average, see 1\
ATO: Analog Timed Output. Control loop output is correlated to a timed contact closure.\
A/M: Auto-Manual. Control modes, where auto typically means output is computer-driven, calculated while manual can be field-driven or merely using a static setpoint.

```{=html}
<!-- -->
```

Bilinear Transform: a variant of the Z-transform, see 2\
Block Diagram:A visual way to represent a system that displays individual system components as boxes, and connections between systems as arrows.\
Bode Plots:A set of two graphs, a \"magnitude\" and a \"phase\" graph, that are both plotted on log scale paper. The magnitude graph is plotted in decibels versus frequency, and the phase graph is plotted in degrees versus frequency. Used to analyze the frequency characteristics of the system.\
Bounded Input, Bounded Output:BIBO. If the input to the system is finite, then the output must also be finite. A condition for **stability**.

```{=html}
<!-- -->
```

Cascade: When the output of a control loop is fed to/from another loop.\
Causal:A system whose output does not depend on future inputs. All physical systems must be causal.\
Classical Approach:See **Classical Controls**.\
Classical Controls:A control methodology that uses the transform domain to analyze and manipulate the **Input-Output** characteristics of a system.\
Closed Loop:a controlled system using feedback or feedforward\
Compensator:A Control System that augments the shortcomings of another system.\
Condition Number:\
Conditional Stability:A system with variable gain is conditionally stable if it is BIBO stable for certain values of gain, but not BIBO stable for other values of gain.\
Continuous-Time:A system or signal that is defined at all points t.\
Control Rate: the rate at which control is computed and any appropriate output sent. Lower bound is sample rate.\
Control System:A system or device that manages the behavior of another system or device.\
Controller:See **Control System**.\
Convolution:A complex operation on functions defined by the integral of the two functions multiplied together, and time-shifted.\
Convolution Integral:The integral form of the convolution operation.\
CQI: Control Quality Index, $=1-abs(PV-SP)/max[PVmax-SP,SP-PVmin]$, 1 being ideal.\
CV: Controlled variable

## D, E, F

Damping Ratio:A constant that determines the damping properties of a system.\
Deadtime: time shift between the output change and the related effect (typ. at least one control sample). One sees \"Lag\" used for this action sometimes.\
Digital:A system that is both **discrete-time**, and **quantized**.\
Direct action: target output increase is required to bring the process variable (PV) to setpoint (SP) when PV is below SP. Thus, PV increases with output increase directly.\
Discrete magnitude:See **quantized**.\
Discrete time:A system or signal that is only defined at specific points in time.\
Distributed:A system is distributed if it has both an infinite number of states, and an infinite number of state variables. See **Lumped**.\
Dynamic:A system is called dynamic if it doesn\'t have memory. See **Instantaneous**, **Memory**.

```{=html}
<!-- -->
```

Eigenvalues:Solutions to the characteristic equation of a matrix. If the matrix is itself a function of time, the eigenvalues might be functions of time. In this case, they are frequently called **eigenfunctions**.\
Eigenvectors:The nullspace vectors of the characteristic equation for particular eigenvalues. Used to determine state-transitions, among other things. See 3\
Euler\'s Formula:An equation that relates complex exponentials to complex sinusoids.\
Exponential Weighted Average (EWA): Apportions fractional weight to new and existing data to form a working average. Example EWA=0.70\*EWA+0.30\*latest, see Filtering.\
External Description:A description of a system that relates the input of the system to the output, without explicitly accounting for the internal states of the system.

```{=html}
<!-- -->
```

Feedback:The output of the system is passed through some sort of processing unit H, and that result is fed into the plant as an input.\
Feedforward: whwn apriori knowledge is used to forecast at least part of the control response.\
Filtering (noise): Use of signal smoothing techniques to reject undesirable components like noise. Can be as simple as using exponential weighted averaging on the input.\
Final Value Theorem:A theorem that allows the steady-state value of a system to be determined from the transfer function.\
FOH:First order hold\
Frequency Response:The response of a system to sinusoids of different frequencies. The Fourier Transform of the impulse response.\
Fourier Transform:An integral transform, similar to the Laplace Transform, that analyzes the frequency characteristics of a system.

See 4

## G, H, I

Game Theory:A branch of study that is related to control engineering, and especially **optimal control**. Multiple competing entities, or \"players\" attempt to minimize their own cost, and maximize the cost of the opponents.\
Gain:A constant multiplier in a system that is typically implemented as an amplifier or attenuator. Gain can be changed, but is typically not a function of time. Adaptive control can use time-adaptive gains that change with time.\
General Description:An external description of a system that relates the system output to the system input, the system response, and a time constant through integration.

```{=html}
<!-- -->
```

Hendrik Wade Bode:Electrical Engineer, did work in control theory and communications. Is primarily remembered in control engineering for his introduction of the **bode plot**.\
Harry Nyquist:Electrical Engineer, did extensive work in controls and information theory. Is remembered in this book primarily for his introduction of the **Nyquist Stability Criterion**.\
Homogeniety:Property of a system whose scaled input results in an equally scaled output.\
Hybrid Systems:Systems which have both analog and digital components.

```{=html}
<!-- -->
```

Impulse:A function denoted δ(t), that is the derivative of the unit step.\
Impulse Response:The system output when the system is stimulated by an impulse input. The Inverse Laplace Transform of the transfer function of the system.\
Initial Conditions:The conditions of the system at time $t = t_0$, where t~0~ is the first time the system is stimulated.\
Initial Value Theorem:A theorem that allows the initial conditions of the system to be determined from the Transfer function.\
Input-Output Description:See **external description**.\
Instantaneous:A system is instantaneous if the system doesn\'t have memory, and if the current output of the system is only dependent on the current input. See **Dynamic**, **Memory**.\
Integrated Absolute Error (IAE):absolute error (ideal vs actual performance) is integrated over the analysis period.\
Integrated Squared Error (ISE):squared error (ideal vs actual performance) is integrated over the analysis period.\
Integrators:A system pole at the origin of the S-plane. Has the effect of integrating the system input.\
Inverse Fourier Transform:An integral transform that converts a function from the frequency domain into the time-domain.\
Inverse Laplace Transform:An integral transform that converts a function from the S-domain into the time-domain.\
Inverse Z-Transform:An integral transform that converts a function from the Z-domain into the discrete time domain.

## J, K, L

Lag: The observed process impact from an output is slower than the control rate.\
Laplace Transform:An integral transform that converts a function from the time domain into a complex frequency domain.\
Laplace Transform Domain:A complex domain where the Laplace Transform of a function is graphed. The imaginary part of **s** is plotted along the vertical axis, and the real part of **s** is plotted along the horizontal axis.\
Left Eigenvectors:Left-hand nullspace solutions to the characteristic equation of a matrix for given eigenvalues. The rows of the inverse transition matrix.\
Linear:A system that satisfies the **superposition principle**. See **Additive** and **Homogeneous**.\
Linear Time-Invariant: LTI. See **Linear**, and **Time-Invariant**.\
Low Clamp: User-applied lower bound on control output signal.\
L/R: Local/Remote operation.\
LQR: Linear Quadratic Regulator.\
Lumped:A system with a finite number of states, or a finite number of state variables.

## M, N, O

Magnitude: the gain component of frequency response. This is often all that is considered in saying a discrete filter\'s response is well matched to the analog\'s. It is the DC gain at 0 frequency.\
Marginal Stability:A system has an oscillatory response, as determined by having imaginary poles or imaginary eigenvalues.\
Mason\'s Rule: see 5\
MATLAB: Commercial software having a Control Systems toolbox. Also see Octave.\
Memory:A system has memory if its current output is dependent on previous and current inputs.\
MFAC:Model Free Adaptive Control.\
MIMO:A system with multiple inputs and multiple outputs.\
Modern Approach:see **modern controls**\
Modern Controls:A control methodology that uses the state-space representation to analyze and manipulate the **Internal Description** of a system.\
Modified Z-Transform:A version of the Z-Transform, expanded to allow for an arbitrary processing delay.\
MPC: Model Predictive Control.\
MRAC: Model Reference Adaptive Control.\
MV: can denote Manipulated variable or Measured variable (not the same)

```{=html}
<!-- -->
```

Natural Frequency:The fundamental frequency of the system, the frequency for which the system\'s frequency response is largest.\
Negative Feedback:A feedback system where the output signal is subtracted from the input signal, and the difference is input to the plant.\
The Nyquist Criteria:A necessary and sufficient condition of stability that can be derived from **Bode plots**.\
Nonlinear Control:A branch of control engineering that deals exclusively with non-linear systems. We do not cover nonlinear systems in this book.

```{=html}
<!-- -->
```

OCTAVE: Open-source software having a Control Systems toolbox. Also see MATLAB.\
Offset: The discrepancy between desired and actual value after settling. P-only control can give offset.\
Oliver Heaviside:Electrical Engineer, Introduced the Laplace Transform as a tool for control engineering.\
Open Loop: when the system is not closed, its behavior has a free-running component rather than controlled\
Optimal Control:A branch of control engineering that deals with the minimization of system cost, or maximization of system performance.\
Order:The order of a polynomial is the highest exponent of the independent variable in that exponent. The order of a system is the order of the Transfer Function\'s denominator polynomial.\
Output equation:An equation that relates the current system input, and the current system state to the current system output.\
Overshoot:measures the extent of system response against desired (setpoint tracking).

## P, Q, R

Parabolic:A parabolic input is defined by the equation$\frac{1}{2}t^2u(t)$.\
Partial Fraction Expansion:A method by which a complex fraction is decomposed into a sum of simple fractions.\
Percent Overshoot:PO, the amount by which the step response overshoots the reference value, in percentage of the reference value.\
Phase: the directional component of frequency response, not typically well-matched between a discrete filter equivalent to the analog version, especially as frequency approaches the Nyquist limit. The final value in the limit drives system stability, and stems from the poles and zeros of the characteristic equation.\
PID:Proportional-Integral-Derivative\
Plant:A central system which has been provided, and must be analyzed or controlled.\
PLC:Programmable Logic Controller\
Pole:A value for s that causes the denominator of the transfer function to become zero, and therefore causes the transfer function itself to approach infinity.\
Pole-Zero Form:The transfer function is factored so that the locations of all the poles and zeros are clearly evident.\
Position Error:The amount of steady-state error of a system stimulated by a unit step input.\
Position Error Constant:A constant that determines the position error of a system.\
Positive Feedback:A feedback system where the system output is added to the system input, and the sum is input into the plant.\
PSD:The power spectral density which shows the distribution of power in the spectrum of a particular signal.\
Pulse Response:The response of a digital system to a unit step input, in terms of the transfer matrix.\
PV: Process variable

```{=html}
<!-- -->
```

Quantized:A system is quantized if it can only output certain discrete values.\
Quarter-decay: the time or number of control rates required for process overshoot to be limited to within 1/4 of the maximum peak overshoot (PO) after a SP change. If the PO is 25% at sample time N, this would be time N+k when subsequent PV remains \< SP\*1.0625, presuming the process is settling.

```{=html}
<!-- -->
```

Raise-Lower: Output type that works from present position rather than as a completely new computed spanned output. For R/L, the % change should be applied to the working clamps i.e. 5%(hi clamp-lo clamp).\
Ramp:A ramp is defined by the function $tu(t)$.\
Reconstructors:A system that converts a digital signal into an analog signal.\
Reference Value:The target input value of a feedback system.\
Relaxed:A system is relaxed if the initial conditions are zero.\
Reverse action: target output decrease is required to bring the process variable (PV) to setpoint (SP) when PV is below SP. Thus, PV decreases with output increase.\
Rise Time:The amount of time it takes for the step response of the system to reach within a certain range of the reference value. Typically, this range is 80%.\
Robust Control:A branch of control engineering that deals with systems subject to external and internal noise and disruptions.

## S, T, U, V

Samplers:A system that converts an analog signal into a digital signal.\
Sampled-Data Systems:See *Hybrid Systems*\'.\
Sampling Time:In a discrete system, the sampling time is the amount of time between samples. Reflects the lower bound for Control rate.\
SCADA: Supervisory Control and Data Acquisition.\
S-Domain:The domain of the Laplace Transform of a signal or system.\
Second-order System;\
Settling Time:The amount of time it takes for the system\'s oscillatory response to be damped to within a certain band of the steady-state value. That band is typically 10%.\
Signal Flow Diagram:A method of visually representing a system, using arrows to represent the direction of signals in the system.\
SISO: Single input, single output.\
Span: the designed operation region of the item,=high range-low range. Working span can be smaller if output clamps are used.\
Stability:Typically \"BIBO Stability\", a system with a well-behaved input will result in a well-behaved output. \"Well-behaved\" in this sense is arbitrary.\
Star Transform:A version of the Laplace Transform that acts on discrete signals. This transform is implemented as an infinite sum.\
State Equation:An equation that relates the future states of a system with the current state and the current system input.\
State Transition Matrix:A coefficient matrix, or a matrix function that relates how the system state changes in response to the system input. In time-invariant systems, the state-transition matrix is the matrix exponential of the system matrix.\
State-Space Equations:A set of equations, typically written in matrix form, that relates the input, the system state, and the output. Consists of the state equation and the output equation. See 6\
State-Variable:A vector that describes the internal state of the system.\
Stability:The system output cannot approach infinity as time approaches infinity. See **BIBO**, **Lyapunov Stability**.\
Step Response:The response of a system when stimulated by a unit-step input. A unit step is a setpoint change for setpoint tracking.\
Steady State:The output value of the system as time approaches infinity.\
Steady State Error:At steady state, the amount by which the system output differs from the reference value.\
Superposition:A system satisfies the condition of superposition if it is both additive and homogeneous.\
System Identification: method of trying to identify the system characterization , typically through least squares analysis of input,output and noise data vectors. May use ARMA type framework.\
System Type:The number of ideal integrators in the system.

```{=html}
<!-- -->
```

Time-Invariant:A system is time-invariant if an input time-shifted by an arbitrary delay produces an output shifted by that same delay.\
Transfer Function:The ratio of the system output to its input, in the S-domain. The Laplace Transform of the function\'s impulse response.\
Transfer Function Matrix:The Laplace transform of the state-space equations of a system, that provides an external description of a MIMO system.

```{=html}
<!-- -->
```

Uniform Stability:Also \"Uniform BIBO Stability\", a system where an input signal in the range \[0, 1\] results in a finite output from the initial time until infinite time. See 7.\
Unit Step:An input defined by $u(t)$. Practically, a setpoint change.\
Unity Feedback:A feedback system where the feedback loop element H has a transfer function of 1.

```{=html}
<!-- -->
```

Velocity Error:The amount of steady-state error when the system is stimulated by a ramp input.\
Velocity Error Constant:A constant that determines that amount of velocity error in a system.

## W, X, Y, Z

W-plane: Reference plane used in the bilinear transform.\
Wind-up: when the numerics of computed control adjustment can \"wind-up\", yielding control correction with an inappropriate component unless prevented. An example is the \"I\" contribution of PID if output has been disconnected during PID calculation

```{=html}
<!-- -->
```

Zero:A value for s that causes the numerator of the transfer function to become zero, and therefore causes the transfer function itself to become zero.\
Zero Input Response:The response of a system with zero external input. Relies only on the value of the system state to produce output.\
Zero State Response:The response of the system with zero system state. The output of the system depends only on the system input.\
ZOH: Zero order hold.\
Z-Transform:An integral transform that is related to the Laplace transform through a change of variables. The Z-Transform is used primarily with digital systems. See 8


# Control Systems/List of Equations

The following is a list of the important equations from the text,
arranged by subject. For more information about these equations,
including the meaning of each variable and symbol, the uses of these
functions, or the derivations of these equations, see the relevant pages
in the main text.

## Fundamental Equations

$$e^{j\omega} = \cos(\omega) + j\sin(\omega)$$

$$(a*b)(t) = \int_{-\infty}^\infty a(\tau)b(t - \tau)d\tau$$

$$\mathcal{L}[f(t) * g(t)] = F(s)G(s)$$

$$\mathcal{L}[f(t)g(t)] = F(s) * G(s)$$

$$|A - \lambda I| = 0$$

$$Av = \lambda v$$

$$wA = \lambda w$$

$$dB = 20 \log(C)$$

## Basic Inputs

$$u(t) = \left\{
\begin{matrix}
  0, & t < 0
\\
  1, & t \ge 0
\end{matrix}\right.$$

$$r(t) = t u(t)$$

$$p(t) = \frac{1}{2}t^2 u(t)$$

## Error Constants

$$K_p = \lim_{s \to 0} G(s)$$

$$K_p = \lim_{z \to 1} G(z)$$

$$K_v = \lim_{s \to 0} s G(s)$$

$$K_v = \lim_{z \to 1} (z - 1) G(z)$$

$$K_a = \lim_{s \to 0} s^2 G(s)$$

$$K_a = \lim_{z \to 1} (z - 1)^2 G(z)$$

## System Descriptions

$$y(t) = \int_{-\infty}^\infty g(t, r)x(r)dr$$

$$y(t) = x(t) * h(t) = \int_{-\infty}^\infty x(\tau)h(t - \tau)d\tau$$

$$Y(s) = H(s)X(s)$$

$$Y(z) = H(z)X(z)$$

$$x'(t) = A x(t) + B u(t)$$

$$y(t) = C x(t) + D u(t)$$

$$C[sI - A]^{-1}B + D = \mathbf{H}(s)$$

$$C[zI - A]^{-1}B + D = \mathbf{H}(z)$$

$$\mathbf{Y}(s) = \mathbf{H}(s)\mathbf{U}(s)$$

$$\mathbf{Y}(z) = \mathbf{H}(z)\mathbf{U}(z)$$

$$M = \frac{y_{out}}{y_{in}} = \sum_{k=1}^N \frac{M_k \Delta\ _k}{ \Delta\ }$$

## Feedback Loops

$$H_{cl}(s) =  \frac{KGp(s)}{1 + KGp(s)Gb(s)}$$

$$H_{ol}(s) = KGp(s)Gb(s)$$

$$F(s) = 1 + H_{ol}$$ {{-}}

## Transforms

$$F(s) = \mathcal{L}[f(t)] = \int_0^\infty f(t) e^{-st}dt$$

$$f(t)
        = \mathcal{L}^{-1} \left\{F(s)\right\}
        = {1 \over {2\pi}}\int_{c-i\infty}^{c+i\infty} e^{st} F(s)\,ds$$

$$F(j\omega) = \mathcal{F}[f(t)] = \int_0^\infty f(t) e^{-j\omega t} dt$$

$$f(t)
        = \mathcal{F}^{-1}\left\{F(j\omega)\right\}
        = \frac{1}{2\pi}\int_{-\infty}^\infty F(j\omega) e^{-j\omega t} d\omega$$

$$F^*(s) = \mathcal{L}^*[f(t)] = \sum_{i = 0}^\infty f(iT)e^{-siT}$$

$$X(z) = \mathcal{Z}\left\{x[n]\right\} = \sum_{i = -\infty}^\infty x[n] z^{-n}$$

$$x[n] = Z^{-1} \{X(z) \}= \frac{1}{2 \pi j} \oint_{C} X(z) z^{n-1} dz \$$

$$X(z, m) = \mathcal{Z}(x[n], m) = \sum_{n = -\infty}^{\infty} x[n + m - 1]z^{-n}$$

## Transform Theorems

$$x(\infty) = \lim_{s \to 0} s X(s)$$

$$x[\infty] = \lim_{z \to 1} (z - 1) X(z)$$

$$x(0) = \lim_{s \to \infty} s X(s)$$

## State-Space Methods

$$x(t) = e^{At-t_0}x(t_0) + \int_{t_0}^{t}e^{A(t - \tau)}Bu(\tau)d\tau$$

$$x[n] = A^nx[0] + \sum_{m=0}^{n-1}A^{n-1-m}Bu[n]$$

$$y(t) = Ce^{At-t_0}x(t_0) + C\int_{t_0}^{t}e^{A(t - \tau)}Bu(\tau)d\tau + Du(t)$$

$$y[n] = CA^nx[0] + \sum_{m=0}^{n-1}CA^{n-1-m}Bu[n] + Du[n]$$

$$x(t) = \phi(t, t_0)x(t_0) + \int_{t_0}^{t} \phi(\tau, t_0)B(\tau)u(\tau)d\tau$$

$$x[n] = \phi[n, n_0]x[t_0] + \sum_{m = n_0}^{n} \phi[n, m+1]B[m]u[m]$$

$$G(t, \tau) = \left\{\begin{matrix}C(\tau)\phi(t, \tau)B(\tau) & \mbox{ if } t \ge \tau \\0 & \mbox{ if } t < \tau\end{matrix}\right.$$

$$G[n] = \left\{\begin{matrix}CA^{k-1}N & \mbox{ if } k > 0 \\ 0 & \mbox{ if } k \le 0\end{matrix}\right.$$

## Root Locus

$$1 + KG(s)H(s) = 0$$

$$1 + K\overline{GH}(z) = 0$$

$$\angle KG(s)H(s) = 180^\circ$$

$$\angle K\overline{GH}(z) = 180^\circ$$

$$N_a = P - Z$$

$$\phi_k = (2k + 1)\frac{\pi}{P - Z}$$

$$\sigma_0 = \frac{\sum_P - \sum_Z}{P - Z}$$

$$\frac{G(s)H(s)}{ds} = 0$$ or $\frac{\overline{GH}(z)}{dz} = 0$

## Lyapunov Stability

$$MA + A^TM = -N$$

## Controllers and Compensators

$$D(s) = K_p + {K_i \over s} + K_d s$$

$$D(z) = K_p + K_i \frac{T}{2} \left[ \frac{z + 1}{z - 1} \right] + K_d \left[ \frac{z - 1}{Tz} \right]$$


# X86 Disassembly/Introduction

## What Is This Book About?

This book is about the disassembly of x86 machine code into
human-readable assembly, and the decompilation of x86 assembly code into
human-readable C or C++ source code. Some topics covered will be common
to all computer architectures, not just x86-compatible machines.

## What Will This Book Cover?

This book is going to look in-depth at the disassembly and decompilation
of x86 machine code and assembly code. We are going to look at the way
programs are made using assemblers and compilers, and examine the way
that assembly code is made from C or C++ source code. Using this
knowledge, we will try to reverse the process. By examining common
structures, such as data and control structures, we can find patterns
that enable us to disassemble and decompile programs quickly.

## Who Is This Book For?

This book is for readers at the undergraduate level with experience
programming in x86 Assembly and C or C++. This book is not designed to
teach assembly language programming, C or C++ programming, or
compiler/assembler theory.

## What Are The Prerequisites?

The reader should have a thorough understanding of x86
Assembly, C
Programming, and possibly C++
Programming. This book is intended to
increase the reader\'s understanding of the relationship between x86
machine code, x86 Assembly Language, and the C Programming Language. If
you are not too familar with these topics, you may want to reread some
of the above-mentioned books before continuing.

## What is Disassembly?

Computer programs are written originally in a human readable code form,
such as assembly language or a high-level language. These programs are
then compiled into a binary format called **machine code**. This binary
format is not directly readable or understandable by humans. Many
programs \-- such as malware, proprietary commercial programs, or very
old legacy programs \-- may not have the source code available to you.

Programs frequently perform tasks that need to be duplicated, or need to
be made to interact with other programs. Without the source code and
without adequate documentation, these tasks can be difficult to
accomplish. This book outlines tools and techniques for attempting to
convert the raw machine code of an executable file into equivalent code
in assembly language and the high-level languages C and C++. With the
high-level code to perform a particular task, several things become
possible:

1.  Programs can be ported to new computer platforms, by compiling the
    source code in a different environment.
2.  The algorithm used by a program can be determined. This allows other
    programs to make use of the same algorithm, or for updated versions
    of a program to be rewritten without needing to track down old
    copies of the source code.
3.  Security holes and vulnerabilities can be identified and patched by
    users without needing access to the original source code.
4.  New interfaces can be implemented for old programs. New components
    can be built on top of old components to speed development time and
    reduce the need to rewrite large volumes of code.
5.  We can figure out what a piece of malware does. We hope this leads
    us to figuring out how to block its harmful effects. Unfortunately,
    some malware writers use self-modifying code techniques (polymorphic
    camouflage, XOR encryption, scrambling)`<ref>`{=html}

\"How does a crypter for bypass antivirus detection
work?\"

```{=html}
</ref>
```
, apparently to make it difficult to even detect that malware, much less
disassemble it.

Disassembling code has a large number of practical uses. One of the
positive side effects of it is that the reader will gain a better
understanding of the relation between machine code, assembly language,
and high-level languages. Having a good knowledge of these topics will
help programmers to produce code that is more efficient and more secure.

## References


# X86 Disassembly/Assemblers and Compilers

## Assemblers

**Assemblers "wikilink")** are
significantly simpler than compilers, and are often implemented to
simply translate the assembly code to binary machine code via one-to-one
correspondence. Assemblers rarely optimize beyond choosing the shortest
form of an instruction or filling delay slots.

Because assembly is such a simple process, disassembly can often be just
as simple. Assembly instructions and machine code words have a
one-to-one correspondence, so each machine code word will exactly map to
one assembly instruction. However, disassembly has some other
difficulties which cannot be accounted for using simple code-word
lookups. We will introduce assemblers here, and talk about disassembly
later.

## Assembler Concepts

Assemblers, on a most basic level, translate assembly instructions into
machine code with a one to one correspondence. They can also translate
named variables into hard-coded memory addresses and labels into their
relative code addresses.

Assemblers, in general, do not perform code optimization. The machine
code that comes out of an assembler is equivalent to the assembly
instructions that go into the assembler. Some assemblers have high-level
capabilities in the form of *Macros.*

Some information about the program is lost during the assembly process.
First and foremost, program data is stored in the same raw binary format
as the machine code instructions. This means that it can be difficult to
determine which parts of the program are actually instructions. Notice
that you can disassemble raw data, but the resultant assembly code will
be nonsensical. Second, textual information from the assembly source
code file, such as variable names, label names, and code comments are
all destroyed during assembly. When you disassemble the code, the
instructions will be the same, but all the other helpful information
will be lost. The code will be accurate, but more difficult to read.

Compilers, as we will see later, cause even more information to be lost,
and decompiling is often so difficult and convoluted as to become nearly
impossible to do accurately.

## Intel Syntax Assemblers

Because of the pervasiveness of Intel-based IA-32 microprocessors in the
home PC market, the majority of assembly work done (and the majority of
assembly work considered in this wikibook) is x86-based. Many of these
assemblers (or new versions of them) can handle amd64/x86_64/EMT64 code
as well, although this wikibook will focus primarily on 32 bit
(x86/IA-32) code examples.

### MASM

MASM is Microsoft\'s assembler, an abbreviation for \"Macro Assembler.\"
However, many people use it as an acronym for \"Microsoft Assembler,\"
and the difference isn\'t a problem at all. MASM has a powerful macro
feature, and is capable of writing very low-level syntax, and
pseudo-high-level code with its macro feature. MASM 6.15 is currently
available as a free-download from Microsoft, and MASM 7.xx is currently
available as part of the Microsoft platform DDK.

-   MASM uses Intel Syntax.
-   MASM is used by Microsoft to implement some low-level portions of
    its Windows Operating systems.
-   MASM, contrary to popular belief, has been in constant development
    since 1980, and is upgraded on a needs-basis.
-   MASM has always been made compatible by Microsoft to the current
    platform, and executable file types.
-   MASM currently supports all Intel instruction sets, including SSE2.

Many users love MASM, but many more still dislike the fact that it
isn\'t portable to other systems.

### TASM

TASM, Borland\'s \"Turbo Assembler,\" is a functional assembler from
Borland that integrates seamlessly with Borland\'s other software
development tools. Current release version is version 5.0. TASM syntax
is very similar to MASM, although it has an \"IDEAL\" mode that many
users prefer. TASM is not free.

### NASM

NASM, the \"Netwide Assembler,\" is a free, portable, and retargetable
assembler that works on both Windows and Linux. It supports a variety of
Windows and Linux executable file formats, and even outputs pure binary.
NASM is not as \"mature\" as either MASM or TASM, but is:

-   more portable than MASM
-   cheaper than TASM
-   strives to be very user-friendly

NASM comes with its own disassembler `ndisasm`, and supports 64-bit
(x86-64/x64/AMD64/Intel 64) CPUs.

NASM is released under the LGPL.

### FASM

FASM, the \"Flat Assembler\" is an open source assembler that supports
x86, and IA-64 Intel architectures.

## (x86) AT&T Syntax Assemblers

AT&T syntax for x86 microprocessor assembly code is not as common as
Intel-syntax, but the GNU Assembler (GAS) uses it, and it is the *de
facto* assembly standard on Unix and Unix-like operating systems.

### GAS

The GNU Assembler (GAS) is the default
back-end to the GNU Compiler Collection (GCC) suite. As such, GAS is as
portable and retargetable as GCC is. However, GAS uses the AT&T syntax
for its instructions as default, which some users find to be less
readable than Intel syntax. Newer versions of gas can be switched to
Intel syntax with the directive \".intel_syntax noprefix\".

GAS is developed specifically to be used as the GCC backend. Because GCC
always feeds it syntactically correct code, GAS often has minimal error
checking.

GAS is available as a part of either the GCC package or the GNU binutils
package. 1

## Other Assemblers

### HLA

HLA, short for \"High Level
Assembler\" is a project spearheaded by Randall Hyde to create an
assembler with high-level syntax. HLA works as a front-end to other
assemblers such as FASM (the default), MASM, NASM, and GAS. HLA supports
\"common\" assembly language instructions, but also implements a series
of higher-level constructs such as loops, if-then-else branching, and
functions. HLA comes complete with a comprehensive standard library.

Since HLA works as a front-end to another assembler, the programmer must
have another assembler installed to assemble programs with HLA. HLA code
output therefore, is as good as the underlying assembler, but the code
is much easier to write for the developer. The high-level components of
HLA may make programs less efficient, but that cost is often far
outweighed by the ease of writing the code. HLA high-level syntax is
very similar in many respects to Pascal, which in turn is itself similar
in many respects to C, so many high-level programmers will immediately
pick up many of the aspects of HLA.

Here is an example of some HLA code:

``` cpp
 mov(src, dest);  // C++ style comments
 pop(eax);
 push(ebp);
 for(mov(0, ecx); ecx < 10; inc(ecx)) do
    mul(ecx);
 endfor;
```

Some disassemblers and debuggers can disassemble binary code into
HLA-format, although none can faithfully recreate the HLA macros.

## Compilers

A compiler is a program that
converts instructions from one language into equivalent instructions in
another language. There is a common misconception that a compiler always
directly converts a high level language into machine language, but this
isn\'t always the case. Many compilers convert code into assembly
language, and a few even convert code from one high level language into
another. Common examples of compiled languages are: C/C++, Fortran, Ada,
and Visual Basic. The figure below shows the common compile-time steps
to building a program using the C programming language. The compiler
produces object files which are linked to form the final executable:

![](C_language_building_steps.png "C_language_building_steps.png")

For the purposes of this book, we will only be considering the case of a
compiler that converts C or C++ into assembly code or machine language.
Some compilers, such as the Microsoft C compiler, compile C and C++
source code directly into machine code. GCC on the other hand compiles C
and C++ into assembly language, and an assembler is used to convert that
into the appropriate machine code. From the standpoint of a
disassembler, it does not matter exactly how the original program was
created. Notice also that it is not possible to exactly reproduce the C
or C++ code used originally to create an executable. It is, however,
possible to create code that compiles identically, or code that performs
the same task.

C language statements do not share a one to one relationship with
assembly language. Consider that the following C statements will
typically all compile into the same assembly language code:

``` C
*arrayA = arrayB[x++];

*arrayA = arrayB[x]; x++;

arrayA[0] = arrayB[x++];

arrayA[0] = arrayB[x]; x++;
```

Also, consider how the following loop constructs perform identical
tasks, and are likely to produce similar or even identical assembly
language code:

``` c
for(;;) { ... }

while(1) { ... }

do { ... } while(1)
```

## Common C/C++ Compilers

The purpose of this section is to list some of the most common C and
C++
compilers in use for developing *production-level* software. There are
many many C compilers in the world, but the reverser doesn\'t need to
consider all cases, especially when looking at professional software.
This page will discuss each compiler\'s strengths and weaknesses, its
availability (download sites or cost information), and it will also
discuss how to generate an assembly listing file from each compiler.

### Microsoft C Compiler

The Microsoft C compiler is available from Microsoft for free as part of
the Windows Server 2003 SDK. It is the same compiler and library as is
used in MS Visual Studio, but doesn\'t come with the fancy IDE. The MS C
Compiler has a very good optimizing engine. It compiles C and C++, and
has the option to compile C++ code into MSIL (the .NET bytecode).

Microsoft\'s compiler only supports Windows systems, and
Intel-compatible 16/32/64 bit architectures.

The Microsoft C compiler is **cl.exe** and the linker is **link.exe**

#### Listing Files

In this wikibook, cl.exe is frequently used to produce assembly listing
files of C source code. To produce an assembly listing file yourself,
use the syntax:

`cl.exe /Fa``<assembly file name>`{=html}` ``<C source file>`{=html}

The \"/Fa\" switch is the command-line option that tells the compiler to
produce an assembly listing file.

For example, the following command line:

`cl.exe /FaTest.asm Test.c`

would produce an assembly listing file named \"Test.asm\" from the C
source file \"Test.c\". Notice that there is no space between the /Fa
switch and the name of the output file.

### GNU C Compiler

The GNU C compiler is part of the GNU Compiler Collection (GCC) suite.
This compiler is available for most systems and it is free software.
Many people use it exclusively so that they can support many platforms
with just one compiler to deal with. The GNU GCC Compiler is the *de
facto* standard compiler for Linux and Unix systems. It is retargetable,
allowing for many input languages (C, C++, Obj-C, Ada, Fortran,
etc\...), and supporting multiple target OSes and architectures. It
optimizes well, but has a non-aggressive IA-32 code generation engine.

The GCC frontend program is "gcc\" ("gcc.exe" on Windows) and the
associated linker is "ld" ("ld.exe" on Windows). Windows cmd searches
for the programs with ".exe" extensions automatically, so you don\'t
need to type the filename extension.

#### Listing Files

To produce an assembly listing file in GCC, use the following command
line syntax:

`gcc -S /path/to/sourcefile.c`

For example, the following commandline:

`gcc -S test.c`

will produce an assembly listing file named "test.s". Assembly listing
files generated by GCC will be in GAS format. On x86 you can select the
syntax with `-masm=intel` or `-masm=att`. GCC listing files are
frequently not as well commented and laid-out as are the listing files
for cl.exe.

You may add \`-g3\` flags to enable source-code-level debugging symbols
so you can see the line numbers in the listing. The
`-fno-asynchronous-unwind-tables` flag can help eliminate some macros in
the listing.

### Intel C Compiler

This compiler is used only for x86, x86-64, and IA-64 code. It is
available for both Windows and Linux. The Intel C compiler was written
by the people who invented the original x86 architecture: Intel.
Intel\'s development tools generate code that is tuned to run on Intel
microprocessors, and is intended to squeeze every last ounce of speed
from an application. AMD IA-32 compatible processors are not guaranteed
to get the same speed boosts because they have different internal
architectures.

### Metrowerks CodeWarrior

This compiler is commonly used for classic MacOS and for embedded
systems. If you try to reverse-engineer a piece of consumer electronics,
you may encounter code generated by Metrowerks CodeWarrior.

### Green Hills Software Compiler

This compiler is commonly used for embedded systems. If you attempt to
reverse-engineer a piece of consumer electronics, you may encounter code
generated by Green Hills C/C++.