\documentclass[epsfig,10pt,fullpage]{article}

\newcommand{\LabNum}{10}
\newcommand{\CommonDocsPath}{../../common/docs}
\input{\CommonDocsPath/preamble.tex}

\begin{document}

\centerline{\huge Embedded Systems}
~\\
\centerline{\huge Laboratory Exercise \LabNum}
~\\
\centerline{\large Image Processing}
~\\

\noindent
CPUs are general-purpose computational devices that are capable of a wide variety of tasks.
This level of flexibility however, comes at a cost; CPUs are slower at some tasks than
specialized devices. Because of this factor, some applications can execute more quickly if
parts of the implementation run on a specialized device, such as a custom circuit in a
field-programmable gate array (FPGA). This approach, of offloading computation to a faster
device, is known as \textit{hardware acceleration}.

\noindent
~\\
In this laboratory exercise, we will implement two versions of an image processing application
that detects the edges of an image. The first version will run entirely on the CPU. We
will assume that the reader is using the DE1-SoC board to run their programs. If a
different board is being used, the same instructions will mostly apply, but we will point
out any differences as needed. The second version of the application will
make use of hardware acceleration, by offloading most of the image processing operations to
a hardware accelerator implemented inside an FPGA. We will assume that image files are
represented in the {\it bitmap} (BMP) file format, using {\it 24-bit true color}.

\noindent
\section*{The Canny Edge-Detection Technique}

\noindent
In this exercise, we will implement a variation of the \textit{Canny edge detector}, which is
a widely-used edge-detection scheme. Figures~\ref{fig:tracks} and \ref{fig:tracks_edges}
show a sample image that is provided as the input to a Canny edge detector, as well as the
resulting edge-detected output image.

~\\
\noindent
As illustrated in Figure~\ref{fig:canny} the Canny edge-detection algorithm involves five
stages, which are applied to the input image in succession. The following
sections describe each stage of the algorithm and show how the sample image from
Figure~\ref{fig:tracks} is transformed as it passes through each stage.

~\\
~\\
\begin{figure}[h]
\centering
\begin{minipage}[b]{0.475\textwidth}
	\includegraphics[width=\textwidth]{figures/tracks.png}
	\caption{Original image.}
	\label{fig:tracks}
\end{minipage}
\hfill
\begin{minipage}[b]{0.475\textwidth}
	\includegraphics[width=\textwidth]{figures/tracks_edges.png}
	\caption{Edge-detected image.}
	\label{fig:tracks_edges}
\end{minipage}
\end{figure}
\pagebreak
\begin{figure}[H]
   \begin{center}
       \includegraphics[scale = 0.6]{figures/canny.pdf}
   \end{center}
	\caption{The Canny edge-detection algorithm.}
	\label{fig:canny}
\end{figure}

\noindent
\section*{Stage 1: Grayscale Conversion}

Figure~\ref{fig:sample_stage1} shows the state of our sample image at the end of the grayscale
conversion stage. This stage converts the input 24-bit bitmap color image (8 bits each for red,
green, and blue) into an 8-bit grayscale image. The grayscale value at each pixel is calculated
as the average of the three 8-bit color values of the original image.

\begin{figure}[h]
   \begin{center}
       \includegraphics[scale = 0.85]{figures/fig_stage1_grayscale.png}
   \end{center}
   \caption{The sample input image after the grayscale conversion stage.}
	\label{fig:sample_stage1}
\end{figure}

\noindent
\section*{Stage 2: Gaussian Smoothing}

\begin{figure}[h]
   \begin{center}
       \includegraphics[scale = 0.85]{figures/fig_stage2_gaussian.png}
   \end{center}
   \caption{The sample input image after the Gaussian smoothing stage.}
	\label{fig:sample_stage2}
\end{figure}

The purpose of the Gaussian smoothing stage is to remove some of the ``noise'' in the image. Smoothing of
the image allows the edge-detection mechanism to focus on changes in image intensity that correspond to
features in the image, as opposed to random variations that can be attributed to image noise.
Figure~\ref{fig:sample_stage2} shows the state of our sample image at the end of the Gaussian
smoothing stage.

\noindent
Smoothing, or blurring, of the image is accomplished by using a {\it Gaussian filter}, which
modifies noisy pixels (pixels that are unlike their neighbouring pixels) to be more like
their neighbours. An example of a Gaussian function is illustrated in Figure~\ref{fig:gaussian}$a$.
By choosing different values for the parameters $\sigma$ and $\mu$, the amplitude and shape of the
function can be selected. For this exercise we are using a digital version of the Gaussian,
specified as a $5 \times 5$ filter, or {\it kernel}. This kernel corresponds to a Gaussian function
with standard deviation $\sigma = 1$ and mean $\mu = 0$. Part~($b$) of Figure~\ref{fig:gaussian}
shows how the kernel is applied to the image. The * operator denotes {\it convolution}, $A$ is
the original image, and $B$ is the resulting filtered image.

\begin{figure}[h]
   \begin{center}
       \includegraphics[scale = 0.85]{figures/gaussian.pdf}
   \end{center}
   \caption{Gaussian functions and filters.}
	\label{fig:gaussian}
\end{figure}

%\[
%B = 1/273
%\begin{bmatrix}
    %1 & 4 & 7 & 4 & 1 \\
    %4 & 16 & 26 & 16 & 4 \\
    %7 & 26 & 41 & 26 & 7 \\
    %4 & 16 & 26 & 16 & 4 \\
    %1 & 4 & 7 & 4 & 1
%\end{bmatrix} * A
%\]

~\\
\noindent
For a pixel in row $i$, column $j$ of the image $A$, the kernel generates the dot-product
\begin{eqnarray*}
    B_{i, j}&=& (A_{i-2, j-2} + 4 A_{i-2, j-1} + 7 A_{i-2, j} + 4 A_{i-2, j+1} + A_{i-2, j+2} +\\
    &&4 A_{i-1, j-2} + 16 A_{i-1, j-1} + 26 A_{i-1, j} + 16 A_{i-1, j+1} + 4 A_{i-1, j+2} +\\
    &&7 A_{i, j-2} + 26 A_{i, j-1} + 41 A_{i, j} + 26 A_{i, j+1} + 7 A_{i, j+2} +\\
    &&4 A_{i+1, j-2} + 16 A_{i+1, j-1} + 26 A_{i+1, j} + 16 A_{i+1, j+1} + 4 A_{i+1, j+2} +\\
    &&A_{i+2, j-2} + 4 A_{i+2, j-1} + 7 A_{i+2, j} + 4 A_{i+2, j+1} + A_{i+2, j+2}) \div 273
\end{eqnarray*}

\noindent
The convolution operation performs this calculation for every pixel $i, j$ so that
each resulting pixel $B_{i,j}$ gets assigned the weighted average value of $A_{i,j}$ and
the $5 \times 5$ grid of pixels surrounding it (if a pixel is near the
top/bottom or left/right of the image,
then 0's are inserted for any ``missing'' pixels that are needed for the calculation). Each
dot-product result is divided by 273, which is the sum of the weights in the kernel,
so that the overall intensity of pixels in the image does not change.

\noindent
\section*{Stage 3: Sobel Operator}

The Sobel stage is used to identify {\it edges} in the image $B$ produced as the output of
the Gaussian stage. It works by finding changes in the image intensity in both the horizontal
(rows) and vertical (columns) directions. If we consider $B$ to be a two-dimensional
function $f(x,y)$, then changes in the image across each row are calculated by finding the
{\it partial derivative} of the image in the $x$ direction,
${\partial f}/{\partial x}$. Similarly, the partial derivative in the $y$ direction,
${\partial f}/{\partial y}$, is used to find changes in the image along each column. To see
how the partial derivatives can be calculated, consider the expressions in
Figure~\ref{fig:derivative}.

\begin{figure}[h]
   \begin{center}
       \includegraphics[scale = 0.85]{figures/derivative.pdf}
   \end{center}
   \caption{The calculation of partial derivatives.}
	\label{fig:derivative}
\end{figure}

~\\
\noindent
Part~($a$) of Figure~\ref{fig:derivative} gives the traditional expression for
the derivative of a function $f^\prime(x)$, which is the limit as $h$ approaches~0 of
$\Delta{f}/\Delta{x}$, where $\Delta{f}=f(x+h)-f(x)$ and $\Delta{x} = h$. To calculate the
derivative of an image at each pixel it is better to use the modified expression in
Figure~\ref{fig:derivative}$b$, in which $\Delta{f} = f(x+0.5h) - f(x-0.5h)$. Part~$c$ of
the figure provides an example that illustrates how this expression applies to a pixel in a row
of an image. To find the derivative of the pixel in the middle of the row (which has the
intensity 200) we use the pixels immediately to the right and left. Thus,
$\Delta{f} = 210 - 10$ and $\Delta{x} = 2$. The key idea for finding derivatives at each
pixel in an image is expressed by the {\it derivative filter} shown on the right hand side
of Figure~\ref{fig:derivative}$c$. It represents the calculation of $\Delta{f}$ and is used
as the basis for the Sobel stage convolution described below.

~\\
\noindent
The Sobel stage uses convolution similar to the Gaussian stage, but with two different
$3 \times 3$ kernels. The kernels and convolution operations are given below.

\[
\frac{\partial{f}}{\partial{x}} =
\begin{bmatrix}
    -1 & 0 & 1  \\
    -2 & 0 & 2  \\
    -1 & 0 & 1
\end{bmatrix} * B
\ \ \ \ \ \ \  \ \ \ \ \  \frac{\partial{f}}{\partial{y}} =
\begin{bmatrix}
    1 & 2 & 1 \\
    0 & 0 & 0 \\
    -1 & -2 & -1
\end{bmatrix} * B
\]

~\\
\noindent
These kernels represent versions of the derivative filter, extended to two dimensions, that
is derived in Figure~\ref{fig:derivative}. For each pixel, the value of
${\partial{f}}/{\partial{x}}$ depends on three rows, where pixels in the same row are
weighted by a factor of two. For example, $({\partial{f}}/{\partial{x}})_{i,j}$ for
the pixel in row $i$, column $j$ is calculated as

\begin{eqnarray*}
    \left(\frac{\partial{f}}{\partial{x}}\right)_{i, j}&=& B_{i-1, j+1} + 2 B_{i, j+1} + B_{i+1, j+1} -\\
    &&(B_{i-1, j-1} + 2 B_{i, j-1} + B_{i+1, j-1})
\end{eqnarray*}

~\\
\noindent
Similarly, the value of ${\partial{f}}/{\partial{y}}$ for each pixel depends on three
columns. Considered as a vector, the partial derivatives in the $x$ and $y$ directions
are referred to as the {\it intensity gradient}:

$$\nabla{f}=\left[\frac{\partial{f}}{\partial{x}},\frac{\partial{f}}{\partial{y}}\right]$$

~\\
\noindent
The {\it magnitude} of the intensity gradient at each pixel reflects whether that pixel is on an
``edge'' from the original image, and the {\it angle} of the gradient indicates the
direction of the corresponding edge. In this exercise we define the magnitude of the
gradient as the average of the absolute values of the partial derivatives:

\begin{equation}
    \|\nabla{f}\|=\frac{1}{2}\left(\left|\frac{\partial{f}}{\partial{x}}\right|+\left|\frac{\partial{f}}{\partial{y}}\right|\right)
\end{equation}

~\\
\noindent
If Equation (1) generates a result that is too large to fit into a pixel's eight-bit grayscale
value, then the pixel is set to its maximum value of 255. The angle of the gradient is
defined by:

\begin{equation}
    \theta={tan}^{-1}\left(\frac{{\partial{f}}/{\partial{y}}}{{\partial{f}}/{\partial{x}}}\right)
\end{equation}

~\\
\noindent
The angle $\theta$ reflects the direction of greatest ascent (in the image) at the pixel. Thus,
if the pixel is on a horizontal edge then $\theta=\pm {90}^\circ$, and if the pixel is on a
vertical edge then $\theta = 0^\circ$ or $\theta = {180}^\circ$.

~\\
\noindent
Figure~\ref{fig:sample_stage3} shows the results produced by the Sobel stage.
Parts ($a$) and ($b$) of the figure illustrate the partial derivatives and part ($c$)
shows the overall gradient. In these images the edges of the original image are highlighted
as brighter pixels. Non-edges, which are areas with low intensity gradients, appear as
darker pixels.

~\\
\begin{figure}[h]
\centering
\begin{minipage}[b]{0.32\textwidth}
	\includegraphics[width=\textwidth]{figures/stage2_gradient_x.png}
    \center{\sf{(a)} $\frac{\partial{f}}{\partial{x}}$}
\end{minipage}
\hfill
\begin{minipage}[b]{0.32\textwidth}
	\includegraphics[width=\textwidth]{figures/stage2_gradient_y.png}
    \center{\sf{(b)} $\frac{\partial{f}}{\partial{y}}$}
\end{minipage}
\hfill
\begin{minipage}[b]{0.32\textwidth}
   \includegraphics[width=\textwidth]{figures/fig_stage3_sobel.png}
    \center{\sf{(c)} $\nabla{f}$}
\end{minipage}
   \caption{Images representing the partial derivatives and the image gradient.}
	\label{fig:sample_stage3}
\end{figure}

~\\
\noindent
To illustrate the effect of the Sobel operator, let us examine different image boundaries that
may exist in an image as shown in Figure~\ref{fig:image_boundaries}. For each $3 \times 3$
image shown, we can use the Sobel operator to calculate the intensity gradient at the center
pixel. Let us examine the vertical example, where there is a boundary between darker
pixels on the left side of the image and brighter pixels on the right side. In this
example, ${\partial{f}}/{\partial{x}}$ of the center pixel can be calculated as
$91 + 2(89) + 92 - (1 + 2(1) + 3) = 355$. In the vertical direction, ${\partial{f}}/{\partial{y}}$
is $1 + 2(49) + 91 -(3 + 2(46) + 92) = 3$. The intensity gradient for
this pixel is high in the horizontal direction, and low in the vertical direction, which is to
be expected along a vertical boundary. The overall intensity gradient is
$\nabla{f} = \frac{1}{2}(355 + 3) = 179$. This is a bright pixel value, meaning that
the Sobel operator has detected this boundary as a strong edge. The gradient angle $\theta
= 0^\circ$ because the direction of steepest ascent is left-to-right.

\begin{figure}[H]
   \begin{center}
       \includegraphics[scale = 1.0]{figures/edges.pdf}
   \end{center}
   \caption{Examples of edges in an image.}
	\label{fig:image_boundaries}
\end{figure}

~\\
\noindent
In the horizontal case given in Figure~\ref{fig:image_boundaries}, using
the Sobel operator to calculate the intensity gradient at the center we see that the
vertical gradient is high (${\partial{f}}/{\partial{y}} = -364$) and the
horizontal gradient is low (${\partial{f}}/{\partial{x}} =  2$). The angle $\theta =
-90^\circ$ because the direction of greatest ascent from darker to brighter pixels is
downward from the top of the image.  For each of the diagonal
cases in Figure~\ref{fig:image_boundaries}, the gradients are high in both the $x$ and $y$
directions. The values of $\theta = \pm45^\circ$ represent the directions from darker to brighter
pixels in each image. Finally, for the non-boundary case,
the gradients are low in both directions with ${\partial{f}}/{\partial{x}} = 1$ and
${\partial{f}}/{\partial{y}} = 19$. As the gradients
are low, the center pixel would become dark with a value of
$\nabla{f} = \frac{1}{2}(1 + 19) = 10$.

\noindent
\section*{Stage 4: Non-Maximum Suppression}

\noindent
After the Sobel stage, some of the edges identified in the image may be thick and/or blurry.
The non-maximum suppression stage is used to enhance and sharpen the edges by making them thinner.
This stage examines each pixel in the image that is on an edge and
compares the pixel with its neighbours that may be part of the same edge---if the pixel is
brighter than its neighbours, then its intensity is retained, else it is set to 0.
Figure~\ref{fig:sample_stage4} shows the state of our sample image at the end of the
non-maximum suppression stage.

~\\
\begin{figure}[H]
   \begin{center}
       \includegraphics[scale = 0.85]{figures/fig_stage4_nonmax_suppression.png}
   \end{center}
   \caption{The sample input image after the non-maximum suppression stage.}
	\label{fig:sample_stage4}
\end{figure}

\begin{figure}[H]
   \begin{center}
       \includegraphics[scale = 0.8]{figures/fig_nonmaximum_suppression.pdf}
   \end{center}
   \caption{The effect of nonmaximum suppression on a blurred vertical line.}
	\label{fig:nonmaximum_suppression}
\end{figure}

~\\
\noindent
The effect of non-maximum suppression on a sample image containing a blurry vertical line
is illustrated in Figure~\ref{fig:nonmaximum_suppression}.
The vertical line, which is originally three-pixels wide, becomes one-pixel
wide in the output image. Non-maximum suppression works by examining each pixel in the
image in turn. The value of the gradient direction $\theta$ produced during the Sobel stage
for the pixel indicates the type of associated edge. If $\theta$ is
close to $0^\circ$ or $180^\circ$ then the pixel
is on a ``vertical'' edge. In this case, the non-maximum suppression algorithm compares the
intensity of its left and right neighbours to the pixel. If its intensity is higher,
then the pixel is preserved in the output image from this stage, else it is set to~0.
Similarly, a pixel with $\theta$ near $\pm90^\circ$ is preserved if its intensity is
higher than the ones above and below it, and pixels with $\theta$ around $\pm45^\circ$
are preserved only if their intensity is greater than the appropriate neighbours that would
be a part of the same ``diagonal'' edge.
Following this process for each pixel in the image has the effect of producing thinner edges.

\noindent
\section*{Stage 5: Hysteresis}

The goal of the hysteresis stage is to remove any pixel that does not belong to an edge.
Additionally, weak edges are erased altogether by removing any pixel that does not meet
a user-defined intensity threshold. The hysteresis algorithm examines each pixel to determine
whether: the pixel exceeds the user-defined threshold value, and there exists at least
one adjacent pixel (horizontally, vertically, or diagonally) that exceeds the intensity threshold.
If both conditions are met, the pixel is preserved, else it is removed by turning it black.
Figure~\ref{fig:sample_stage5} shows the end result of the hysteresis stage.

\begin{figure}[H]
   \begin{center}
       \includegraphics[scale = 0.85]{figures/fig_stage5_hysteresis.png}
   \end{center}
   \caption{The sample input image after the hysteresis stage.}
	\label{fig:sample_stage5}
\end{figure}

\section*{Part I}

Write a C-language program that implements the five stages of the canny edge detector as described
above, and run your code on the DE1-SoC Computer. Some sample images are provided along
with this exercise. Sample skeleton code for this part is provided in Figure~\ref{fig:skeleton}.
It contains functionality for loading and storing bitmap images. The {\it main} function for
the program is given in part~($c$) of the figure. Once a 24-bit true-color image is loaded
into memory, the code calls functions to transform the pixels according to the five
edge-detection stages, and then writes the resulting image into an output file. The first
step of edge-detection, in which the image is converted to grayscale, is provided in the code,
but you have to write the other stages.  The code in Figure~\ref{fig:skeleton} also
shows how to measure the runtime of your program, which will allow you to compare with the
hardware-accelerated version developed later in this exercise. The code in
Figure~\ref{fig:skeleton} is provided along with this exercise. Some additional functionality not
shown in the figure is also included, such as code that can draw the images on an
output video display.

\lstset{language=C,numbers=none,escapechar=|,basicstyle=\small\ttfamily,}
\begin{figure}[h]
\begin{center}
\begin{minipage}[t]{15.5 cm}
\begin{lstlisting}[name=skeleton]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int width, height; // the dimensions of the image
struct pixel {
    unsigned char b;
    unsigned char g;
    unsigned char r;
};

// Read BMP file and extract the pixel values (data) and header.
// Data is data[0] = BLUE, data[1] = GREEN, data[2] = RED, data[3] = BLUE, etc...
int read_bmp(char *filename, unsigned char **header, struct pixel **data) {
    struct pixel *data_tmp;
    unsigned char *header_tmp;
    FILE *file = fopen (filename, "rb");
    if (!file) return -1;

    // read the 54-byte header
    header_tmp = malloc (54 * sizeof(unsigned char));
    fread (header_tmp, sizeof(unsigned char), 54, file);

    // get height and width of image from the header
    width = *(int*)(header_tmp + 18);  // width is a 32-bit int at offset 18
    height = *(int*)(header_tmp + 22); // height is a 32-bit int at offset 22

    // Read in the image
    int size = width * height;
    data_tmp = malloc (size * sizeof(struct pixel));
    fread (data_tmp, sizeof(struct pixel), size, file); // read the data
    fclose (file);

    *header = header_tmp;
    *data = data_tmp;
    return 0;
}
\end{lstlisting}
\end{minipage}
\caption{An outline of the software for edge detection (part $a$).}
\label{fig:skeleton}
\end{center}
\end{figure}

\lstset{language=C,numbers=none,escapechar=|}
\begin{center}
\begin{minipage}[t]{15.5 cm}
\begin{lstlisting}[name=skeleton]
// Set the grayscale 8-bit value by averaging the r, g, and b channel values.
// Store the 8-bit grayscale value in the r channel.
void convert_to_grayscale(struct pixel *data) {
    int x, y;

    // declare image as a 2-D array, to allow the syntax image[row][column]
    struct pixel (*image)[width] = (struct pixel (*)[width]) data;
    for (y = 0; y < height; y++) {          // y = 0 is the bottom row
        for (x = 0; x < width; x++) {       // x = 0 is the left side
            // Use the 8 bits of the r field to hold the grayscale image
            image[y][x].r = (image[y][x].r + image[y][x].b + image[y][x].g) / 3;
        }
    }
}

// Write the grayscale image to disk. The 8-bit grayscale values should be
// inside the r channel of each pixel.
void write_bmp(char *filename, unsigned char *header, struct pixel *data) {
    FILE* file = fopen (filename, "wb");
    // declare image as a 2-D array, to allow the syntax image[row][column]
    struct pixel (*image)[width] = (struct pixel (*)[width]) data;

    // write the 54-byte header
    fwrite (header, sizeof(unsigned char), 54, file);
    int y, x;

    // the r field of the pixel has the grayscale value; copy to g and b.
    for (y = 0; y < height; y++) {          // y = 0 is the bottom row
        for (x = 0; x < width; x++) {       // x = 0 is the left side
            image[y][x].b = image[y][x].r;
            image[y][x].g = image[y][x].r;
        }
    }
    int size = width * height;
    fwrite (image, sizeof(struct pixel), size, file); // write the data
    fclose (file);
}

// Gaussian blur. Operate on the .r fields of the pixels only.
void gaussian_blur(|$\ldots$|) {
    unsigned int filter[5][5] = {
        { 1,  4,  7,  4, 1 },
        { 4, 16, 26, 16, 4 },
        { 7, 26, 41, 26, 7 },
        { 4, 16, 26, 16, 4 },
        { 1,  4,  7,  4, 1 }
    };
	 // ... code not shown
}

\end{lstlisting}
~\\
Figure \ref{fig:skeleton}. An outline of the software for edge detection (part $b$).
\end{minipage}
\end{center}

\lstset{language=C,numbers=none,escapechar=|}
\begin{center}
\begin{minipage}[t]{15.5 cm}
\begin{lstlisting}[name=skeleton]
void sobel_filter(|$\ldots$|) {
    int sobel_x[3][3] = {   // Sobel x direction (finds vertical edges)
        { -1,  0,  1 },
        { -2,  0,  2 },
        { -1,  0,  1 }
    };
    int sobel_y[3][3] = {   // Sobel in y direction (finds horizontal edges)
        { -1, -2, -1 },     // y == 0 (bottom) row
        {  0,  0,  0 },     // y == 1 (middle) row
        {  1,  2,  1 }      // y == 2 (top) row
    };
	 // ... code not shown
}

void non_maximum_suppressor(|$\ldots$|) {
	 // ... code not shown
}

void hysteresis_filter(|$\ldots$|) {
    #define strong_pixel_threshold 32	// example value
	 // ... code not shown
}

int main(int argc, char *argv[]) {
    struct pixel *image;     // used to hold the image after each stage
    signed int *G_x, *G_y;   // used to hold the partial derivatives after Sobel
    unsigned char *header;
    time_t start, end;

    if (argc < 2) {         // Check inputs
        printf("Usage: part1 <BMP filename>\n");
        return 0;
    }
    // Open input image file (24-bit true color bitmap)
    if (read_bmp (argv[1], &header, &image) < 0) {
        printf("Failed to read BMP\n");
        return 0;
    }
    start = clock ();   // Start measuring time

    convert_to_grayscale (image);
    // gaussian_blur (&image);
    // sobel_filter (&image, &G_x, &G_y);
    // non_max_suppress (&image, G_x, G_y);
    // hysteresis_filter (&image);

    end = clock();

    printf("TIME ELAPSED: %.0f ms\n", ((double) (end - start)) * 1000 / CLOCKS_PER_SEC);

    write_bmp ("edges.bmp", header, image);
    return 0;
}
\end{lstlisting}
~\\
Figure \ref{fig:skeleton}. An outline of the software for edge detection (part $c$).
\end{minipage}
\end{center}

\section*{Part II}

For Part I you used the DE1-SoC Computer system to run your program. For this part, you will
use a different computer system, which is illustrated in Figure~\ref{fig:edge_detect_system}.
This system include an edge-detection mechanism that is implemented as a hardware circuit
in the FPGA device. As indicated in the figure, the hardware edge-detection mechanism
consists of five components that are connected in sequence. The first component is called
{\it Mem-to-Stream DMA}. This component is a {\it direct memory access} (DMA) controller that
reads a 24-bit color image from memory. As the DMA reads these pixels, it
{\it streams} (sends in sequence) them to the {\it RGB24-to-Grayscale} color-space converter.
This converter implements stage one of the canny edge detector, converting the 24-bit color
pixels into 8-bit grayscale pixels. The grayscale pixels are then streamed to the
{\it Edge Detector} component, which implements stages two to five. The
{\it Grayscale-to-RGB24} color-space converter then transforms the grayscale image back into
the RGB24 format, which the {\it Stream-to-Mem DMA} then writes back into memory.

~\\
\noindent
Figure~\ref{fig:edge_detect_system} shows two types of memory ports in the FPGA: an SDRAM
port, and an Onchip-memory port. The physical address ranges of these memories are
\texttt{0xC0000000} to \texttt{0xC3FFFFFF} for SDRAM and \texttt{0xC8000000} to
\texttt{0xC807FFFF} for Onchip memory. If you are using the DE1-SoC or DE10-Standard
boards, then the edge-detection mechanism and video-out port are connected to the SDRAM port.
If you are using the DE10-Nano board, then the edge-detection mechanism and video-out port
are connected to the Onchip memory (the DE10-Nano board does not include SDRAM). When the
SDRAM memory is being used, the edge-detection mechanism assumes that the image size is
$640 \times 480$ pixels, and the image is stored in the memory starting at address
\texttt{0xC0000000}. The edge-detected output image is saved to the address \texttt{0xC2000000}.
When the Onchip memory is being used, the image size is $320 \times 240$ pixels. The
original image is stored at address \texttt{0xC8000000}, and the edge-detected result
{\it overwrites} the original and is therefore stored at the same address.

~\\
\noindent
The DMA controllers shown in Figure~\ref{fig:edge_detect_system}, as well as the video-out port,
require that each pixel in memory is {\it word-aligned}. Every 32 bits in memory should store
one pixel, where bits 31 to 24 are (unused) padding bits, 23 to 16 are the red component,
15 to 8 are green, and 7 to 0 are blue.

~\\
\noindent
For the DE1-SoC and DE10-Standard boards the video-out port is initialized to read pixel
data starting at the address \texttt{0xC0000000} (SDRAM). On the DE10-Nano board the video-out
port is set up to read pixel data from the address \texttt{0xC8000000} (Onchip memory).

~\\
\begin{figure}[H]
   \begin{center}
       \includegraphics[scale = 1.0]{figures/edge_detect_system.png}
   \end{center}
   \caption{The components of the edge-detection system.}
	\label{fig:edge_detect_system}
\end{figure}

\newpage
\noindent Perform the following:

\begin{enumerate}
\item
Reconfigure the FPGA with the \textit{Edge\_Detector\_System.rbf} file. An easy way to
program the FPGA is to execute the Linux command \texttt{/home/root/misc/program\_fpga}
(a description of the FPGA programming process is provided in the appendix of the
tutorial \textit{Using Linux on DE-series Boards}). For this part you will make use of only
the video-out capability of the system; the edge-detection capability will be used in Part III.

\item
Consider the code in Figure~\ref{fig:part2}. It first calls {\it read\_bmp}, shown in
Figure~\ref{fig:skeleton}$a$, to read a bitmap image from a file into a data structure.
The code then generates virtual addresses that allow access to SDRAM memory at physical
address \texttt{0xC0000000}, and the FPGA lightweight bridge at address \texttt{0xFF200000}
(for the DE10-Nano board you would need to use the Onchip memory instead of SDRAM).
The functions {\it open\_physical} and {\it map\_physical} use the {\it /dev/mem} mechanism
and the Linux system function {\it mmap} to provide virtual memory mappings of physical
addresses. More details are provided in the tutorial {\it Using Linux on DE-series Boards}.

\item
You are to write the function {\it memcpy\_consecutive\_to\_padded} to complete the code in
Figure~\ref{fig:part2}. This function has to write a 32-bit value into the SDRAM buffer
corresponding to each 24-bit pixel in the image.

\item
Compile and test your code. Some sample images that have the correct dimensions are provided with
this lab exercise ($640 \times 480$ pixels for the DE1-SoC and DE10-Standard boards, and $320
\times 240$ for the DE10-Nano). You should see the bitmap image, upside down, on the video
display.

\item
Write a function called {\it flip} that flips the image vertically before writing it into
the SDRAM buffer. Test your code to see that the image is now displayed right-side up.

\end{enumerate}

\lstset{language=C,numbers=none,escapechar=|,basicstyle=\small\ttfamily,}
\begin{figure}[h]
\begin{center}
\begin{minipage}[t]{15.5 cm}
\begin{lstlisting}[name=part2]
int main(int argc, char *argv[]){
   struct pixel *data;		// used to hold the image pixels
   byte *header;				// used to hold the image header
	int width, height;		// image size
   int fd = -1;				// used to open/read/etc. the image file
	void *SDRAM_virtual;
	void *LW_virtual;

	// Pointer to the DMA controller for the original image
   volatile unsigned int *mem_to_stream_dma = NULL;

   // Check inputs
   if (argc < 2){
      printf ("Usage: edgedetect <BMP filename>\n");
      return 0;
   }
   // Open input image file (24-bit bitmap image)
   if (read_bmp (argv[1], &header, &data, &width, &height) < 0){
      printf ("Failed to read BMP\n");
      return 0;
   }
	printf ("Image width = %d pixels, Image height = %d pixels\n", width, height);

   if ((fd = open_physical (fd)) == -1)   // Open /dev/mem
      return (-1);
   SDRAM_virtual = map_physical (fd, 0xC0000000, 0x03FFFFFF);
   LW_virtual = map_physical (fd, 0xFF200000, 0x00005000);
	if ((LW_virtual == NULL) || (SDRAM_virtual == NULL))
      return (0);

	// Set up pointer to edge-detection DMA controller
   mem_to_stream_dma = (volatile unsigned int *)(LW_virtual + 0x3100);
   *(mem_to_stream_dma+3) = 0; // Turn off edge-detection hardware DMA

   // Write the image to the memory used for video-out and edge-detection
   memcpy_consecutive_to_padded (data, SDRAM_virtual, width*height);

   free(header);
   free(data);

	unmap_physical (SDRAM_virtual, 0x03FFFFFF);	// release mem mapping
	unmap_physical (LW_virtual, 0x00005000);		// release mem mapping
	close_physical (fd);									// close /dev/mem

   return 0;
}
\end{lstlisting}
\end{minipage}
\caption{The software code for Part II.}
\label{fig:part2}
\end{center}
\end{figure}

\section*{Part III}

For this part you are to extend your program from Part II so that it makes use of the
hardware edge-detection mechanism. You will need to access the programming registers of
the DMA controllers, which are illustrated in Figure~\ref{fig:pixel_ctrl}.
The register at the \texttt{Base} address is called the {\it Buffer} register, and the one
at address \texttt{Base+4} is the {\it Backbuffer} register. Each of these registers stores
the address of a memory buffer.  The \texttt{Buffer} register stores the address of the
buffer that is {\it currently} being used by the DMA controller.

~\\
\noindent
The operation of the DMA controller can be turned {\it off} by writing the value \texttt{0}
into the {\it Status} register, at address \texttt{Base+12}. Writing the value \texttt{0x4}
turns the DMA controller {\it on}, so that it performs transfers from/to memory starting at
the address in the {\it Buffer} register.

~\\
\noindent
It is possible for software to directly write into the {\it Backbuffer} register to change
its contents, but not the {\it Buffer} register. To change the {\it Buffer} register it is
necessary to perform a {\it swap} operation, explained below.

~\\
\noindent
A buffer register swap is caused by writing the value \texttt{1} to the {\it Buffer}
register. This write operation does not directly modify the content of
the {\it Buffer} register, but instead causes the contents of the {\it Buffer}
and {\it Backbuffer} registers to be swapped. The swap operation does not happen right away;
it occurs at the end of the current DMA operation, when all pixels have been transferred.
Software can poll the value of the $S$ bit in the {\it Status} register to see when a DMA
operation has been completed (an entire image has been processed). Writing the value 1 into
the {\it Buffer} register causes $S$ to be set to 1. Then, when the DMA operation is
completed, $S$ is reset back to 0.

~\\
\noindent
The addresses of the programming registers for the three DMA controllers shown in
Figure~\ref{fig:edge_detect_system} are given in Table~\ref{tab:DMA_addr}. The last two
columns in the table give the initial contents of
the {\it Buffer} and {\it Backbuffer} registers for
each DMA. The columns labeled SDRAM and Onchip show the contents when the SDRAM memory or
Onchip memory are being used, respectively.  For the video-port DMA controller,
the {\it Buffer} address is set to the start of memory, and the {\it Backbuffer} address
points to the start of the edge-detected image. Performing a swap operation allows either
the original image or the generated edge-detected image to be displayed.

\clearpage
\newpage
\begin{figure}[h!]
   \begin{center}
       \includegraphics{figures/fig_DMA_ctrl.pdf}
   \end{center}
   \caption{DMA controller registers.}
	\label{fig:pixel_ctrl}
\end{figure}

\begin{table}[h]
\begin{center}
\begin{tabular}{l|c|l|c|c}
\textbf{DMA} & \textbf{Address} & \textbf{Register} & \textbf{SDRAM} & \textbf{Onchip}\\ \hline
 \rule{0cm}{12pt}Video-out & \texttt{0xFF203020} & Buffer & \texttt{0xC0000000} & \texttt{0xC8000000} \\
 & \texttt{0xFF203024} & Backbuffer & \texttt{0xC2000000} & \texttt{0xC8000000} \\
 & \texttt{0xFF203028} & Resolution &  & \\
 & \texttt{0xFF20302C} & Status &  & \\ \hline
 \rule{0cm}{12pt}Mem-to-Stream & \texttt{0xFF203100} & Buffer & \texttt{0xC0000000}
 & \texttt{0xC8000000} \\
 & \texttt{0xFF203104} & Backbuffer & \texttt{0xC0000000} & \texttt{0xC8000000} \\
 & \texttt{0xFF203108} & Resolution &  & \\
 & \texttt{0xFF20310C} & Status & & \\ \hline
 \rule{0cm}{12pt}Stream-to-Mem & \texttt{0xFF203120} & Buffer & \texttt{0xC2000000}
 & \texttt{0xC8000000} \\
 & \texttt{0xFF203124} & Backbuffer & \texttt{0xC2000000} & \texttt{0xC8000000} \\
 & \texttt{0xFF203128} & Resolution &  & \\
 & \texttt{0xFF20312C} & Status &  & \\
\end{tabular}
\caption{DMA register addresses.}
\label{tab:DMA_addr}
\end{center}
\end{table}

\noindent
Your program should do the following:
\begin{enumerate}
\item Disable the {\it Mem-to-Stream} and {\it Stream-to-Mem} DMA controllers. Recall that
you will first need to obtain virtual addresses for accessing the physical addresses in
Table~\ref{tab:DMA_addr}. Refer to the tutorial {\it Using Linux on DE-series Boards} if needed.
\item Copy the pixels of the input image to memory at address \texttt{0xC0000000}
(or \texttt{0xC8000000}).  The bitmap image should now appear on the video display.
\item Enable the DMAs to start the edge-detection operation. Then, perform a swap operation and
wait until both DMA controllers are finished.
\item Disable the DMAs.
\item Perform a swap operation for the video DMA, so that the edge-detected image appears
on the display (not necessary for the DE10-Nano, because the result overwrites the original).
\item Save the edge-detected image into a file \textit{edges.bmp}, for later display.
\item Test your program by using the images provided with this lab exercise. For the
DE1-SoC and DE10-Standard boards $640 \times 480$ images are provided, and for the
DE10-Nano $320 \times 240$ images are included. Compare the run-time of your program with
the software-only solution from Part I, to see the benefits of using hardware acceleration.
\end{enumerate}

~\\
\noindent
\input{\CommonDocsPath/copyright.tex}

\end{document}


\documentclass[11pt,a4paper]{report}
\usepackage{amsmath,amsfonts,amssymb,amsthm,epsfig,epstopdf,titling,url,array}
\usepackage{enumitem}
\usepackage{changepage}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{listings}
\usepackage{color}
\theoremstyle{plain}
\newtheorem{thm}{Theorem}[section]
\newtheorem{lem}[thm]{Lemma}
\newtheorem{prop}[thm]{Proposition}
\newtheorem*{cor}{Corollary}
\theoremstyle{definition}
\newtheorem{defn}{Definition}[section]
\newtheorem{conj}{Conjecture}[section]
\newtheorem{exmp}{Example}[section]
\newtheorem{exercise}{Exercise}[section]
\theoremstyle{remark}
\newtheorem*{rem}{Remark}
\newtheorem*{note}{Note}
\def\changemargin#1#2{\list{}{\rightmargin#2\leftmargin#1}\item[]}
\let\endchangemargin=\endlist

\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}

\lstdefinestyle{mystyle}{
	backgroundcolor=\color{backcolour},
	commentstyle=\color{codegreen},
	keywordstyle=\color{magenta},
	numberstyle=\tiny\color{codegray},
	stringstyle=\color{codepurple},
	basicstyle=\footnotesize,
	breakatwhitespace=false,
	breaklines=true,
	captionpos=b,
	keepspaces=true,
	numbers=left,
	numbersep=5pt,
	showspaces=false,
	showstringspaces=false,
	showtabs=false,
	tabsize=2
}

\lstset{style=mystyle}
\begin{document}

\section*{Problem}
Moe is driving to visit his brother Joe.  They live in one of those awful East Coast burgs where you have to pay tolls to drive anywhere.  He stops at a toll booth at noon and gets a ticket (old school, no EZ-pass).  The timestamp on the ticket says 12:00PM.  An hour later he has to stop again to pay another toll.  It turns out that the other toll booth is exactly 60 miles from the last one.  He arrives there at exactly 1:00PM.  He gives the public servant in the tollbooth the ticket and, to his surprise, he gets a speeding citation. He says, “Dude, the speed limit is 60MPH. I went 60 miles in an hour.  What is your problem?”  Explain what is going on here and why.

\textit{Source:} This was adapted from an example in  \href{https://www.cartalk.com}{Car Talk}

\section*{Solution}
\textit{Intuitive, non-calculus answer:} Moe's average speed over the hour was 60 mph.  Since he started from rest and ended at rest, there must have been some time interval over which his speed was less than 60mph.  But if he never exceeded 60mph, he could never "make up" the lost distance from the time when he was accelerating or decelerating.

\textit{Calculus answer: } Let $s(t)$ be the distance Moe's car has traveled at time $t$ minutes, so $s(0) = 0$ and $s(60)= 60$.  Let $v(t) = s'(t)$ be Moe's velocity at time $t$ in minutes (so $v(t)$ is measured in miles / minute).  Then $s(t) = \int_{0}^{t} v(u) du$. Since Moe had to accelerate to 60 mph, there has to be some $t_0>0$ such that for $0 < u < t_0$, we have $v(u) \leq 50$.  Then $s(60) = \int_{0}^{60} v(u) du = \int_{0}^{t_0} v(u) du + \int_{t_0}^{60} v(u) du$.  But each of these integrals is bounded above by the maximum value of the function over the interval times the length of the interval, so $\int_{0}^{t_0} v(u) du + \int_{t_0}^{60} v(u) du \leq (5/6) t_0 + 1(60 - t_0) < 60$ This means that under the assumption that Moe's velocity never exceeded 60mph, he must have traveled a distance strictly less than 60 miles.

\textit{Bonus question: } Suppose Moe was driving a 1952 Studebaker that goes from 0 to 60 in one minute.  Assume his acceleration is linear - i.e., after 10 seconds he is going 10 mph, after 20 seconds 20 mph, 30 seconds 30 mph, etc. - and he goes at a constant speed once he gets to 60mph.  Assume his deceleration at the end is also linear. How far could he go in an hour with this speed regimen (one minute accelerating to 60, 58 minutes at 60, 1 minute decelerating to 0)?
\end{document}


\documentclass[10pt]{beamer}
\usepackage{ragged2e}
\usepackage{tfrupee}
\usepackage{xcolor,colortbl}
\usepackage{hyperref}
\usepackage{booktabs}
\usepackage{ccicons}
\hypersetup{
colorlinks=true,
urlcolor= red}
\usetheme[               % right of left position of sidebar (default is right)
  ]{Aalborg}

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage{helvet}
\newcommand{\gray}{\rowcolor[gray]{.05}}
\definecolor{gold}{rgb}{0.85,.66,0}
 \definecolor{khaki}{rgb}{0.941176,0.901961,0.549020}
\definecolor{saffron}{rgb}{0.96, 0.77, 0.19}
\definecolor{sand}{rgb}{0.76, 0.7, 0.5}
\definecolor{ablue}{rgb}{0.94, 0.97, 1.0}
\definecolor{cgreen}{rgb}{0.0, 0.42, 0.24}
\setbeamercolor{bgcolor}{fg=black,bg=ablue}
\setbeamercolor{separation line}{use=structure,bg=structure.fg!20!bg}
\setbeamercolor{block body}{fg=black,bg=ablue}
\setbeamercolor{footlinecolor}{fg=white,bg=sand}
\newenvironment<>{varblock}[2][.9\textwidth]{%
  \setlength{\textwidth}{#1}
  \begin{actionenv}#3%
    \def\insertblocktitle{#2}%
    \par%
    \usebeamertemplate{block begin}}
  {\par%
    \usebeamertemplate{block end}%
  \end{actionenv}}

\newcommand{\ma}{\textbf{Maxima {}}}
\newcommand{\wma}{\textit{WxMaxima {}}}

\setbeamercolor{normal text}{fg=black}

\newcommand{\chref}[2]{%
  \href{#1}{{\usebeamercolor[bg]{Aalborg}#2}}%
}

\title[The CAS Workshop]
{ Workshop on\\ \textbf{{\huge Computer Algebra System (CAS)}}\vspace{0.2cm}}

\subtitle{\textbf{Session: Solving Equations with CAS}}  % could also be a conference name

%\date{\today}
\date{10. 04. 2016}

\author[\ccbyncndeu$\,$ P. K. Yadav] % optional, use only with lots of authors
{
	\textbf{P. K. Yadav \& K. Taneja}\\
	\href{mailto:khusboo.taneja@sharda.ac.in}{{\tt khusboo.taneja@sharda.ac.in}}
}

\institute[
  Dept.\ of Civil Engineering\\
  Dept.\ of Computer Sci. \& Engg.\\
  Sharda University\\]
{
  Department of Civil Engineering\\
  Dept.\ of Computer Sci. \& Engg.\\
}

\pgfdeclareimage[height=0.5cm]{mainlogo}{fig/logo.png} % placed in the upper left/right corner
\logo{\pgfuseimage{mainlogo}}

\pgfdeclareimage[height=1.5cm]{titlepagelogo}{fig/logo.png} % placed on the title page

\titlegraphic{% is placed on the bottom of the title page
  \pgfuseimage{titlepagelogo}

}

\begin{document}
% the titlepage
{\aauwavesbg
\begin{frame}[plain,noframenumbering] % the plain option removes the sidebar and header from the title page
  \titlepage
\end{frame}}

\section{Motivation}
% motivation for creating this theme
\begin{frame}{Motivation}{}
\begin{block}{Solving Equations with CAS}
\justifying
\vspace{0.5cm}
Engineering and Science  is all about equations. We have different types of equations: Algebraic (polynomial), parametric equations, the calculus equations- differential equations, integral equations etc.\\
\vspace{0.2cm}

The actual Engineering or Scientific challenge is finding the solution of the equations.\\
\vspace{0.2cm}
The challenge has become bigger due to bigger Engineering or Scientific demand.\\
\vspace{0.2cm}
The use of computer can now let us solve equations more efficiently and CAS is one of the best ``Analytical" tool as opposed to ``Numerical'' Tool- e.g., MATLAB, Numpy etc.\\
\vspace{0.2cm}
We now learn to use CAS \ma for solving  equations.

\end{block}
\end{frame}

\section{Solve with solve}

\begin{frame}[fragile]{The solve function}{}
\begin{block}{ Solving Equation and Equations}
\justifying
The functions:\\
\begin{enumerate}
\item \textbf{\textcolor{red}{solve(eqn, var)}}\\
\item \textbf{\textcolor{red}{solve([eqn1, eqn2,\ldots], [var1, var2,\dots])}}\\
\end{enumerate}

 solves the \textbf{algebraic} equation (expression or function)  for the variable (in 1) or variables (in 2) \textbf{var} in equation (in 1) or equations (in 2) and returns a \textbf{list} of solutions in \textbf{var}.\\
\vspace{0.2cm}

If \verb|expr| is not an `equation', the equation \verb|expr= 0| is assumed. \\
\vspace{0.2cm}

Variants of the \verb|solve| and related function can be found using \verb|appropos(solve)| and described using, e.g., \verb|describe(solve)|.
\\
\vspace{0.2cm}
Let us learn the \verb|solve| functions from examples.

\end{block}
\end{frame}

\begin{frame}[fragile]{The MAXIMA CAS}{}
\begin{block}{The function solve(eq, var) \vspace{0.2cm} }
\justifying
1. The quadratic equation (you all know this!):\\

 \begin{beamercolorbox}[rounded=true, left, shadow=true,wd=9cm, colsep=1.5pt]{upper separation line foot}
 \vspace{-0.1cm}
\begin{minipage}[t]{8ex}{\color{red}\bf
\begin{verbatim}
(%i1) solve(a*x^2+b*x+c=0,x);
\end{verbatim}}
\end{minipage}

\vspace{0.05cm}

\definecolor{labelcolor}{RGB}{100,0,0}
$$
(\%o1)\quad \left[ x=-{{\sqrt{b^2-4\,a\,c}+b}\over{2\,a}} , x={{\sqrt{b^2-4\,a \,c}-b}\over{2\,a}} \right]
$$

\end{beamercolorbox}

\vspace{0.2cm}
let us define, $a, b\, \textrm{and}\, c$ and find the numerical value of $x$.

 \begin{beamercolorbox}[rounded=true, left, shadow=true,wd=9cm, colsep=1.5pt]{upper separation line foot}
 \vspace{-0.1cm}
\begin{minipage}[t]{8ex}{\color{red}\bf
\begin{verbatim}
(%i1) [a,b,c]: [5,3,2];
\end{verbatim}}
\end{minipage}

\vspace{0.05cm}

\definecolor{labelcolor}{RGB}{100,0,0}
$$
(\%o1)\quad \left[ x=-2, x=-1 \right]
$$

\end{beamercolorbox}

You may want to check your solution function \textcolor{red}{ev(eq1,sol)}. The \verb|eq1| is your equation and \verb|sol| is the solution.

\end{block}
\end{frame}

\begin{frame}[fragile]{The solve function}{}
\begin{block}{The function solve(eq, var) \vspace{0.2cm} }
\justifying
OK, that was easy, now \\
\begin{enumerate}
\item  Let us try to solve the cubic equation: $ax^3+bx^2+cx+d = 0$ in \wma, and\\\vspace{0.1cm}
\item The quartic equation $ax^4+bx^3+cx^2+d*x + e = 0$
\end{enumerate}
\vspace{0.2cm}
You may want to use $[a, b, c, d] : [6, -3, 1, -1 ] $ and $e = 125$\\
\vspace{0.2cm}
And, get the numerical values using \verb|numer| or \verb|float| function.\\
\vspace{0.2cm}

You may get a complex result.

\end{block}
\end{frame}

\begin{frame}[fragile]{The solve function}{}
\begin{block}{The function solve([eq1,eq2,...], [var1,var2,...]) \vspace{0.2cm} }
\justifying
Now we attempt to solve set of equations using solve. The \verb|solve| function will now include all equations separated by `\textbf{\textcolor{red}{,}}' and enclosed in \textbf{\textcolor{red}{[\hspace{0.2cm}]}}. The same is done for variables.\\
\vspace{0.2cm}
Let us look at an example\\
\vspace{0.2cm}

 \begin{beamercolorbox}[rounded=true, left, shadow=true,wd=6cm, colsep=1.5pt]{upper separation line foot}
 \vspace{-0.1cm}
\begin{minipage}[t]{8ex}{\color{red}\bf
\begin{verbatim}
(%i1) eq2: [3*x+2*y=5, 6*x+y=0]
\end{verbatim}}
\end{minipage}

\vspace{0.05cm}

\definecolor{labelcolor}{RGB}{100,0,0}
$$
(\%o1)\quad \left[ x=-\frac{5}{9}, x=\frac{10}{3} \right]
$$

\end{beamercolorbox}
\vspace{0.2cm}
How about solving: $\sqrt{x}+y=0 \, \textrm{and} \, \sqrt{x}=1\, \textrm{for}\, x \, \textrm{and}\, y$\\
\vspace{0.2cm}

For that you will have to use another function called:\\
\verb|to_poly_solve|. Check the \wma for more.

\vspace{0.2cm}

You may want to learn more on that by yourself.

\end{block}
\end{frame}

\section{Engineering Problems}
\subsection{Decay}
\begin{frame}[fragile]{The solve function}{}
\begin{block}{The Engineering Problems- Decay \vspace{0.2cm} }
\justifying
The radioactive decay model is:

$$
DEq:q=q_0\exp\frac{-t}{\tau}
$$

We can find the rate of reaction ($\tau$) by first solving the equation using \verb|solve| function and substituting the values $q_0 = 10 g, q = 4 g \, \textrm{and} \,t= 2s$ using another function \textcolor{red}{subst([val1, val2,\ldots], sol)}. \\

\vspace{0.2cm}

We should get $\tau = 2.18$. \\
\vspace{0.2cm}

Now if half-life ($t_{1/2}$) is to be found, we can use the relation
$$
t_{1/2} = \frac{\ln(2)}{\tau}
$$

We obtain $t_{1/2} = 0.317 $

\end{block}
\end{frame}

\subsection{Motion Trajectory }
\begin{frame}[fragile]{The solve function}{}
\begin{block}{The Engineering Problems-  The Motion Trajectory \vspace{0.2cm} }
\justifying
\textbf{The two-dimensional motion under constant acceleration}\\
\vspace{0.1cm}

Let a ball is moving with constant acceleration in the $y-$
direction only (see Figure). The equations for the position of the ball in the \textit{x} and \textit{y} directions at any time \textit{t} are given by equations EqX and EqY:

\begin{columns}
\column{.5\textwidth}
EqX: $x =x_0+v_0\cos\theta t $\\
and\\
\vspace{0.2cm}
EqY: $y=y_0+v_0\sin\theta t+\frac{1}{2}at^2 $\\
\vspace{0.2cm}
$v_0$ (the initial velocity) and $a$ (the acceleration), have to be obtained provided that initial position ($x_0,y_0$), $\theta$ and $t$ are known.

\column{.5\textwidth}
\includegraphics[width = 5cm]{fig1}
\end{columns}

\end{block}
\end{frame}

\begin{frame}[fragile]{The solve function}{}
\begin{block}{The Motion Trajectory \vspace{0.2cm} }
\justifying

Using function \verb|solve|, we can solve two simultaneous equation $EqX$ and $EqY$ for $v_0$ and $a$

 \begin{beamercolorbox}[rounded=true, left, shadow=true,wd=9cm, colsep=1.5pt]{upper separation line foot}
 \vspace{-0.1cm}
\begin{minipage}[t]{8ex}{\color{red}\bf
\begin{verbatim}
(%i1) SolXY: solve([EqX,EqY], [v0, a])
\end{verbatim}}
\end{minipage}

\vspace{0.05cm}

\definecolor{labelcolor}{RGB}{100,0,0}
$$
(\%o1)\qquad v0=-\frac{x0-x}\cos(\theta)t\,,
$$
$$
a=\frac{\cos(\theta)2y-2y0 +2\sin(\theta)x0-2\sin (\theta)x}{{t}^{2}\cos(\theta)}
$$
\end{beamercolorbox}
\vspace{0.1cm}
Let us use  $x0 = 0, x = 2 m, y0 = 2 m, y = 8 m, \theta = \pi/6,
\,\textrm{and}\, t = 2 s$, then substituting them we get $v0$ and $a$

$$
v0=1.154 m/s\, \text{and}\, a= 2.422 m/s^2
$$

Check them in \wma.

\end{block}
\end{frame}

\begin{frame}[fragile]{The solve function}{}
\begin{block}{The Motion Trajectory \vspace{0.2cm} }
\justifying

Few notes on the trajectory problem before we move to another problem:
\begin{enumerate}[A)]
\item \verb|solve| will not be able to obtain solution for $theta$, because it is not algebraic and can not be linearly isolated.

\item A solution for $x0$ and $t$ is allowed because both terms are algebraic in the
equations, even if $t$ is quadratic.

\end{enumerate}

For the case A): a numerical solution using function \verb|find_root| can be used after substituting all the known values in the equations.\\
\vspace{0.2cm}
You may want to try the above in \wma.

\end{block}
\end{frame}

\subsection{Open channel}
\begin{frame}[fragile]{The solve function}{}
\begin{block}{The Engineering Problems-  The open channel problem  \vspace{0.2cm} }
\justifying

Let us solve the Manning's equation for a circular open channel.\\
\vspace{0.2cm}
The cross-section of a circular channel is characterized by its diameter \textit{D}, and its depth \textit{y}. These two variables are related by
the half-angle $\beta$, such that $\cos(\beta) = 1-2(y/D)$.
\vspace{0.3cm}
\begin{columns}
\column{0.5\textwidth}

Let us start with Manning's equation:\\
$$\textrm{EqM}: v = \frac{kR^{2/3}S^{1/2}}{n}$$
\vspace{0.2cm}

\column{.5\textwidth}
\includegraphics[width = 5cm]{fig2}
\end{columns}

\end{block}
\end{frame}

\begin{frame}[fragile]{The solve function}{}
\begin{block}{The open channel problem  \vspace{0.2cm} }
\justifying

Next, we define the continuity equation, EqQ.\\
$$
\textrm{EqQ}: Q = Av
$$

And, then combine two equations using \verb|subst| function
$$
\textrm{EqMQ}:subst(EqM,EqQ)
$$
Next, we substitute the definition of the hydraulic radius:
$$
\textrm{EqMQ}:subst(R=A/P,EqMQ)
$$

\end{block}
\end{frame}

\begin{frame}[fragile]{The solve function}{}
\begin{block}{The open channel problem  \vspace{0.2cm} }
\justifying

Next, we substitute the definitions of the area, \textit{A}, and wetted perimeter, \textit{P}, for a circular
cross-section in terms of the half-angle $\beta$ to produce equation EqMQC:

$$
\textrm{EqMQC}: subst([A=\frac{D^2}{4}(\beta-\sin(\beta)\cos(\beta)),P=\beta D], EqMQ)
$$

Next, we replace the half-angle $\beta$ in terms of the depth $y$ and diameter $D$, to produce equation EqMQCy:
$$
\textrm{EqMQCy}: subst(beta=\textrm{acos}(1-2y/D),EqMQC)
$$

Finally, we substitute the parameters of the problem as follows, $k = 1.486, D = 5 ft, Q =
2.5 ft^3/s, S = 0.000023, and n = 0.012$, to create equation

\end{block}
\end{frame}
\subsubsection{find\_root function}
\begin{frame}[fragile]{The find\_root function}{}
\begin{block}{The open channel problem  \vspace{0.2cm} }
\justifying

\begin{align*}
\textrm{EqMQCy1}&: subst([k=1.486, D=5, Q=2.5, S=0.000023,\\ & \qquad \qquad n=0.012], EqMQCy)
\end{align*}

This is the equation we need to solve for $y$. The equation is not algebraic (see $\arccos$), and therefore the \verb|solve| function will not work. Hence, a new function: $ \color{red} find\_root(exp, var, a, b) $ is introduced.\\
\vspace{0.2cm}
The \verb|exp| = expression,\\
The \verb|var| = the variable\\
The \verb|a and b| = the limit within which the root is to be searched.\\

\end{block}
\end{frame}

\begin{frame}[fragile]{The solve function}{}
\begin{block}{The open channel problem  \vspace{0.2cm} }
\justifying

\textbf{Question}: Which interval contains the root ($f(x)=0$)?\\
\vspace{0.2cm}
We need to plot the problem for an easy answer. Let us do that.\\
\vspace{0.2cm}
For plotting, we use
\textcolor{red}{\textbf{wxplot2d(fn,[y,0,5])}}\\
\vspace{0.2cm}
\begin{columns}
\column{0.5\textwidth}

The plot shows that \verb|fn=0| will be between 1 and 2. We use this as our interval.

\vspace{0.2cm}

\column{.5\textwidth}
\includegraphics[width = 5.5cm]{fig3}
\end{columns}

Finally, we find the critical depth or $y$, using:
find\_root(fn=0, y, 1,2) and get, $\color{red} y = 1.45$

\end{block}
\end{frame}

\begin{frame}[fragile]{Final Thoughts}{}
\begin{block}{Conclusions \vspace{0.2cm} }
\justifying

This was a very brief introduction to the solving of equation using \ma.\\
\vspace{0.2cm}

\ma can be used to solve varieties of ODE, and some PDE. More detail on it can be
found in the \ma manual.\\
\vspace{0.2cm}
Moreover, the \wma provide us with a very handy interface to solve mathematical problems intuitively.\\
\vspace{0.2cm}

You may want to check following function in the \ma manual:\\\verb| ode2, linsolve, dsolve| for solving different types of equations.\\
\vspace{0.2cm}

We realized the importance of graphics when solving a complicated problem. We next focus on plotting.

\end{block}
\end{frame}

{\aauwavesbg%
\begin{frame}[plain,noframenumbering]%
  \finalpage{\huge That was introduction to Solving Eqautions using \ma. Let us get advanced \\ \vspace{0.3cm}\textbf{\textcolor{yellow}{and learn to visualize maths.}}}
\end{frame}}

\end{document}


   \section{Secure Coding : INT06-A. Use strtol() to convert a string token to an integer}

   Use {\tt strtol()} or a related function to convert a string token to an integer. The {\tt strtol()}, {\tt strtoll()}, {\tt strtoul()}, and {\tt strtoull()} functions convert the initial portion of a string token to {\tt long int}, {\tt long long int}, {\tt unsigned long int}, and {\tt unsigned long long int} representation, respectively. These functions provide more robust error handling than alternative solutions.
   \subsection{Non-Compliant Example}

   This non-compliant code example converts the string token stored in the static array {\tt buff} to a signed integer value using the {\tt atoi()} function.
 \code{

\noindent
\ttfamily
\hlstd{}\hlline{\ \ \ \ 1\ }\hlstd{}\hltyp{int\ }\hlstd{si;\\
}\hlline{\ \ \ \ 2\ }\hlstd{\\
}\hlline{\ \ \ \ 3\ }\hlstd{}\hlkey{if\ }\hlstd{}\hlsym{(}\hlstd{argc\ $>$\ }\hlnum{1}\hlstd{}\hlsym{)\ \{\\
}\hlline{\ \ \ \ 4\ }\hlsym{\hlstd{\ \ }}\hlstd{si\ =\ atoi}\hlsym{(}\hlstd{argv}\hlsym{[}\hlstd{}\hlnum{1}\hlstd{}\hlsym{])}\hlstd{;\\
}\hlline{\ \ \ \ 5\ }\hlstd{}\hlsym{\}\\
}\hlline{\ \ \ \ 6\ }\hlsym{}\hlstd{}\\
\mbox{}\\
\normalfont

}

   The {\tt atoi()}, {\tt atol()}, and {\tt atoll()} functions convert the initial portion of a string token to {\tt int}, {\tt long int}, and {\tt long long int} representation, respectively. Except for the behavior on error, they are equivalent to
 \code{

\noindent
\ttfamily
\hlstd{}\hlline{\ \ \ \ 1\ }\hlstd{atoi:\ }\hlsym{(}\hlstd{}\hltyp{int}\hlstd{}\hlsym{)}\hlstd{strtol}\hlsym{(}\hlstd{nptr,\ }\hlsym{(}\hlstd{}\hltyp{char\ }\hlstd{**}\hlsym{)}\hlstd{NULL,\ }\hlnum{10}\hlstd{}\hlsym{)\\
}\hlline{\ \ \ \ 2\ }\hlsym{}\hlstd{atol:\ strtol}\hlsym{(}\hlstd{nptr,\ }\hlsym{(}\hlstd{}\hltyp{char\ }\hlstd{**}\hlsym{)}\hlstd{NULL,\ }\hlnum{10}\hlstd{}\hlsym{)\\
}\hlline{\ \ \ \ 3\ }\hlsym{}\hlstd{atoll:\ strtoll}\hlsym{(}\hlstd{nptr,\ }\hlsym{(}\hlstd{}\hltyp{char\ }\hlstd{**}\hlsym{)}\hlstd{NULL,\ }\hlnum{10}\hlstd{}\hlsym{)\\
}\hlline{\ \ \ \ 4\ }\hlsym{}\hlstd{}\\
\mbox{}\\
\normalfont

}

   Unfortunately, {\tt atoi()} and related functions lack a mechanism for reporting errors for invalid values. Specifically, the {\tt atoi()}, {\tt atol()}, and {\tt atoll()} functions:
   \subsection{Non-Compliant Example}

   This non-compliant example uses the {\tt sscanf()} function to convert a string token to an integer. The {\tt sscanf()} function has the same problems as {\tt atoi()}.
 \code{

\noindent
\ttfamily
\hlstd{}\hlline{\ \ \ \ 1\ }\hlstd{}\hltyp{int\ }\hlstd{si;\\
}\hlline{\ \ \ \ 2\ }\hlstd{\\
}\hlline{\ \ \ \ 3\ }\hlstd{}\hlkey{if\ }\hlstd{}\hlsym{(}\hlstd{argc\ $>$\ }\hlnum{1}\hlstd{}\hlsym{)\ \{\\
}\hlline{\ \ \ \ 4\ }\hlsym{\hlstd{\ \ }}\hlstd{sscanf}\hlsym{(}\hlstd{argv}\hlsym{[}\hlstd{}\hlnum{1}\hlstd{}\hlsym{]}\hlstd{,\ }\hlstr{"\%d"}\hlstd{,\ \&si}\hlsym{)}\hlstd{;\\
}\hlline{\ \ \ \ 5\ }\hlstd{}\hlsym{\}\\
}\hlline{\ \ \ \ 6\ }\hlsym{}\hlstd{}\\
\mbox{}\\
\normalfont

}

   \subsection{Compliant Solution}

   This compliant example uses {\tt strtol()} to convert a string token to an integer value and provides error checking to make sure that the value is in the range of {\tt int}.
 \code{

\noindent
\ttfamily
\hlstd{}\hlline{\ \ \ \ 1\ }\hlstd{}\hltyp{long\ }\hlstd{sl;\\
}\hlline{\ \ \ \ 2\ }\hlstd{}\hltyp{int\ }\hlstd{si;\\
}\hlline{\ \ \ \ 3\ }\hlstd{}\hltyp{char\ }\hlstd{*end\textunderscore ptr;\\
}\hlline{\ \ \ \ 4\ }\hlstd{\\
}\hlline{\ \ \ \ 5\ }\hlstd{}\hlkey{if\ }\hlstd{}\hlsym{(}\hlstd{argc\ $>$\ }\hlnum{1}\hlstd{}\hlsym{)\ \{\\
}\hlline{\ \ \ \ 6\ }\hlsym{\\
}\hlline{\ \ \ \ 7\ }\hlsym{\hlstd{\ \ }}\hlstd{errno\ =\ }\hlnum{0}\hlstd{;\\
}\hlline{\ \ \ \ 8\ }\hlstd{\\
}\hlline{\ \ \ \ 9\ }\hlstd{\hlstd{\ \ }sl\ =\ strtol}\hlsym{(}\hlstd{argv}\hlsym{[}\hlstd{}\hlnum{1}\hlstd{}\hlsym{]}\hlstd{,\ \&end\textunderscore ptr,\ }\hlnum{10}\hlstd{}\hlsym{)}\hlstd{;\\
}\hlline{\ \ \ 10\ }\hlstd{\\
}\hlline{\ \ \ 11\ }\hlstd{\hlstd{\ \ }}\hlkey{if\ }\hlstd{}\hlsym{(}\hlstd{ERANGE\ ==\ errno}\hlsym{)\ \{\\
}\hlline{\ \ \ 12\ }\hlsym{\hlstd{\ \ \ \ }}\hlstd{puts}\hlsym{(}\hlstd{}\hlstr{"number\ out\ of\ range}\hlesc{$\backslash$n}\hlstr{"}\hlstd{}\hlsym{)}\hlstd{;\\
}\hlline{\ \ \ 13\ }\hlstd{\hlstd{\ \ }}\hlsym{\}\\
}\hlline{\ \ \ 14\ }\hlsym{\hlstd{\ \ }}\hlstd{}\hlkey{else\ if\ }\hlstd{}\hlsym{(}\hlstd{sl\ $>$\ INT\textunderscore MAX}\hlsym{)\ \{\\
}\hlline{\ \ \ 15\ }\hlsym{\hlstd{\ \ \ \ }}\hlstd{printf}\hlsym{(}\hlstd{}\hlstr{"\%ld\ too\ large!}\hlesc{$\backslash$n}\hlstr{"}\hlstd{,\ sl}\hlsym{)}\hlstd{;\\
}\hlline{\ \ \ 16\ }\hlstd{\hlstd{\ \ }}\hlsym{\}\\
}\hlline{\ \ \ 17\ }\hlsym{\hlstd{\ \ }}\hlstd{}\hlkey{else\ if\ }\hlstd{}\hlsym{(}\hlstd{sl\ $<$\ INT\textunderscore MIN}\hlsym{)\ \{\\
}\hlline{\ \ \ 18\ }\hlsym{\hlstd{\ \ \ \ }}\hlstd{printf}\hlsym{(}\hlstd{}\hlstr{"\%ld\ too\ small!}\hlesc{$\backslash$n}\hlstr{"}\hlstd{,\ sl}\hlsym{)}\hlstd{;\\
}\hlline{\ \ \ 19\ }\hlstd{\hlstd{\ \ }}\hlsym{\}\\
}\hlline{\ \ \ 20\ }\hlsym{\hlstd{\ \ }}\hlstd{}\hlkey{else\ if\ }\hlstd{}\hlsym{(}\hlstd{end\textunderscore ptr\ ==\ argv}\hlsym{[}\hlstd{}\hlnum{1}\hlstd{}\hlsym{])\ \{\\
}\hlline{\ \ \ 21\ }\hlsym{\hlstd{\ \ \ \ }}\hlstd{puts}\hlsym{(}\hlstd{}\hlstr{"invalid\ numeric\ input}\hlesc{$\backslash$n}\hlstr{"}\hlstd{}\hlsym{)}\hlstd{;\\
}\hlline{\ \ \ 22\ }\hlstd{\hlstd{\ \ }}\hlsym{\}\\
}\hlline{\ \ \ 23\ }\hlsym{\hlstd{\ \ }}\hlstd{}\hlkey{else\ if\ }\hlstd{}\hlsym{(}\hlstd{}\hlstr{'}\hlesc{$\backslash$0}\hlstr{'}\hlstd{\ !=\ *end\textunderscore ptr}\hlsym{)\ \{\\
}\hlline{\ \ \ 24\ }\hlsym{\hlstd{\ \ \ \ }}\hlstd{puts}\hlsym{(}\hlstd{}\hlstr{"extra\ characters\ on\ input\ line}\hlesc{$\backslash$n}\hlstr{"}\hlstd{}\hlsym{)}\hlstd{;\\
}\hlline{\ \ \ 25\ }\hlstd{\hlstd{\ \ }}\hlsym{\}\\
}\hlline{\ \ \ 26\ }\hlsym{\hlstd{\ \ }}\hlstd{}\hlkey{else\ }\hlstd{}\hlsym{\{\\
}\hlline{\ \ \ 27\ }\hlsym{\hlstd{\ \ \ \ }}\hlstd{si\ =\ }\hlsym{(}\hlstd{}\hltyp{int}\hlstd{}\hlsym{)}\hlstd{sl;\\
}\hlline{\ \ \ 28\ }\hlstd{\hlstd{\ \ }}\hlsym{\}\\
}\hlline{\ \ \ 29\ }\hlsym{\}\\
}\hlline{\ \ \ 30\ }\hlsym{}\hlstd{}\\
\mbox{}\\
\normalfont

}

   If you are attempting to convert a string token to a smaller integer type ({\tt int}, {\tt short}, or {\tt signed char}), then you only need test the result against the limits for that type. The tests do nothing if the smaller type happens to have the same size and representation on a particular compiler.
   \subsection{Risk Assessment}

   While it is relatively rare for a violation of this rule to result in a security vulnerability, it could more easily result in loss or misinterpreted data.

   \begin{tabular}[c]{| c| c| c| c| c| c|}
   \hline
   {\bf Rule} & {\bf Severity} & {\bf Likelihood} & {\bf Remediation Cost} & {\bf Priority} & {\bf Level} \\ \hline
   INT06-A & {\bf 2} (medium) & {\bf 2} (probable) & {\bf 2} (medium) & {\bf P8} & {\bf L2} \\ \hline
   \end{tabular}
   \subsubsection{Related Vulnerabilities}

   Search for vulnerabilities resulting from the violation of this rule on the \htmladdnormallink{CERT website}{https://www.kb.cert.org/vulnotes/bymetric?searchview\&query=FIELD+contains+INT06-A} .
   \subsection{References}

   [ \htmladdnormallink{Klein 02}{https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References} ] [ \\*
   \htmladdnormallink{ISO/IEC 9899-1999}{https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References} ] Section 7.20.1.4, "The strtol, strtoll, strtoul, and strtoull functions," Section 7.20.1.2, "The atoi, atol, and atoll functions," and Section 7.19.6.7, "The sscanf function"


%% It is just an empty TeX file.
%% Write your code here.
\graphicspath{{sec04/images/}{sec04/code/}}
\lstset{inputpath=sec04/code/}

\begin{frame}{Entities}

\begin{enumerate}
    \item Primitive commands
    \item Macros
    \item Counters (=integer numbers)
    \item Lengths
    \item Glues
    \item Boxes
    \item Strings
\end{enumerate}
\incPause
We already see something about all this stuff except counters. Let us look at them! (And then return to look deeper at the boxes, lengths, glues and strings)

\end{frame}

\subsection{Counters}
\begin{frame}{What is ``counter''}\relax

``Counter'' is just an integer number.

It's using in multiple places to count everything in \LaTeX: sections, equations, references, citation, enumerate lists,...

\end{frame}

\begin{frame}{Define and simple manipulation with counters \lW}\relax
\twocolImg{
\lstinputlisting[linerange={11-18}]{countersimp.tex}
}{countersimp}

\begin{itemize}
    \item \ccol\newcounter\ to define new counter
    \item \ccol\setcounter\ to set counter to new value
    \item \ccol\addtocounter\ to add a number to the counter
\end{itemize}

\skfootnote{\lvoc{VII.3.1}[244] \lmanc{12.5}[117] \lmanc{13.4-5}[128] \wikiC{https://en.wikibooks.org/wiki/LaTeX/Counters\#Counter_manipulation}}

\end{frame}

\inclassFrame{

\begin{frame}{Try it out}\relax

     \lstinputlisting{countersimpTASK.tex}

\end{frame}}

\begin{frame}{Print counter\lW}\relax

     \newcommand{\countab}[1]{\newcounter{tmptt}
     \ccol#1\{countname\}&
     \setcounter{tmptt}{1} #1{tmptt} &
     \setcounter{tmptt}{2} #1{tmptt} &
     \setcounter{tmptt}{3} #1{tmptt} &
     \setcounter{tmptt}{4} #1{tmptt} &
     \setcounter{tmptt}{5} #1{tmptt} &
     \setcounter{tmptt}{6} #1{tmptt} &
     \setcounter{tmptt}{7} #1{tmptt} &
     \setcounter{tmptt}{8} #1{tmptt} &
     \setcounter{tmptt}{9} #1{tmptt}
     \\}

     \begin{tabular}{l|ccccccccc}
          \countab{\arabic}
          \countab{\alph}
          \countab{\Alph}
          \countab{\roman}
          \countab{\Roman}
          \countab{\fnsymbol}
     \end{tabular}
     \vspace{1ex}

     P.S. \ccol\value\ to get ``raw'' value of the counter
     \skfootnote{ \wikiC{\https://en.wikibooks.org/wiki/LaTeX/Counters\#Counter_style} \lmac{13.1}[126]\\
     see \lvoc{IX.2.3}[295] for russian analog of \ccol\alph}
\end{frame}

\begin{frame}{pre-defined counters in standart classes}
\newlength{\myboxlen}%
\setlength{\myboxlen}{5em}

\newcommand{\showC}[1]{%
\makebox[\myboxlen]{#1\hfill}%
}

\showC{part}\hfill
\showC{chapter}\hfill
\showC{section}\hfill
\showC{subsection}\hfill
\showC{subsubsection}\hfill
\showC{paragraph}\hfill
\showC{subparagraph}\hfill
\showC{}\hfill
\showC{}\hfill
\showC{}\hfill
\showC{}\hfill
\showC{}\hfill

\showC{page}\hfill
\showC{figure}\hfill
\showC{table}\hfill
\showC{footnote}\hfill
\showC{equation}\hfill

\showC{enumi}\hfill
\showC{enumii}\hfill
\showC{enumiii}\hfill
\showC{enumiv}\hfill
\showC{}\hfill
\showC{}\hfill
\showC{}\hfill
\showC{}\hfill
\showC{}\hfill

\TeX's counters (will talk later)
\showC{\ccol\year}\hfill
\showC{\ccol\month}\hfill
\showC{\ccol\day}\hfill
\showC{\ccol\time}\hfill
\showC{}\hfill
\showC{}\hfill
\showC{}\hfill
\showC{}\hfill
\showC{}\hfill

\skfootnote{\wikiC{https://en.wikibooks.org/wiki/LaTeX/Counters\#LaTeX_default_counters} \lmanc{13}[126]}
\end{frame}

\begin{frame}{Counter Domination\inClass{, conquering, humiliation}}{problem}\relax
\begin{columns}
\begin{column}{0.45\textwidth}
     You may want to write something like

     \vspace{-5ex}
     \includegraphics[width=\linewidth]{counterdom}
\end{column}
\incPause
\begin{column}{0.45\textwidth}
But the straightforward solution will give you

\vspace{-5ex}
\includegraphics[width=\linewidth]{counterdomno}

\end{column}

\end{columns}
\end{frame}

\begin{frame}{Counter Domination\inClass{, conquering, humiliation}}{straightforward solution}\relax

\twocolImg{
\lstinputlisting[linerange={11-20}]{counterdomno.tex}
}{counterdomno}

\inclassFrag{Modify your code so it will look the same way}[0]
\end{frame}

\begin{frame}[fragile]{Counter Domination\inClass{, conquering, humiliation}}{The Way}\relax

\newcommand{\modif}[3]{\fbox{\parbox{\textwidth}{\makebox[\textwidth]{\small\makebox[0.47\textwidth]{#1}\hfill$\to$\hfill\makebox[0.47\textwidth]{#2}}\\ #3}}}

\centering
\modif{\string\newcounter\{task\}}{\ocol\newcounter\{task\}[section]}{\ocol\newcounter\{<slave>\}[<master>] will resets the value of <slave> if the value of <master> is change}

\inclassFrag{Please, modify your code after this and every step in this frame}
% \incPause

\modif{\ccol\addtocounter\{task\}\{1\}}{\ccol\refstepcounter\{task\}}{
\ccol\refstepcounter\{<counter>\} use it to update \ccol\label--\ccol\ref\ mechanism
}

\incPause
\modif{\string\textbf\{Task \string\#\string\arabic\{task\}.}{\tiny\string\textbf\{Task \string\#\string\arabic\{section\}.\string\arabic\{task\}.}{Inside \string\newcommand\{\string\tsk\} to redefine the labels}

\incPause
\modif{}{\tiny\string\renewcommand\{\ccol\thetask\}\{\string\arabic\{section\}.\string\arabic\{task\}\}}{\string\renewcommand\{\ccol{\the<counter>}\} to redefine the reference}

\skfootnote{\lvoc{VII.3.3}[250] \lmanc{13.6}[128]}
\end{frame}

\begin{frame}{Counter Domination\inClass{, conquering, humiliation}}{solution}\relax
\twocolImg{
\lstinputlisting[linerange={11-20}]{counterdom.tex}
}{counterdom}
\end{frame}

\begin{frame}[fragile]{Redefine existing counter domination\magicPage}{``equation'' example}\relax
Package based solution:

\lstinline|\usepackage{chngcntr}|

and \lstinline|\counterwith{equation}{chapter}|  to make the ``equation'' a slave or \lstinline|\counterwithout{equation}{chapter}| to ``free'' the counter.

Core-based solution:

\begin{lstlisting}
\makeatletter
\@removefromreset{equation}{section}
\@addtoreset{equation}{chapter}
\renewcommand{\theequation}{\thechapter.\@arabic\c@equation}
\makeatother
\end{lstlisting}

\skfootnote{\vspace{-10ex}\stExC{https://tex.stackexchange.com/questions/61756/how-to-change-equation-numbering-style} \stExC{https://tex.stackexchange.com/questions/54241/change-the-type-of-equation-numbering-in-document-class-article} \stExC{https://tex.stackexchange.com/questions/28333/continuous-v-per-chapter-section-numbering-of-figures-tables-and-other-docume} \normalfont\url{https://texfaq.org/FAQ-running-nos} \lvoc{IX.2.1}[293].\\ Also see \ccol{\p@} prefix \lvoc{IX.2.2}[295] and \stExC{https://tex.stackexchange.com/questions/61426/how-to-make-ref-display-only-subsection}}
\end{frame}

\begin{frame}[fragile]{Define and simple manipulation\tW\magicPage}\relax

     \textbf{Define new} \ccol\newcount\ccol{\<countname>} as \verb|\newcount\mycounter|

     \textbf{Set number} \ccol{\<countname>=<number>}  Or use \ccol\countdef. Like \verb|\countdef\mynumber=43|

     \textbf{Add number}  \ccol{\advance\string\<countname>\ by <number>}. Also there are \ccol\multiply\ and \ccol\divide. As well as \ccol\numexp.

     \textbf{Show number} \ccol{\the\string\<countname>} or \ccol\number\ or \ccol\romannumeral

     \skfootnote{\vspace{-3ex}\knuthc{15}[129] \stExC{https://tex.stackexchange.com/questions/245635/formal-syntax-rules-of-dimexpr-numexpr-glueexpr}\\Actually you can use \ccol\count<number> like \ccol\count212. What \ccol\newcount\ do is just find a free number and fix it to your defined name.}
\end{frame}

\begin{frame}{Define and simple manipulation\tW\magicPage}{Example}\relax

\twocolImg{
\lstinputlisting[linerange={11-16}]{counterTeX.tex}
}{counterTeX}

\end{frame}

\subsection{Length}

\begin{frame}{Length manipulation\tW\magicPage}\relax

\textbf{Define lenght} \ccol{\newdimen\string\<lenname>}

\textbf{Set length} \ccol{\string\<lenname>=<len>}

\textbf{Add lenght}  \ccol{\advance\string\<lenname>\ by <len>}. Also there are \ccol\multiply\ and \ccol\divide. As well as \ccol\dimexp.

\textbf{Show lenght} \ccol{\the\string\<lenname>}

\skfootnote{\knuthc{15}[132] }
\end{frame}

\begin{frame}{Length manipulation\tW\magicPage}{Example}\relax

\twocolImg{
\lstinputlisting[linerange={11-14}]{lengthTeX.tex}
}{lengthTeX}

\end{frame}

\begin{frame}{Length manipulation\lW\magicPage}\relax

\textbf{Define lenght} \ccol{\newlength\{\string\<lenname>\}}

\textbf{Set length} \ccol{\setlength}

\textbf{Add lenght}  \ccol{\addtolength}.

\textbf{Show lenght} \ccol{\the\string\<lenname>}. But also you can use \ncol\usepackage{printlen}\ and then \ccol\uselengthunit, \ccol\printlength

\skfootnote{\wikiC{https://en.wikibooks.org/wiki/LaTeX/Lengths} }
\end{frame}

\begin{frame}{Length manipulation\lW\magicPage}{Example}\relax

\twocolImg{
\lstinputlisting[linerange={7-7,11-16}]{lengthLaTeX.tex}
}{lengthLaTeX}

\end{frame}

\subsection{Skips}

\begin{frame}{Skip manipulation\tW\magicPage}\relax

\TeX\ provides additional storage for glue and glue in math mode (that is sensible for math style). They have the same syntax as length, just with \ccol\skip\ or \ccol\muskip\ prefix/suffix
\end{frame}

\subsection{Toks}

\begin{frame}{Toks manipulation\tw\magicPage}\relax

\TeX\ has addition registers for storing strings. They have \ccol\toks\ prefix/suffix. The difference between toks and storage inside macros are in extension...

     \skfootnote{\stExC{https://tex.stackexchange.com/questions/455208/token-register-vs-macro-register}}
\end{frame}

\subsection{Boxes}

\begin{frame}{Box manipulation\tW\magicPage}\relax

\textbf{Define box} \ccol{\newbox\string\<boxname>}

\textbf{Set box} \ccol{\setbox\string\<boxname>=<box>}

\textbf{Provide the content without deleting it:} \ccol{\copy\string\<boxname>}

\textbf{Provide the content with delete from memory:} \ccol{\box\string\<boxname>}

\textbf{Dimentions}: width: \ccol\wd, height: \ccol\ht, depth: \ccol\dp

\skfootnote{\knuthc{15}[131] }
\end{frame}

\begin{frame}{Box manipulation\tW\magicPage}{Example}\relax

\twocolImg{
\lstinputlisting[linerange={12-20}]{boxTeX.tex}
}{boxTeX}

\skfootnote{\ccol\the\ here is just to PRINT the length. Not the part of the command.}
\end{frame}

\begin{frame}[fragile]{Box manipulation\lW\magicPage}\relax

\textbf{Define box} \ccol{\newsavebox\{\string\<boxname>\}}

\textbf{Set box} \ccol{\savebox}

\textbf{Provide the content without deleting it:} \ccol{\usebox}

\textbf{Dimentions}:
\begin{enumerate}
    \item Create a length variable: \ccol\newlength
    \item Set the variable to dimention of the box CONTENT:
    \begin{itemize}
        \item width: \verb|\settowidth{\<len-var>}{\usebox{\<box>}}|
        \item height: \verb|\settoheight{\<len-var>}{\usebox{\<box>}}|
        \item depth: \verb|\settodepth{\<len-var>}{\usebox{\<box>}}|
    \end{itemize}

\end{enumerate}

\skfootnote{\lmanc{14.4-6}[133] \lmanc{20.5, 20.7}[183]}
\end{frame}

\begin{frame}{Box manipulation\lW\magicPage}{Example}\relax

\twocolImg{
\lstinputlisting[linerange={12-26}]{boxLaTeX.tex}
}{boxLaTeX}

\skfootnote{\ccol\the\ here is just to PRINT the length. Not the part of the command.}
\end{frame}


\documentclass[12pt]{article}
\usepackage[pdftex]{graphicx}

\begin{document}
\newcounter{problem}
\thispagestyle{empty}

\section*{NYU General Physics 1---Problem set 4}

\paragraph{Problem~\theproblem:}\refstepcounter{problem}%
Look up the definition of the ``coefficient of friction'' and the
difference between ``static friction'' and ``sliding'' or ``kinetic''
friction.  Once you have done that, re-do the block on an inclined
plane problem but with friction and the following parameters:

\textsl{(a)} The block has mass $m$.  The plane is inclined at an
angle $\theta=35\,\deg$ to the horizontal.  The block-plane interface
has a frictional force with coefficient of friction $\mu=0.1$.  Draw
the free-body diagram.  Draw the vector force sum as a vector diagram
in two dimensions (as we did in lecture).  Compute the magnitude $a$
of the acceleration; give your answer in terms of the magnitude $g$ of
the acceleration due to gravity.  Compute the magnitude $f$ of the
frictional force in terms of $m$, $g$, and $\theta$.

\textsl{(b)} The same again, but now with a coefficient of friction
$\mu=1.3$.  Note that this case will be \emph{qualitatively
  differerent} because the friction will be static.

\textsl{(c)} What is the minimum coefficient of friction $\mu$ at
which the system will be static?  Give your answer in terms of
$\theta$.

\paragraph{Problem~\theproblem:}\refstepcounter{problem}%
In the following device, the string can be approximated as massless
and inextensible, the pulley can be approximated as massless and
frictionless, but the horizontal surface has a coefficient of friction
(static and kinetic) of $\mu$.\\[1ex]
\includegraphics{../mp/pulley_table.pdf}

\textsl{(a)} What do you think this system will do, if released from
rest?  Consider the case that the coefficient of friction $\mu$ is
very large, and also the case in which the coefficient of friction is
very small.  What would it do in the limit that $m_2$ is far larger
than $m_1$?  What about in the limit that $m_1$ is far larger than
$m_2$?  Don't calculate here; use your intuition.

\textsl{(b)} Obtain the acceleration of the blocks and the tension in
the string for the case of kinetic friction and for the case of static
friction.  Note that you do different calculations in each case.  Give
your answers in terms of $m_1$, $m_2$, $\vec{g}$, and $\mu$ (or a
subset of these).

\textsl{(c)} Do your answers to \textsl{(b)} mesh
with the intuitions you wrote down in part \textsl{(a)}?

\paragraph{Problem~\theproblem:}\refstepcounter{problem}%
A ball of mass $M$ swings like a pendulum on a light, inextensible
string of length $L$.  Imagine that the pendulum is swinging back and
forth with a significant amplitude (say an amplitude of $L/4$).  Think
about the tension in the string.  At the lowest point in the swing, is
the tension in the string equal to, less than, or greater than $M\,g$?
Explain why in words.

Don't \emph{calculate} the tension unless you really want to.

\end{document}


%

\documentclass[twoside]{article}
\setlength{\oddsidemargin}{0.25 in}
\setlength{\evensidemargin}{-0.25 in}
\setlength{\topmargin}{-0.6 in}
\setlength{\textwidth}{6.5 in}
\setlength{\textheight}{8.5 in}
\setlength{\headsep}{0.75 in}
\setlength{\parindent}{0 in}
\setlength{\parskip}{0.1 in}

%
% ADD PACKAGES here:
%

\usepackage{amsmath,amsfonts,graphicx}

%
\newcounter{lecnum}
\renewcommand{\thepage}{\thelecnum-\arabic{page}}
\renewcommand{\thesection}{\thelecnum.\arabic{section}}
\renewcommand{\theequation}{\thelecnum.\arabic{equation}}
\renewcommand{\thefigure}{\thelecnum.\arabic{figure}}
\renewcommand{\thetable}{\thelecnum.\arabic{table}}

%
% The following macro is used to generate the header.
%
\newcommand{\lecture}[4]{
   \pagestyle{myheadings}
   \thispagestyle{plain}
   \newpage
   \setcounter{lecnum}{#1}
   \setcounter{page}{1}
   \noindent
   \begin{center}
   \framebox{
      \vbox{\vspace{2mm}
    \hbox to 6.28in { {\bf EE402 - Discrete Time Systems
	\hfill Spring 2018} }
       \vspace{4mm}
       \hbox to 6.28in { {\Large \hfill Lecture #1 \hfill} }
       \vspace{2mm}
       \hbox to 6.28in { {\it Lecturer: #2 \hfill } }
      \vspace{2mm}}
   }
   \end{center}
   \markboth{Lecture #1}{Lecture #1}

   \vspace*{4mm}
}
%
% Convention for citations is authors' initials followed by the year.
% For example, to cite a paper by Leighton and Maggs you would type
% \cite{LM89}, and to cite a paper by Strassen you would type \cite{S69}.
% (To avoid bibliography problems, for now we redefine the \cite command.)
% Also commands that create a suitable format for the reference list.
\renewcommand{\cite}[1]{[#1]}
\def\beginrefs{\begin{list}%
        {[\arabic{equation}]}{\usecounter{equation}
         \setlength{\leftmargin}{2.0truecm}\setlength{\labelsep}{0.4truecm}%
         \setlength{\labelwidth}{1.6truecm}}}
\def\endrefs{\end{list}}
\def\bibentry#1{\item[\hbox{[#1]}]}

%Use this command for a figure; it puts a figure in wherever you want it.
%usage: \fig{NUMBER}{SPACE-IN-INCHES}{CAPTION}
\newcommand{\fig}[3]{
			\vspace{#2}
			\begin{center}
			Figure \thelecnum.#1:~#3
			\end{center}
	}
% Use these for theorems, lemmas, proofs, etc.
\newtheorem{theorem}{Theorem}[lecnum]
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{claim}[theorem]{Claim}
\newtheorem{corollary}[theorem]{Corollary}
\newtheorem{definition}[theorem]{Definition}
\newenvironment{proof}{{\bf Proof:}}{\hfill\rule{2mm}{2mm}}

% **** IF YOU WANT TO DEFINE ADDITIONAL MACROS FOR YOURSELF, PUT THEM HERE:

\begin{document}

% Lecture Details
\lecture{11}{Asst. Prof. M. Mert Ankarali}
....

\section*{Frequency Response in Discrete Time Control Systems}

Let's assume $u[k]$, $y[k]$, and $G(z)$ represents the input, output,
and transfer function representation of an input-output discrete time
system.

In order to characterize frequency response of a discret system,
the test signal is
%
\begin{align*}
 u[k] = e^{j \omega k}
\end{align*}
%
which is an artificial complex periodic signal with a DT domain
frequency of $\omega$. The z-transform of $u[k]$ takes the
form
%
%
\begin{align*}
 U(z) = \mathcal{Z} \lbrace e^{j \omega k} \rbrace = \frac{z}{z - e^{j \omega}}
\end{align*}
%
Response of the system in z-domain is given by
%
%
\begin{align*}
 Y(z) = G(z) U(z) = G(z) \frac{z}{z - e^{j \omega}}
\end{align*}
%
Assuming that $G(z)$ is a rational transfer function
we can perform a partial fraction expansion
%
\begin{align*}
     Y(z) &= \frac{a z}{z -  e^{j \omega}} + \left[ \mathrm{terms \ due \
  to \ the \ poles \ of} \  G(z) \right]
\\
a &= \lim_{z \to e^{j \omega}} \left[ (z - e^{j \omega}) \frac{Y(z)}{z}
  \right]  = G(e^{j \omega})
\\
Y(z) &=  \frac{G(e^{j \omega}) z}{z -  e^{j \omega}} + \left[ \mathrm{terms \ due \
  to \ the \ poles \ of} \  G(z) \right]
\end{align*}
%
Taking the inverse z-transform yields
%
\begin{align*}
  y(t) = G(e^{j \omega}) e^{j \omega k} + \mathcal{Z}^{-1} \left[ \mathrm{terms \ due \
  to \ the \ poles \ of} \  G(z) \right]
\end{align*}
%
If we assume that the system is ``stable'' or system is a part of
closed loop system and closed loop behavior is stable then
at steady state we have
%
\begin{align*}
y_{ss}[k] &= G(e^{j \omega}) e^{j \omega k} \\
&= | G(e^{j \omega}) | e^{i \omega k + \angle G(e^{j \omega})}
\\
&= M e^{i \omega k + \theta}
\end{align*}
%
In other words complex periodic signal is scaled and phase shifted
based on the following operators
%
\begin{align*}
M &= | G(e^{j \omega}) | \\
\theta &= \angle G(e^{j \omega})
\end{align*}
%
It is very easy to show that for a general real time domain signal
$u[k] = \sin (\omega k + \phi)$, the output $y[k]$ at steady state
is computed via
%
\begin{align*}
  y_{ss}[k] = M \sin(\omega k + \phi + \theta)
\end{align*}
%
If there is sampling involved in the system the following relation
between DT frequency and CT frequency exists $\omega_d = \omega_c T$

Similar to CT systems we utilize bode polts (or FRF function polts) to
analyze DT systems and design filters/controllers. Main difference
between CT and DT bode polt is that while the frequency goes to
infinity for CT bode polts, for DT systems the frequency goes up-to
$\pi \ \mathrm{rad}$ or  $\omega_s / 2$ (i.e. Nyquist frequency).
Given the bode polt one can extract the magnitude scale and phase
difference with respect to any input frequency.

\textbf{Example:} Let's assume that we have the following
CT plant transfer function
%
\begin{align*}
  G(s) = \frac{1}{s+1}
\end{align*}
%
The pulse transfer function of the following discretized
system can be computed as
%
%
\begin{align*}
  G(z) = \mathcal{Z} \left[ \frac{1-e^{-Ts}}{s} \frac{1}{s+1} \right]
\end{align*}
%
     \begin{center}
 \begin{minipage}[h]{\linewidth}
     \begin{center}
       \includegraphics[width=\textwidth]{Gz}
     \end{center}
 \end{minipage}
     \end{center}
%
We can also transform this DT transfer function to an
artificial CT form using Bilinear-Tustin transformation.
%
%
\begin{align*}
  G(\bar{s}) = G(z) |_{z = \frac{1 + (T/2) \bar{s}}{1 - (T/2) \bar{s}}}
\end{align*}
%
Now let's draw the bode plots of $G(s)$, $G(z)$, and $G(\bar{s})$
for both $T = 0.01 s$ and $T = 0.001 s$.

\begin{center}
 \begin{minipage}[h]{0.99\linewidth}
     \begin{center}
       \includegraphics[width=\textwidth]{bode_all}
     \end{center}
 \end{minipage}
\end{center}

\newpage

\section*{Phase and Gain Margins}

We already know that a binary stability metric is not enough to
characterize the system performance and that we need metrics
to evaluate how stable the system is and its robustness to
perturbations. Using root-locus techniques we talked about
some ``good'' pole regions which provides some specifications
about stability and closed-loop performance.

Another common and powerful method is to use gain and phase margins
based on the Frequency Response Functions of a closed-loop topology.
Phase and gain margins are derived from the Nyquist’s stability
criterion and it is relatively easy to compute them from the Bode diagrams.

\subsection*{Gain Margin}

The \textit{gain margin}, $g_m$, of a system is defined as the smallest amount
that the open loop gain can be increased before the closed loop system
goes unstable. For a system, whose ``open-loop'' phase response starts from an angle
$> -180^o$ at $\omega = 0$, the gain margin can be computed based on
the smallest frequency where the phase of the loop transfer function
$G_{OL}(s)$ is $-180^o$. Let $\omega_{pc}$ represent this frequency,
called the phase crossover frequency. Then the gain margin for the
system is given by

\begin{align*}
  g_m = \frac{1}{| G_{OL}(j \omega_{pc})| } \quad \mathrm{or} \quad G_m
  = -20 \,
  \mathrm{log}_{10} | G_{OL}(j \omega_{pc} ) |
\end{align*}

where $G_m$ is the gain margin in dB scale.

If the phase response never crosses the $-180^o$ line, gain margin is simply $\infty$.

\subsection*{Phase Margin}

The \textit{phase margin} is the amount of ``phase lag'' required to
reach the (Nyquist) stability limit. Let $\omega_{gc}$ be the gain
crossover frequency, the smallest frequency where the loop transfer
function $G_{OL}(s)$ has unit magnitude. Then for a system for which
the gain response at $\omega = 0$ is larger than $1$ and gain
decreases and eventually crosses the unity gain line, the phase margin
is given by

\begin{align*}
  \phi_m = \pi + \angle G_{OL} (j \omega_{gc})
\end{align*}

When the gain and phase plots shows monotonic like
behaviors gain and phase margins becomes more
meaningful in terms of closed-loop performance.

So far we have only talked about stability margins for a
CT control system. Indeed, the Nyquist stability criterion
and associated phase and gain margin definitions
are almost exactly same, if we consider FRF functions.
Let $G_{OL}(z)$ be the open-loop pulse transfer function
of a discrete time control system, then the gain and
phase margins are computed as

\begin{align*}
    g_m &= \frac{1}{| G_{OL}(e^{j \omega_{wc})} |} \quad \mathrm{or} \quad G_m
  = -20 \,
  \mathrm{log}_{10} | G_{OL}(e^{j \omega_{wc} }) |
\\
  \phi_m &= \pi + \angle G_{OL} (e^{j \omega_{gc}})
\end{align*}

where as definitions of gain and phase crossover frequencies are
exactly same.

\textbf{Example:} Let's consider a CT plant transfer function
%
\begin{align*}
  G(s) = \frac{3}{(s+1)^3}
\end{align*}
%
Nyquist plot, bode diagrams are illustrated in the given Figure below
%
\begin{center}
\begin{minipage}[h]{\linewidth}
    \begin{center}
      \includegraphics[width=\textwidth]{Gp}
    \end{center}
\end{minipage}
\end{center}
%
The phase crosover frequency and gain margin for the CT open-loop
transfer function is given below
%
\begin{align*}
\omega_{pc} &= 1.73 \ \mathrm{rad/s}
\\
g_m &= \frac{1}{| G(j \omega_{pc}|} = 2.67
\\
G_m &= 8.5 dB
\end{align*}
%
On the other hand gain crosover frequency and phase margin
for $G(s)$ is computed as
%
\begin{align*}
\omega_{gc} &= 1.04 \ \mathrm{rad/s}
\\
\phi_m &= \pi + \angle G(j \omega_{pc}) = 42^0
\end{align*}
%
Now let's assume that this plant transfer function
is controlled via a unity gain digital feedback
controller and a ZOH operator, where sampling time
is $T = 0.5 \ s$. Open-loop pulse transfer function
can be found as
%
\begin{align*}
  G(z) = \left[ \frac{1 - e^{-Ts}}{s} G(s) \right]
\end{align*}
%
The Nyquist and bode polts for this DT open-loop
puls transfer function is illustrated below
%
\begin{center}
\begin{minipage}[h]{\linewidth}
    \begin{center}
      \includegraphics[width=\textwidth]{Gd}
    \end{center}
\end{minipage}
\end{center}
%
Note that instead of DT frequency $\omega_d \in [0, pi)$,
the x-axis illustrates the actual frequency $\omega = \omega_d / T $.
It is very easy to associate DT and CT frequencies, and main advantage
of actual frequency is that CT and DT versions of bode plots
becomes directly comparable.

The phase crosover frequency and gain margin for the DT open-loop
transfer function is given below
%
\begin{align*}
\omega_{pc} &= 1.35 \ \mathrm{rad/s}
\\
g_m &= \frac{1}{| G(e^{j \omega_{pc} T|}} = 1.62
\\
G_m &= 4.18 dB
\end{align*}
%
On the other hand gain crosover frequency and phase margin
for $G(s)$ is computed as
%
\begin{align*}
\omega_{gc} &= 1.03 \ \mathrm{rad/s}
\\
\phi_m &= \pi + \angle G(j \omega_{pc}| = 28^0
\end{align*}

If we compare the CT and DT versions of the same system, we can see
that both gain margin and phase margin of the original CT system is
better, and we can conclude that discretization reduces the
``stability''. Another interesting result is that while there is a
significant change in phase-crossover frequency, the change in gain
crosover frequency is minimal.

Now let's transfrom the $G(z)$ to a artificial CT system using
Bilinear-Tustin transformation:
%
%
\begin{align*}
  G(\bar{s}) = G(z) |_{z = \frac{1 + (T/2) \bar{s}}{1 - (T/2) \bar{s}}}
\end{align*}
%
We know that the relation between the frequency of this
artificial system, $\bar{\omega}$, and frequencies of the actual system
and discretized system are given by
%
\begin{align*}
\bar{\omega} = \frac{2}{T} \tan (\frac{\omega_d}{2}) = \frac{2}{T}
  \tan (\frac{\omega T}{2})
\end{align*}
%
%
\begin{center}
\begin{minipage}[h]{\linewidth}
    \begin{center}
      \includegraphics[width=\textwidth]{Gt}
    \end{center}
\end{minipage}
\end{center}
%

The phase crosover frequency and gain margin for this artificial CT open-loop
transfer function is given below
%
\begin{align*}
\omega_{pc} &= 1.41 \mathrm{rad/s}
\\
g_m &= \frac{1}{| G(e^{j \omega_{pc} T|}} = 1.62
\\
G_m &= 4.18 dB
\end{align*}
%
On the other hand gain crosover frequency and phase margin
for $G(s)$ is computed as
%
\begin{align*}
\omega_{gc} &= 1.06 \ \mathrm{rad/s}
\\
\phi_m &= \pi + \angle G(j \omega_{pc}| = 28^0
\end{align*}

If we compare the phase and gain margin and associated
crosover frequencies we can see that stability margins of
DT and Tustin-Transformed are almost same. It is an expected
result, because the core purpose of Tustin transformation
is transforming a DT system to a CT form by preserving the
stability and other importan characteristics.

Tustin transformation has two basic advantages
%
\begin{itemize}
  \item It ``preserves'' the stability and robustness
   characteristics of the digital control system.
  \item Even though bode polts of DT systems
   are perfectly valid (and useful), due to periodicity in
   $\omega_d$ the some of the simplicities and
   advantages of CT bode plots are lost. Since Tustin
   transformed system is a CT representation, we
   still can use these simplicities and other advantages.
\end{itemize}

There two basic disadvantages of Tustin transformation
\begin{itemize}
  \item It has significant computational costs. However in
   a computer environment these costs can be negligible.
  \item If one designs a controller in Tustin form, and then
  back-transformes the controller in DT form. For some class
  of controller the quantization effects can become important
   and deadly.
\end{itemize}

\newpage

\textbf{Lead-Compensator Design for DT Control Systems}

Let's consider the DT control system below. Let's assume
that $T = 0.1 s$
%
     \begin{center}
 \begin{minipage}[h]{\linewidth}
     \begin{center}
       \includegraphics[width=\textwidth]{mainblock}
     \end{center}
 \end{minipage}
     \end{center}
%
The goal is designing a DT phase-lead compensator such that
the Phase-Margin is of the controlled system is in the desired
range of $\phi_m \in [50^o \, 60^o]$.

Due to nice properties of CT bode plots, lead-compensator design
procedure is handled in the Bilinear-Tustin transformed domain.
Below we will summarize the process for the example plant.

\begin{enumerate}
  \item Compute discretized plant transfer function $G(z)$
%
\begin{align*}
  G(z) &= \mathcal{Z} \left[ \frac{1-e^{-Ts}}{s} G_P(s) \right]
\\
       &= \mathcal{Z} \left[ \frac{1-e^{-Ts}}{s} \frac{10}{(s+1)^2}
         \right]
\\
&= \frac{0.047 z + 0.044}{z^2 - 1.8 z + 0.82}
\end{align*}
%
\item Compute the Bilinear-Tustin transformation of $G(z)$
%
\begin{align*}
  G(\bar{s}) &= G(z) |_{z = \frac{1 + (T/2) \bar{s}}{1 - (T/2)
  \bar{s}}}
\\
&= \frac{ -0.0008 s^2 - 0.48 s + 9.98 }{s^2 + 2 s + 0.998}
\end{align*}
%

\item Now goal is designing a lead compensator for $G(\bar{s})$.
Lead-compensator has the form.
%
\begin{align*}
  G_{l}(\bar{s}) = K_{\mathrm{lead}} \frac{T_{l} \ a \ s +
  1}{T_{l} /  a \ s + 1}
\end{align*}
%
where gain $K_{l}$ (generally) computed based on steady
state requirments. This can be computed either in z-domain or
s-bar domain. Let's assume that we are OK with steady-state
performance and $K_{l} = 1$.

\item Compute the $\phi_m$ of the un-compensated system
and find the required $\Delta \phi_m$ such that the
compensated system meets the specifications.
%
\begin{align*}
  \phi_m &\approx 28^o
\\
  \Delta \phi_m &= [ 22^o \ , \ 32^o]
\end{align*}
%
     \begin{center}
 \begin{minipage}[h]{\linewidth}
     \begin{center}
       \includegraphics[width=\textwidth]{uncomp}
     \end{center}
 \end{minipage}
     \end{center}
%
\item For $a = 1.5$, $a = 2$, and $a = 3$, bode plots
of a phase-lead compensator is illustrated with $T_{l} = 1$
in the figure below.
%
     \begin{center}
 \begin{minipage}[h]{\linewidth}
     \begin{center}
       \includegraphics[width=\textwidth]{lead}
     \end{center}
 \end{minipage}
     \end{center}
%
It can be seen that $\phi_{max}$ is larger for large $a$.
$\phi_{max}$ (or $a$) can also be computed using the following
relation.
%
\begin{align*}
\sin \phi_{max} &=  \frac{a^2 - 1}{a^2 + 1}
\end{align*}
%
As your remember from EE302, Lead compensator should
have a lead angle that is above $\approx 5-15^o$ the reqired
$\Delta \phi_m$. Based on this we compute/find $a$.
Based on the bode polts, it seems that $a =2$
may supply the required additonal phase-margin.
One should see that $\phi_{max}$ is not affected
from the choice of $T_{l}$.
%
\item Now our goal is to copmpute $T_{l}$, where $1/T_{l}$
corresponds to the center freqeuncy of the copmensator.
One possible choice is choosing $T$ such that
$1/T_{l} = \bar{\omega}_{gc}$, i.e. gain croesover frequency.
However, at center frequency the lead copmensator
shifts the bode magnitude by
%
\begin{align*}
G_{\mathrm{center}} = 20 \mathrm{log}_{10} (1 / a)
\end{align*}
%
which causes a shift in gain-croesover frequency.
For example, for $a = 2$, $G_{\mathrm{center}} \approx 6 \ dB$.
For this reason, a ``better'' choice is choosing $T$ such that
center freqeuncy of the lead-compensator coincides with
the frequency where $|G(j \bar{\omega})|$ crosses
$- 20 \ \mathrm{log}_{10} (1 / a)$, i.e. we compute $T_{l}$
such that
%
\begin{align*}
  |G(j 1/T_{l})| = - 20 \ \mathrm{log}_{10} (1 / a)
\end{align*}
%
From the bode polts for $a = 2$, the freqeuncy for which
$G(\bar{s})$ croesses the $- 6 dB$ line is approximatelly
$4.45 \ \mathrm{rad/s}$. Thus we choose $T = 0.225 s$.
Check if the lead-compensator meets the phase-margin
reqeuirment. Otherwise, repeat the process with a higher
$\delta \phi$ angle.

In our example, the resultant tustin domain lead compensator
has the form.
%
\begin{align*}
  G_{l}(\bar{s}) = \frac{0.45 s + 1}{0.1125 s + 1}
\end{align*}
%
The Figure below illiustrates the bode plots of both (tustin
domain) compensated and uncompansated systems.
Compensated systems has a phase margin of $\phi_m = 51^o$
which meets the requirements.
%
     \begin{center}
 \begin{minipage}[h]{\linewidth}
     \begin{center}
       \includegraphics[width=\textwidth]{comptust}
     \end{center}
 \end{minipage}
     \end{center}
%
\item Transform the $\bar{s}$-domain lead-compensator
to z-domain.
%
\begin{align*}
  G_{l}(z) =& G_{l}(\bar{s})|_{\bar{s} = \frac{2}{T} \frac{z-1}{z+1}}
\\
  G_{l}(z) =& \frac{3.08 z - 2.46}{z - 0.385}
\end{align*}
%
\item Check if the discrete-time compensator meets the
the phse-margin requirments.
%
     \begin{center}
 \begin{minipage}[h]{\linewidth}
     \begin{center}
       \includegraphics[width=\textwidth]{DTlead}
     \end{center}
 \end{minipage}
     \end{center}
%
It can be seen that the designed compensator in z-domain
also meets the phase-margin specifications.
%
\end{enumerate}

\newpage

In Figure below, we compare the closed-loop step responses
of both uncompensated and compensated pulse transfer functions.
%
     \begin{center}
 \begin{minipage}[h]{0.7\linewidth}
     \begin{center}
       \includegraphics[width=\textwidth]{step}
     \end{center}
 \end{minipage}
     \end{center}
%

% **** This ENDS THE EXAMPLES. DON'T DELETE THE FOLLOWING LINE:
\end{document}