\section{Artificial Intelligence}
\subsection{Basic Problems \& Nomenclature}
There are some goal states and one initial state. The objective is to find the goal state that is closer (with the shortest path to the root/ with the least search cost). Is given as the solution the steps necessary to perform that path.

To keep the formulation as general as possible, abstractions are required, keeping in mind that they will need a correspondence when applied to a real problem.

Example of the application to a problem: a vacuum cleaner that needs to clean every square. In this case, only 2 squares are presented, no localization sensors are present, only "rubbish" sensors that tell if the current square is dirty or not.

Therefore:
\begin{itemize}
    \item \ul{States}: $<r, d_1, d_2>$ where $r$ is the robot position, $d_1$ and $d_2$ are binary, representing the existence of dirt in each of the rooms.
    \item \ul{Operators/Actions}: L (go left), R (go right) or S (suck dirt)
    \item \ul{Goal Test}: $d_1$ = False and $d_2$ = False. (($d_1$ nor $d_2$) == 1)
    \item \ul{Initial State}: $<r, d_1, d_2> = <1, T, T>$ is at square 1, and squares 1 and 2 are dirty
    \item \ul{Step Cost}: the description of each action cost. In this case, 1 for each one.
\end{itemize}

\quickimagesidebyside{AIML/cap3-001.png}{1}{AIML/cap3-002.png}{.8}

\quickimagesidebyside{AIML/cap3-003.png}{1}{AIML/cap3-004.png}{1}

\quickimagesidebyside{AIML/cap3-005.png}{1}{AIML/cap3-007.png}{1}

As you can see, every problem is very well defined in terms of the start, the end, the possible moves and what makes a solution better than other. Therefore, the conditions to put the computer thinking how to get from the possible steps to the best solution are assembled. One way the computer should be able to get to the solution is by exploring every move combination and check the state it ended up with.

Given the initial state, use the operators to generate successor states.

\quickimage{AIML/cap3-008.png}{.6}

Then a choice of which is more "profitable" or more likely to lead to a goal state needs to be made and this cycle continues until the arrival at a goal state.

\quickimage{AIML/cap3-009.png}{.6}

In this case, the solution would be $\{S, R, S\}$.

However, before diving directly in algorithms, is important to note the characteristics of the Environment and of the Agent. Based on these we'll be able to perform much better choosing the search algorithm that is best for us.

\subsection{Environment} %FORMULATE THIS SECTION BETTER!!!!!!!!!!!!!!!!!!

Observability: how much can the agent know about the environment.

An environment is fully observable if the agent can see everything. Or partial observable:
- part of the state is occulted and you simply can't

Deterministic: the effect of the actions are predictable
If I move one queen from one place to the other, I can predict the effects, what is attacking what, etc\dots
Instead of Deterministic, it can be stochastic, where the outcomes are functions of probability functions. Therefore, you can't be 100\% sure of the outcome. Therefore, you can use probability to make choices\dots

Neither the environment nor the agent performance change while the agent is deliberating. --> Static.

In a dynamic environment, the agent performance can change with time.

Semi-dynamic means that the world is static, but the performance is changing.
ex: turn game where the game doesn't change while you are thinking but the more you take, the less point you get.

Continuous or discrete

Sequential or episodic. Episodic means that one episode doesn't influence the next one. It's very related with causality. In episodic environments, there's no influence in consequent problems.

E.g. one game of chess is sequential, but different games are episodic.

The outcomes for all actions are given. --> Known environment.

In a case where the less time you spend thinking before answering,

Knowing these is very important because it allows us to best choose the shelf of methods from which we take our algorithms from. Some are best from some things and some can only be used in certain situations as well.

Internally to the agent, you have a way of representing of the world. (Internal representation)

Example when you don't have an internal representation: random vacuum cleaning robots don't know anything about the environment, they just rotate randomly when they see an object.

%CHECK: how many iterations are needed depending on uniform function of the angle. Maybe if it rotates only between pi/2 and pi, it will clean everything quicker.

\quickimage{AIML/cap2-001.png}{.5}
\quickimage{AIML/cap2-002.png}{.5}

\subsection{Agent}

Model-based: typically, when you have partial observability.

Goal-based: when you aim for a goal. You have states and actions and can search for the goal.

Utility-based: are very similar to goal-based but are a bit more, not all goals are the same. There a preference between goals.
Utility Theory handles how to translate preferences to numbers.

\subsection{Search Problems}

In essence, is necessary some \bb{Search Terminology} to refer to certain things:

\quickimage{AIML/cap3-010.png}{.5}

General algorithm shape, starting with $open\_list = \{initial_node\}$, iterate over:
\begin{enumerate}
    \item Select a node from the open\_list;
    \item Check if it's a goal node (in case it satisfies the goal test). If yes, return solution by backing up to the root;
    \item If not, remote it from the open\_list, expand it with the successor function and insert the nodes that come from there to the open\_list.
\end{enumerate}

Different selection criteria leads to a variety of search methods.

If it's tree based, then no nodes will be repeated and it's not necessary to have a list of the already visited nodes. In a graph however, is needed to have a list of these, or else a cycle is possible.

To evaluate the algorithm, many parameters may be enumerated:

\quickimage{AIML/cap3-011.png}{.5}

\vspace{.5cm}
Mentioning types of search strategies:

\quickimage{AIML/cap3-012.png}{.5}

\subsection{Uniformed Search Strategies}

A list of \bb{Uniformed search strategies} we'll have a deeper look to:
\begin{itemize}
    \item \bb{Breadth-first Search} - Select \ul{earliest} expanded node first - uses a FIFO queue (First In, First out). This leads to opening every node at the safe depth first before moving the deeper nodes.

    \quickimage{AIML/cap3-013.png}{.5}

    Because order of depth is followed and every node checked, this search strategy is \ul{Complete} and \ul{Optimal} (if the path cost increases - or at least doesn't decreases - with depth).
    Being \bb{d} the depth of the solution and \bb{b} the branching factor(max number of successors of a node.) then in the worst case, the total number of nodes generated is: $1 + b + b^2 + b^3 + \dots + b^d$

    Time Complexity - O($b^d$)
    Space Complexity - O(sum no of nodes) = O($b^d$)

    \quickimage{AIML/cap3-014.png}{.5}

    Note that it makes a difference if you test the node before or after expanding it. If it's tested before, there's no need of expanding the node. If the test is made only after the expansion, the complexities grows to O($b^{d+1}$).

    \item \bb{Uniform-cost Search} - expands the node that has the smallest cost from the root to it.

    \quickimage{AIML/cap3-015.png}{.5}

    Note that each action generates one possible state from the state where the robot was previously.

    This search strategy is only complete and optimal if the step costs are strictly positive. Else, it can give several steps that cost nothing to places far away from the solution.

    \item \bb{Depth-first Search} - Exactly as the name suggests, goes until the deepest node first, and only then looks at the other nodes at the first level. Therefore, it can be very inefficient on a large or infinite tree. Open the last node added to the list (LIFO- Last In, First Out).

    \quickimage{AIML/cap3-016.png}{.5}

    \item \bb{Backtrack Search} - a variation of depth-first, but expands one node at a time, only stores in memory that only node and the expansion is made by modifying the node, while backtrack is nothing more than undoing the modification..

    It's not complete nor it is optimal... but saves a lot of memory.

    \item \bb{Depth-limited search} - another variation of depth-first where limiting the search tree to a depth L, is possible to contain the inefficiency. It's complete if the depth of the solution if smaller than L but still not optimal.

    Time complexity: O($b^L$)
    Space complexity: O($b \times L$)

    \item \bb{Iterative deepening depth-first search} - A variation of the previous one. In this one, the idea will be to run depth-limited search for an increasing L. Run for L=1, L=2, \dots

    This way, it is complete and it's optimal (if the path cost is a non-decreasing function of depth).

    Time complexity: O($b^d$)
    Space complexity: O($b \times d$)

    \quickimage{AIML/cap3-017.png}{.5}

    \item \bb{Bidirectional Search} - Search both from initial node and from the gold node. Note however that can only be used when a goal node is known and when the parent nodes can be computed given its child (through the sets of available actions). It's complete (if breath-first in both directions) and Optimal, if the step costs are equal.

    Time and space complexity: O($b^{d/2}$)

    \quickimage{AIML/cap3-018.png}{1}
\end{itemize}

A summary of the above analysis:

\quickimage{AIML/cap3-019.png}{.7}

A \bb{General Search Algorithm} can be formulated in the following way:

\quickimage{AIML/cap3-020.png}{.6}

Finally, there are problem dependent and problem independent details. The search strategies are problem independent, but how we define the actions, states, ect\dots is problem dependent. And the way we see and think about the problem can be highly related to the way we represent it.

An incredibly well formulated example is the Mutilated Chess Board problem. If we take just the squares of the corners of a chess board, can we still fill the whole board with dominos (each domino takes 2 squares). It becomes slightly harder! If you keep removing squares it gets increasingly harder to figure out by head.

\quickimage{AIML/cap2-003.png}{.6}

However, if you represent the chess board as the remaining black and white pieces and notice that a domino piece must always cover one black and one white squares, then by taking those two corners then 30 black and 32 white squares will be remaining making it impossible to fill with dominos. As a matter of fact, accordingly with Gomory's Theorem is also possible to say that if 2 square of opposite colours are removed then is always possible to fill the board with dominos! More in: \href{https://en.wikipedia.org/wiki/Mutilated_chessboard_problem}{\ul{Mutilated chessboard problem}}

The bottom line is that the representation (problem dependent details) matters.

With this is mind, consider the following example:

Initial state with:
bedroom(3), living room(2), kitchen(3), hall(2), truck(0)

\begin{enumerate}[a)]
    \item State: $<pos, n_{bedroom}, n_{living}, n_{kitchen}, n_{hall}, n_{truck}>$
    \item Initial State: $<truck, 3,2,3,2,0>$
    \item $m$ for move, $p$ for push $<m_N, m_S, m_E, m_W, p_N, p_W, p_E, p_W >$. However, is only possible to push in directions where there are rooms (as for walking) and when there are boxes in the current room we are located in.
    \item A goal condition could be $n_{truck} = 10$. Another could be the sum of all rooms to be 0. But the first one is more elegant and also seems more general... We don't want to throw boxes out of the window.
\end{enumerate}

Sometimes, just finding the solution is enough. Some times, there's a best solution.

The heuristic (the only difference between informed and uninformed search) is a function of a state that gives us the appreciation we have for that state - how good that state is. If we want the best solution, we must have the heuristic function is key. If you just want a solution, that function can be much simpler or even nonexistent.

\subsection{Informed Search Strategies}
A problem-solving agent is a goal-based agent that acts on the environment,
leading him to go through a series of states in order to achieve the desired goal.

\bb{In this course, we only study the single-state problems}, meaning that continuous, dynamic, non-deterministic or partially-observable problems are out of scope.

\quickimage{AIML/cap3-021.png}{.6}

The difference between Informed and Uniformed is the heuristic function. In informed search, we know something about the problem that allows us to choose better paths while doing uninformed search the algorithm would simply cover all paths.

As a reminder, the Uniform search is nothing more than opening the one closest to the root first and discarding all repeated nodes with a longer path to them.

The \bb{evaluation function} $f(n)$ that outputs the value accordingly to which the nodes will be expanded first or not include as a component the \bb{heuristic function} $h(n)$, in case of informed search. One good example of an heuristic is the straight line distance. The closer something is in a straight line, probably the closer it is in general.

From now on, the only difference is in the evaluation function!
\begin{itemize}
    \item Greedy best-first search: uses $f(n) = h(n)$
    \item A* Search: uses $f(n) = g(n) + h(n)$ where $g(n)$ is the \bb{path cost} function. Exactly identical to Uniform-cost-search but has the additional contribution of $h(n)$
\end{itemize}

Depending on what we are doing our search on, graphs or trees, there are different requirements on the heuristic function to achieve optimality.
If graphs, then \bb{consistency} is required for optimality.
If the search is on trees, then \bb{admissibility} is enough for optimality.

But what is Admissibility and Consistency?

Admissibility is never overestimating the cost to reach the goal. For instances, the straight line distance is an optimistic distance and presents a good heuristic.

Consistency is exactly that. The heuristic in n must be smaller than the cost necessary to reach n' from n plus the heuristic in the previous node. In essence, the difference between heuristics in adjacent nodes can't me bigger than the cost of going from one to the other.

\quickimage{AIML/cap3-022.png}{.6}

Some light about heuristics:

\quickimage{AIML/cap3-023.png}{.6}
\quickimage{AIML/cap3-024.png}{.6}

Now, obviously, one of the heuristics will give results closer to the reality and the
other will underestimate more severely. \bb{Does this difference affects the quality of the heuristic?}

The quality of the heuristic can be assessed by the \bb{effective branching factor} $b^*$ .
The \bb{branching factor} of a tree is the maximum number of successors a node has. It is a useful measure to quantify the maximum number of nodes it will be necessary to expand. The effective branching factor is the necessary branching factor a uniform tree would have to have to expand as many nodes as were expanded in our tree.

Therefore, because A* does a better job (due to the heuristic), the solution will be a smaller branching factor than the uniform tree.

\quickimage{AIML/cap3-025.png}{.6}

%how to solve this shit?

If $h_2(n) \geq h_1(n)$ then $h_2$ dominates $h_1$ and domination translates directly into efficiency! Because A* using $h_2$ will never expand more nodes than using $h_1$.

This is true because all nodes with an evaluation smaller than the cost of the solution will be evaluated. Therefore, by making $h(n)$ as big as possible, less nodes will be in that set!

%Continue 3.6.2

\begin{center}
    \bb{Therefore it is very important to find an heuristic that estimates the distance to the solution as close to the real distance as possible.}
\end{center}

One way of coming up with good heuristics is to solve the relaxed problem perfectly:
a problem where there are no constraints, no movement constraints, no nothing\dots

Then that apply that heuristic to the constraint model because it will certainly underestimate but may be close to the actual value.

\quickimage{AIML/cap3-026.png}{.6}

Considering only one of them at the time:
\begin{itemize}
    \item From a), there's the Manhattan distance.
    \item From b) the Gasching's heuristic.
    \item From c), the misplaced tiles heuristic because the actual distance would be one movement.
\end{itemize}

If we have many heuristics, it may be hard to find a clear best heuristic. Therefore, one may simply use the maximum of them at each node as a new heuristic and that would be the best one and one that is still admissible.
\quickimage{AIML/cap3-027.png}{.6}

A curiosity, a program called ABSOLVER (Prieditis, 1993) was able to create relaxed problems from problem definitions and did output very useful results for Rubik's Cube and for 8-puzzle.

One other way of learning heuristics is from experience. By solving that kind of problem a few times, we start to know when we are getting closer and that can be coded into an heuristic.

\subsection{The best of formal and natural languages - First Order Logic}

The Chapter 8 of the book of the course is a wonderful read. Here is the key content:

One can define objects, relations (among objects) and functions (relations with an unique output for the given input).

\quickimage{AIML/cap3-029.png}{.6}

The \bb{domain} is the set of objects. Symbols come in three kinds: \bb{constant symbols}, these stand for objects, \bb{predicate symbols} that stand for relations and \bb{function symbols} which stand for functions. \ul{Symbols will begin wtith uppercase letters.}

\quickimage{AIML/cap3-030.png}{.6}


%! Author = tstreule

\section{Optical Biosensors}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	\subsection{Optical Methods}
%	%
%	\begin{itemize}
%		\item \underline{Reflection based} (ELM, SAR)\\
%			information through $\Delta\phi$ and $\Delta$amplitude
%		\item \underline{Interference based} (OIA, TINS)\\
%			information through color change \quad
%			very sensitive to $\Delta$thickness
%		\item \underline{Evanescent field} techniques (\textbf{SPR}, \textbf{OWLS}, RM, FTIR, SAR)\\
%			information through $\Delta n$ ($n$: refractive index)
%	\end{itemize}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{EM}
%
\textbf{Relations}:\\
$c_0 = \frac{1}{\sqrt{\epsilon_0\mu_0}}$ \hfill
$k_0 = \frac{2\pi}{\lambda_0} = \frac{\omega}{c_0} = \omega\sqrt{\epsilon_0\mu_0}$ \hfill
$k = \frac{2\pi n}{\lambda}$ \hfill
$n = \frac{c_0}{c} = \sqrt{\epsilon_r\mu_r} \simeq \sqrt{\epsilon_r}$
\formula{Dispersion relation}{k^2 = \epsilon\omega^2 = \epsilon k_0^2c_0^2 = k_0\frac{\epsilon}{\epsilon_0} = k_0^2\epsilon_r = (k_0n)^2}

\formbox{\textbf{Plane waves}}{\vec{E}(\vec{r},t) = \vec{E}_0\;\eu^{\iu(\vec{k}\vec{r}-\omega t)}} \\
whereby \hfill
$\partial_t \hat= -\iu\omega$, \hfill
$\partial_x \hat= \iu k_x$, \hfill
$\partial_z \hat= \iu k_z$, \hfill
$\partial_y \hat= 0$ (infinite extent)
\formula{Depth of penetration}{d_p = \frac{\lambda}{4\pi} \frac{1}{\sqrt{n\ped{inc}^2\sin^2\theta -n_2^2}}}
\quad (about $\unit[500]{nm}$)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Evanescent Field Techniques}
%
\formtex{\textit{Recap}}{Always \textbf{total reflection} for $n\ped{inc}>n_2$}
\formtex{Evanescence}{Negligible change of sensitivity compared to}
\formtex{~}{the size of the antibodies}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{SPR \textnormal{-- Surface Plasmon Resonance}}
%
\formtex{\textbf{Plasmon}}{\underline{quantum} of electron density wave in a metal}
\formtex{\textbf{Plasmon Polariton}}{mixt. of photon (diel.) and el. dens. wave (met.)}
\formtex{\textbf{SPP}}{field components point in dir. of propagation}

\formbox{Dispersion relation}{k_{z,i}^2 = k_0^2\epsilon_i-\beta^2}
\quad $i=d,m$
\formula{Mom. of inc. wave}{\highlight{\beta \coloneqq k_x} = \frac{\omega}{c} \frac{\epsilon_m\epsilon_d}{\epsilon_m+\epsilon_d} = k_0 \cdot N}
\formtex{~}{where $N$ effective refr. index of SP}  % $N = \sqrt{\frac{1}{n_c^2} {+} \frac{1}{\epsilon_m}}$

\begin{minipage}{.3\columnwidth}
    \includegraphics[width=.9\columnwidth]{Optical_SPR}
\end{minipage}\vspace{\boxmargin}
\begin{minipage}{.7\columnwidth-\boxmargin}
    \textbf{Launch a SPP}:
    \quad $0\leq k_{\vert\vert,\textrm{inc}} \leq k_0\;n\ped{inc}$\\
    must ensure \highlight{$\beta \overset{!}{=} k_{\vert\vert,\textrm{inc}} = k_0\;n\ped{inc}\;\sin\theta$}
    \quad $\theta\in[0,\frac{\pi}{2}]$

    $\implies$ \fbox{$n\ped{inc} \geq n\sqrt{\frac{\epsilon_m}{\epsilon_m+n_c^2}}$} \fbox{$\frac{\Delta\theta}{\Delta N} \hat= \pderiv{\theta}{N} = \frac{1}{n\ped{inc}\cos\theta} \simeq \frac{1}{n\ped{inc}}$}
\end{minipage}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{OWLS \textnormal{-- Optical Waveguide Lightmode Spectroscopy}}
%
\begin{minipage}{.5\columnwidth}
    \includegraphics[width=.9\columnwidth]{Optical_OWLS}
\end{minipage}%
\begin{minipage}{.5\columnwidth}
    $N \coloneqq n_F\sin\theta = n\ped{air}\sin\alpha + \frac{l\lambda}{\Lambda}$
    \vspace{2mm}\par
    Penetr. depth \quad \fbox{$\sigma \sim \frac{\lambda}{2\pi} \frac{1}{\sqrt{N^2-n_c^2}}$}
\end{minipage}

Waves have to be in phase (constr. interf.) $\to$ extremely sensitive

\formula{constr. interference}{\textcolor{gray}{0=}\;2\pi m \overset{!}{=} \phi_F + \phi_{FS} + \phi_{FAC}}
\quad $\phi$: phase shifts

\formula{Ansatz for \textit{3 layer model}}{\scriptsize
    \begin{cases}
        \text{Cover:}		& C \;\eu^{-\abs{k_{z,C}} \;(z-d_F/2)}\\
        \text{Waveguide:}	& B \;\eu^{\iu k_{z,F} z} + A \;\eu^{\iu k_{z,F} z}\\
        \text{Support:}	& D \;\eu^{\abs{k_{z,S}} \;(z+d_F/2)}
    \end{cases}
}

\formula{Idealized adlayer}{n_A = n_C + c_A\deriv{n}{c}}
\formbox{Mass calculation}{M = \diff_A \frac{n_A-n_C}{\diff n/\diff c}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Limitations}
%
%	Above methods are \textit{not usable for diagnostic purposes}.\\
%	For analyzing \textit{simple things} it is extremely accurate, but when the composition of the probe gets more complex (e.g. blood) your device is not usable.\\
%	However, because of the NSB problems, we cannot use it (see LOD).
Above methods not usable for \textit{diagnostic purpose} $\to$ NSB, LOD

\textbf{Solution}: diffractometric biosensors (Focal Molography)


\XtoCBlock{PID}
\label{block:PID}
\begin{figure}[H]\includegraphics{PID}\end{figure}

\begin{XtoCtabular}{Inports}
In & Control error input\tabularnewline
\hline
Init & Value which is loaded at initialization function call\tabularnewline
\hline
Enable & Enable == 0: Deactivation of block; Out set to 0

Enable 0->1: Preload of integral part

Enable == 1: Activation of block\tabularnewline
\hline
\end{XtoCtabular}

\begin{XtoCtabular}{Outports}
Out & \tabularnewline
\hline
\end{XtoCtabular}

\begin{XtoCtabular}{Mask Parameters}
Kp & Proportional Factor\tabularnewline
\hline
Ki & Integral Factor\tabularnewline
\hline
Kd & Derivative Factor\tabularnewline
\hline
fc & Cutoff frequency of realization low pass\tabularnewline
\hline
ts\_fact & Multiplication factor of base sampling time (in integer format)\tabularnewline
\hline
\end{XtoCtabular}

\subsubsection*{Description:}
PID controller:

    G(s) = Kp + Ki/s + Kd*s/(s/(2*pi*fc) + 1)

% include optional documentation file
\InputIfFileExists{\XcHomePath/Library/Control/Doc/PID_Info.tex}{\vspace{1ex}}{}

\subsubsection*{Implementations:}
\begin{tabular}{l l}
\textbf{FiP8} & 8 Bit Fixed Point Implementation\tabularnewline
\textbf{FiP16} & 16 Bit Fixed Point Implementation\tabularnewline
\textbf{FiP32} & 32 Bit Fixed Point Implementation\tabularnewline
\textbf{Float32} & 32 Bit Floating Point Implementation\tabularnewline
\textbf{Float64} & 64 Bit Floating Point Implementation\tabularnewline
\end{tabular}

\XtoCImplementation{FiP8}
\index{Block ID!3248}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & FiP8 \tabularnewline
\textbf{ID} & 3248 \tabularnewline
\textbf{Revision} & 1.0 \tabularnewline
\textbf{C filename} & PID\_FiP8.c \tabularnewline
\textbf{H filename} & PID\_FiP8.h \tabularnewline
\end{tabular}
\vspace{1ex}

8 Bit Fixed Point Implementation

\begin{XtoCtabular}{Controller Parameters}
b0 & Integral coefficient\tabularnewline
\hline
b1 & Proportional coefficient\tabularnewline
\hline
b0d & Derivational coefficient b0\tabularnewline
\hline
b1d & Derivational coefficient b1\tabularnewline
\hline
a0d & Derivational coefficient a0\tabularnewline
\hline
sfrb0 & Shift factor for PI coefficient b0\tabularnewline
\hline
sfrb1 & Shift factor for PI coefficient b1\tabularnewline
\hline
sfrd & Shift factor for D coefficients b0d and b1d\tabularnewline
\hline
in\_old & Input value of previous cycle\tabularnewline
\hline
i\_old & Integrator value of previous cycle\tabularnewline
\hline
d\_old & Derivative value of previous cycle\tabularnewline
\hline
enable\_old & Enable value of previous cycle\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int8          *In;
     int8          *Init;
     int8          *Enable;
     int8          Out;
     int8          b0;
     int8          b1;
     int8          b0d;
     int8          b1d;
     int8          a0d;
     int8          sfrb0;
     int8          sfrb1;
     int8          sfrd;
     int8          in_old;
     int16         i_old;
     int8          d_old;
     int8          enable_old;
} PID_FIP8;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/Control/Doc/Test_PID_FiP8.tex}{}{}
\fi
\XtoCImplementation{FiP16}
\index{Block ID!3249}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & FiP16 \tabularnewline
\textbf{ID} & 3249 \tabularnewline
\textbf{Revision} & 1.0 \tabularnewline
\textbf{C filename} & PID\_FiP16.c \tabularnewline
\textbf{H filename} & PID\_FiP16.h \tabularnewline
\end{tabular}
\vspace{1ex}

16 Bit Fixed Point Implementation

\begin{XtoCtabular}{Controller Parameters}
b0 & Integral coefficient\tabularnewline
\hline
b1 & Proportional coefficient\tabularnewline
\hline
b0d & Derivational coefficient b0\tabularnewline
\hline
b1d & Derivational coefficient b1\tabularnewline
\hline
a0d & Derivational coefficient a0\tabularnewline
\hline
sfrb0 & Shift factor for PI coefficient b0\tabularnewline
\hline
sfrb1 & Shift factor for PI coefficient b1\tabularnewline
\hline
sfrd & Shift factor for D coefficients b0d and b1d\tabularnewline
\hline
in\_old & Input value of previous cycle\tabularnewline
\hline
i\_old & Integrator value of previous cycle\tabularnewline
\hline
d\_old & Derivative value of previous cycle\tabularnewline
\hline
enable\_old & Enable value of previous cycle\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int16         *In;
     int16         *Init;
     int8          *Enable;
     int16         Out;
     int16         b0;
     int16         b1;
     int16         b0d;
     int16         b1d;
     int16         a0d;
     int8          sfrb0;
     int8          sfrb1;
     int8          sfrd;
     int16         in_old;
     int32         i_old;
     int16         d_old;
     int8          enable_old;
} PID_FIP16;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/Control/Doc/Test_PID_FiP16.tex}{}{}
\fi
\XtoCImplementation{FiP32}
\index{Block ID!3250}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & FiP32 \tabularnewline
\textbf{ID} & 3250 \tabularnewline
\textbf{Revision} & 1.0 \tabularnewline
\textbf{C filename} & PID\_FiP32.c \tabularnewline
\textbf{H filename} & PID\_FiP32.h \tabularnewline
\end{tabular}
\vspace{1ex}

32 Bit Fixed Point Implementation

\begin{XtoCtabular}{Controller Parameters}
b0 & Integral coefficient\tabularnewline
\hline
b1 & Proportional coefficient\tabularnewline
\hline
b0d & Derivational coefficient b0\tabularnewline
\hline
b1d & Derivational coefficient b1\tabularnewline
\hline
a0d & Derivational coefficient a0\tabularnewline
\hline
sfrb0 & Shift factor for PI coefficient b0\tabularnewline
\hline
sfrb1 & Shift factor for PI coefficient b1\tabularnewline
\hline
sfrd & Shift factor for D coefficients b0d and b1d\tabularnewline
\hline
in\_old & Input value of previous cycle\tabularnewline
\hline
i\_old & Integrator value of previous cycle\tabularnewline
\hline
d\_old & Derivative value of previous cycle\tabularnewline
\hline
enable\_old & Enable value of previous cycle\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int32         *In;
     int32         *Init;
     int8          *Enable;
     int32         Out;
     int32         b0;
     int32         b1;
     int32         b0d;
     int32         b1d;
     int32         a0d;
     int8          sfrb0;
     int8          sfrb1;
     int8          sfrd;
     int32         in_old;
     int64         i_old;
     int32         d_old;
     int8          enable_old;
} PID_FIP32;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/Control/Doc/Test_PID_FiP32.tex}{}{}
\fi
\XtoCImplementation{Float32}
\index{Block ID!3251}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & Float32 \tabularnewline
\textbf{ID} & 3251 \tabularnewline
\textbf{Revision} & 0.1 \tabularnewline
\textbf{C filename} & PID\_Float32.c \tabularnewline
\textbf{H filename} & PID\_Float32.h \tabularnewline
\end{tabular}
\vspace{1ex}

32 Bit Floating Point Implementation

\begin{XtoCtabular}{Controller Parameters}
b0 & Integral coefficient\tabularnewline
\hline
b1 & Proportional coefficient\tabularnewline
\hline
b0d & Derivational coefficient b0\tabularnewline
\hline
b1d & Derivational coefficient b1\tabularnewline
\hline
a0d & Derivational coefficient a0\tabularnewline
\hline
in\_old & Input value of previous cycle\tabularnewline
\hline
i\_old & Integrator value of previous cycle\tabularnewline
\hline
d\_old & Derivative value of previous cycle\tabularnewline
\hline
enable\_old & Enable value of previous cycle\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     float32       *In;
     float32       *Init;
     int8          *Enable;
     float32       Out;
     float32       b0;
     float32       b1;
     float32       b0d;
     float32       b1d;
     float32       a0d;
     float32       in_old;
     float32       i_old;
     float32       d_old;
     int8          enable_old;
} PID_FLOAT32;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/Control/Doc/Test_PID_Float32.tex}{}{}
\fi
\XtoCImplementation{Float64}
\index{Block ID!3252}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & Float64 \tabularnewline
\textbf{ID} & 3252 \tabularnewline
\textbf{Revision} & 0.1 \tabularnewline
\textbf{C filename} & PID\_Float64.c \tabularnewline
\textbf{H filename} & PID\_Float64.h \tabularnewline
\end{tabular}
\vspace{1ex}

64 Bit Floating Point Implementation

\begin{XtoCtabular}{Controller Parameters}
b0 & Integral coefficient\tabularnewline
\hline
b1 & Proportional coefficient\tabularnewline
\hline
b0d & Derivational coefficient b0\tabularnewline
\hline
b1d & Derivational coefficient b1\tabularnewline
\hline
a0d & Derivational coefficient a0\tabularnewline
\hline
in\_old & Input value of previous cycle\tabularnewline
\hline
i\_old & Integrator value of previous cycle\tabularnewline
\hline
d\_old & Derivative value of previous cycle\tabularnewline
\hline
enable\_old & Enable value of previous cycle\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     float64       *In;
     float64       *Init;
     int8          *Enable;
     float64       Out;
     float64       b0;
     float64       b1;
     float64       b0d;
     float64       b1d;
     float64       a0d;
     float64       in_old;
     float64       i_old;
     float64       d_old;
     int8          enable_old;
} PID_FLOAT64;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/Control/Doc/Test_PID_Float64.tex}{}{}
\fi


%2multibyte Version: 5.50.0.2953 CodePage: 65001

\documentclass{article}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%TCIDATA{OutputFilter=LATEX.DLL}
%TCIDATA{Version=5.50.0.2953}
%TCIDATA{Codepage=65001}
%TCIDATA{<META NAME="SaveForMode" CONTENT="1">}
%TCIDATA{BibliographyScheme=Manual}
%TCIDATA{Created=Wednesday, July 31, 2013 16:50:51}
%TCIDATA{LastRevised=Wednesday, July 31, 2013 17:20:44}
%TCIDATA{<META NAME="GraphicsSave" CONTENT="32">}
%TCIDATA{<META NAME="DocumentShell" CONTENT="Scientific Notebook\Blank Document">}
%TCIDATA{CSTFile=Math with theorems suppressed.cst}
%TCIDATA{PageSetup=72,72,72,72,0}
%TCIDATA{AllPages=
%F=36,\PARA{038<p type="texpara" tag="Body Text" >\hfill \thepage}
%}

\newtheorem{theorem}{Theorem}
\newtheorem{acknowledgement}[theorem]{Acknowledgement}
\newtheorem{algorithm}[theorem]{Algorithm}
\newtheorem{axiom}[theorem]{Axiom}
\newtheorem{case}[theorem]{Case}
\newtheorem{claim}[theorem]{Claim}
\newtheorem{conclusion}[theorem]{Conclusion}
\newtheorem{condition}[theorem]{Condition}
\newtheorem{conjecture}[theorem]{Conjecture}
\newtheorem{corollary}[theorem]{Corollary}
\newtheorem{criterion}[theorem]{Criterion}
\newtheorem{definition}[theorem]{Definition}
\newtheorem{example}[theorem]{Example}
\newtheorem{exercise}[theorem]{Exercise}
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{notation}[theorem]{Notation}
\newtheorem{problem}[theorem]{Problem}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{remark}[theorem]{Remark}
\newtheorem{solution}[theorem]{Solution}
\newtheorem{summary}[theorem]{Summary}
\newenvironment{proof}[1][Proof]{\noindent\textbf{#1.} }{\ \rule{0.5em}{0.5em}}
\input{tcilatex}

\begin{document}

\section{A more complex example}

Phillips curve

\[
\alpha _{\pi }\pi _{t}=c_{\pi }+\alpha _{\pi ,1}\pi _{t-1}+\alpha _{\pi
,2}\pi _{t-2}+\alpha _{y}y_{t-1}+\varepsilon _{\pi ,t}
\]

IS curve

\[
\beta _{y}y_{t}=c_{y}+\beta _{y,1}y_{t-1}+\beta _{y,2}y_{t-2}-\beta
_{r}\left( i_{t-1}-\pi _{t-1}\right) +\varepsilon _{y,t}
\]

Taylor rule

\[
\gamma _{i}i_{t}=c_{i}+\gamma _{i}\rho _{i}i_{t-1}+\gamma _{i}\left( 1-\rho
_{i}\right) \left( \gamma _{y}y_{t}+\gamma _{\pi }\pi _{t}\right)
+\varepsilon _{i,t}
\]

The original equation in Tao's pdf file is : $\gamma _{i}i_{t}=c_{i}+\gamma
_{i}\rho _{i}i_{t-1}-\gamma _{i}\left( 1-\rho _{i}\right) \left( \gamma
_{y}y_{t}+\gamma _{\pi }\pi _{t}\right) +\varepsilon _{i,t}$. I think the
minus is a typo

\subsection{Some important points}

\begin{itemize}
\item This example is simple

\item It is backward looking

\item Risk does not matter

\item estimation is faster... at least provided that we do not spend time
computing the steady state below

\item If the parameters switch, there are potentially multiple steady
states, which RISE easily handles both for backward looking models, like
this one, and for more general forward-looking models.

\item one potential issue is how to set bounds on non-structural parameters

\item This shows how RISE\ is flexible: One can easily set up an estimation
of such a model with sign restrictions.

\item It makes more sense to estimate SVARs in this way, rather than
thinking that letting the parameters wander where they want will reveal some
important economic insights: NO, NO and NO!!!
\end{itemize}

\section{The steady state}

\[
y_{t}=\frac{c_{y}-\frac{\beta _{r}c_{i}}{\gamma _{i}\left( 1-\rho
_{i}\right) }-\frac{\beta _{r}\left( \gamma _{\pi }-1\right) c_{\pi }}{%
\alpha _{\pi }-\alpha _{\pi ,1}-\alpha _{\pi ,2}}}{\beta _{y}-\beta
_{y,1}-\beta _{y,2}+\beta _{r}\gamma _{y}+\frac{\beta _{r}\left( \gamma
_{\pi }-1\right) \alpha _{y}}{\alpha _{\pi }-\alpha _{\pi ,1}-\alpha _{\pi
,2}}}
\]

\[
\pi _{t}=\frac{c_{\pi }}{\alpha _{\pi }-\alpha _{\pi ,1}-\alpha _{\pi ,2}}+%
\frac{\alpha _{y}}{\alpha _{\pi }-\alpha _{\pi ,1}-\alpha _{\pi ,2}}y_{t}
\]

\[
i_{t}=\frac{c_{i}}{\gamma _{i}\left( 1-\rho _{i}\right) }+\gamma
_{y}y_{t}+\gamma _{\pi }\pi _{t}
\]

\end{document}


\documentclass{article}

\usepackage{amsmath}
\usepackage{siunitx}
\usepackage{mathtools}
\usepackage{url}
\usepackage{makeidx} \makeindex

\DeclarePairedDelimiter\ceil{\lceil}{\rceil}
\DeclarePairedDelimiter\floor{\lfloor}{\rfloor}
\DeclareMathOperator{\arctantwo}{arctan2}

\begin{document}

\tableofcontents

\section{Introduction}

\par With the continuous technological advancements in solar radiation
applications, there will always be a demand for smaller uncertainty in
calculating the solar position. Many methods to calculate the solar
position have been published in the solar radiation literature,
nevertheless, their uncertainties have been greater than
$\pm$~\ang{0.01} in solar zenith and azimuth angle calculations, and
some are only valid for a specific number of years \cite{blanco}. \par
For example, Michalsky's calculations are limited to the period from
1950 to 2050 with uncertainty of greater than $\pm$~\ang{0.01}
\cite{michalsky}, and the calculations of Blanco-Muriel et al.'s are
limited to the period from 1999 to 2015 with uncertainty greater than
$\pm$~\ang{0.01} \cite{blanco}.\\ %

An example emphasizing the importance of reducing the uncertainty of
calculating the solar position to lower than $\pm$~\ang{0.01}, is the
calibration of pyranometers that measure the global solar
irradiance. During the calibration, the responsivity of the
pyranometer is calculated at zenith angles from \ang{0} to \ang{90} by
dividing its output voltage by th e reference global solar irradiance
($G$), which is a function of the cosine of the zenith angle
($\cos(\Theta)$). Figure 1 shows the magnitude of errors that the
\ang{0.01} uncertainty in $\Theta$ can contribute to the calculation of
$\cos(\Theta)$ , and consequently $G$ that is used to calculate the
responsivity.  Figure 1 shows that the uncertainty in $\cos(\Theta)$
exponentially increases as 2 reaches \ang{90} (e.g. at $\Theta$ equal to
\ang{87}, the uncertainty in $\cos(\Theta)$ is $0.7\%$, which can result in
an uncertainty of 0.35\% in calculating $G$; because at such large
zenith angles the normal incidence irradiance is approximately equal
to half the value of $G$). From this arises the need to use a solar
position algorithm with lower uncertainty for users that are
interested in measuring the global solar irradiance with smaller
uncertainties in the full zenith angle range from \ang{0} to
\ang{90}.\\ %

\par In this report we describe a procedure for a Solar Position
Algorithm (SPA) to calculate the solar zenith and azimuth angle with
uncertainties equal to $\pm$~\ang{0.0003} in the period from the year
-2000 to 6000. The procedure is adopted from \textit{The Astronomical
  Algorithms} \cite{meeus}, which is based on the Variations
Séculaires des Orbites Planétaires Theory (VSOP87) that was developed
by P. Bretagnon in 1982 then modified in 1987 by Bretagnon and Francou
\cite{meeus}. In this report, we summarize the complex algorithm
elements scattered throughout the book to calculate the solar
position, and introduce some modification to the algorithm to
accommodate solar radiation applications. For example, in \textit{The
  Astronomical Algorithms} \cite{meeus}, the azimuth angle is measured
westward from south, but for solar radiation applications, it is
measured eastward from north. Also, the observer’s geographical
longitude is considered positive west, or negative east from
Greenwich, while for solar radiation applications, it is considered
negative west, or positive east from Greenwich.\\ %

\par We start this report by:
\begin{itemize}
\item Describing the time scales because of the importance of using
  the correct time in the SPA;
\item Providing a step by step procedure to calculate the solar
  position and the solar incidence angle for an arbitrary surface
  orientation using the methods described in \textit{An Introduction
    to Solar Radiation} \cite{iqbal};
\item Evaluating the SPA against the \textit{Astronomical Almanac}
  (AA) data for the years 1994, 1995, 1996, and 2004.
\end{itemize}

\par Because of the complexity of the algorithm we included some
examples, in the Appendix, to give the users confidence in their step
by step calculations. We also included in the Appendix an explanation
of how to calculate the equation of time, sun transit (solar noon),
sunrise, sunset, and how to change the Julian Day to a Calendar
Date. We also included a C source code with header file, for all the
calculations in this report (except for the Julian Day to Calendar
Date conversion). The users can incorporate this module into their own
code by including the header file, declaring the SPA structure,
filling in the required input parameters into the strucWeture, and
then call the SPA calculation function. This function will calculate
all the output values and fill in the SPA structure for the user.\\ %

\par The users should note that this report is used to calculate the
solar position for solar radiation applications only, and that it is
purely mathematical and not meant to teach astronomy or to describe
the Earth rotation. For more description about the astronomical
nomenclature that is used through out the report, the user is
encouraged to review the definitions in the \textit{Astronomical
  Almanacs}, or other astronomical reference.

\section{Time Scale}

\par The following are the internationally recognized time scales:

\begin{itemize}
\item The Universal Time ($UT$), or Greenwich civil time, is based on
  the Earth’s rotation and counted from 0-hour at midnight; the unit
  is mean solar day \cite{meeus}. $UT$ is the time used to calculate
  the solar position in the described algorithm. It is sometimes
  referred to as UT1.
\item The International Atomic Time ($TAI$) is the duration of the
  System International Second (SI-second) and based on a large number
  of atomic clocks \cite{norwich}.
\item The Coordinated Universal Time ($UTC$) is the bases of most
  radio time signals and the legal time systems. It is kept to within
  0.9 seconds of $UT1$ ($UT$) by introducing one second steps to its
  value (leap second); to date the steps are always positive.
\item The Terrestrial Dynamical or Terrestrial Time ($TDT$ or $TT$) is
  the time scale of ephemerides for observations from the Earth
  surface.
\end{itemize}

\par The following equations describe the relationship between the above
time scales (in seconds):

\begin{equation}
  \label{eq:tt}
  TT = TAI + 32.184
\end{equation}

\begin{equation}
  \label{eq:ut}
  UT = TT - \Delta T
\end{equation}

\par where $\Delta T$ is the difference between the Earth rotation time and
the Terrestrial Time ($TT$). It is derived from observation only and
reported yearly in the Astronomical Almanac [5].

\begin{equation}
  \label{eq:ut1}
  UT = UT1 = UTC + \Delta UT1
\end{equation}

\par where $\Delta UT1$ is a fraction of a second, positive or negative value,
that is added to the $UTC$ to adjust for the Earth irregular
rotational rate. It is derived from observation, but predicted values
are transmitted in code in some time signals, e.g. weekly by the
U.S. Naval Observatory (USNO) [6].

\section{Procedure}

\subsection{Calculate the Julian and Julian Ephemeris Day, Century,
  and Millennium}

\par The Julian date starts on January 1, in the year - 4712 at 12:00:00
UT. The Julian Day ($JD$) is calculated using UT and the Julian
Ephemeris Day ($JDE$) is calculated using $TT$. In the following
steps, note that there is a 10-day gap between the Julian and
Gregorian calendar where the Julian calendar ends on October 4, 1582
($JD = 2299160$), and after 10-days the Gregorian calendar starts on
October 15, 1582.

\subsubsection{Calculate the Julian Day ($JD$)}

\begin{equation}
  \label{eq:jd}
  JD = \floor{365.25 \times (Y + 4716)} + \floor{30.6001 \times (M + 1)} + D + B - 1524.5
\end{equation}

\par where
\begin{itemize}
\item $\floor{x}$ is the integer of the calculated term (e.g. 8.7~=~8,
  8.2~=~8, and -8.7~`  8, etc.);
\item $Y$ is the year (e.g. 2001, 2002, 2018, etc.);
\item $M$ is the month of the year (e.g. 1 for January, etc.). Note
  that if $M = 1$ or $M = 2$, then $Y = Y - 1$ and $M = M + 12$. If
  $M > 2$, then $Y$ and $M$ are not changed;
\item $D$ is the day of the month with decimal time (e.g. for the
  second day of the month at 12:30:30 UT, $D = 2.521180556$);
\item $B$ is equal to
  \begin{itemize}
  \item $0$, for the Julian calendar (i.e. by using $B = 0$ in equation
    \ref{eq:jd}, $JD < 2299160$);
  \item $(2 - A + \floor{A/4})$) for the Gregorian calendar (i.e. by
    using $B = 0$ in equation \ref{eq:jd}, $JD > 2299160$), where $A
    = \floor{Y/100}$.
  \end{itemize}
\end{itemize}

\par For users who wish to use their local time instead of UT, change the
time zone to a fraction of a day (by dividing it by 24), then subtract
the result from $JD$. Note that the fraction is subtracted from $JD$
calculated before the test for $B < 2299160$ to maintain the Julian
and Gregorian periods.

\par Table \ref{tbl:jd} shows examples to test any implemented program
used to calculate the $JD$.

\subsubsection{Calculate the Julian Ephemeris Day ($JDE$)}

\begin{equation}
  \label{eq:jde}
  JDE = JD + \frac{\Delta T}{86400}
\end{equation}

\subsubsection{Calculate the Julian century ($JC$) and the Julian
  Ephemeris Century ($JCE$) for the 2000 standard epoch}

\begin{equation}
  \label{eq:jc}
  JC = \frac{JD - 2451545}{36525}
\end{equation}

\begin{equation}
  \label{eq:jce}
  JCE = \frac{JDE - 2451545}{36525}
\end{equation}

\subsubsection{Calculate the Julian Ephemeris Millennium ($JME$) for
  the 2000 standard epoch}

\begin{equation}
  \label{eq:jme}
  JME = \frac{JCE}{10}
\end{equation}

\subsection{Calculate the Earth heliocentric longitude, latitude, and
  radius vector ($L$, $B$, and $R$)}
\label{sec:earth_heliocentric}

\par “Heliocentric” means that the Earth position is calculated with
respect to the center of the sun.

\begin{enumerate}

\item \label{item:step_1} For each row of table
  \ref{tbl:earth_periodic_terms}, calculate the term $L0_i$ (in
  radians):

  \begin{equation}
    \label{eq:l0i}
    L0_i = A_i \times \cos\left(B_i + C_i \times JME\right)
  \end{equation}
  where
  \begin{itemize}
  \item $i$ is the $i$th row for the term $L0$ in table
    \ref{tbl:earth_periodic_terms};
  \item $A_i$, $B_i$ and $C_i$ are the values in the $i$th row and
    $A$, $B$ and $C$ columns in the table
    \ref{tbl:earth_periodic_terms}, for the term $L0$ (in radians).
  \end{itemize}

\item Calculate the term $L0$ (in radians):

  \begin{equation}
    \label{eq:l0}
    L0 = \sum_{i=0}^{n}L0_i
  \end{equation}
  \par where $n$ is the number of rows for the term $L0$ in table
  \ref{tbl:earth_periodic_terms}.

\item \label{item:step_3} Calculate the terms $L1$, $L2$, $L3$, $L4$,
  and $L5$ by using equations \ref{eq:l0i} and \ref{eq:l0} and
  changing the 0 to 1, 2, 3, 4, and 5, and by using their
  corresponding values in 4 columns $A$, $B$, and $C$ in table
  \ref{tbl:earth_periodic_terms} (in radians);

\item \label{item:step_4} Calculate the Earth heliocentric longitude,
  $L_r$ (in radians),

  \begin{equation}
    \label{eq:l}
    L_r = \frac{L0 + L1 \times JME + L2 \times JME^2 + L3 \times JME^3 + L4 \times JME^4 + L5 \times JME^5}{10^8}
  \end{equation}

\item \label{item:step_5} Calculate $L$ in degrees

  \begin{equation}
    \label{eq:l_in_degrees}
    L = \frac{L_r \times 180}{\pi}
  \end{equation}

  \par where $\pi$ is approximately equal to 3.1415926535898;

\item \label{tiem:step_6} Limit $L$ to the range from \ang{0} to
  \ang{360}. That can be accomplished by dividing $L$ by 360 and
  recording the decimal fraction of the division as $F$. If $L$ is
  positive, then the limited $L = 360 * F$ .If $L$ is negative, then
  the limited $L = 360 - 360 * F$;

\item \label{item:step_7} Calculate the Earth heliocentric latitude,
  $B$ (in degrees), by using table \ref{tbl:earth_periodic_terms} and
  steps \ref{item:step_1} through \ref{item:step_5} and by replacing
  all the $L$s by $B$s in all equations. Note that there are no $B2$
  through $B5$, consequently, replace them by zero in steps
  \ref{item:step_3} and \ref{item:step_4};

\item Calculate the Earth radius vector, $R$ (in Astronomical Units,
  AU), by repeating step \ref{item:step_7} and by replacing all $L$s
  by $R$s in all equations. Note that there is no $R5$, consequently,
  replace it by zero in steps \ref{item:step_3} and \ref{item:step_4}.

\end{enumerate}

\subsection{Calculate the geocentric longitude and latitude ($\Theta$ and
  $\beta$)}

\par “Geocentric” means that the sun position is calculated with respect
to the Earth center.

\begin{enumerate}
\item Calculate the geocentric longitude, $\Theta$ (in degrees)

  \begin{equation}
    \label{eq:theta}
    \Theta = L + 180
  \end{equation}

\item Limit $\Theta$ to the range from \ang{0} to \ang{360} as described in
  step \ref{item:step_6} in section \ref{sec:earth_heliocentric};

\item Calculate the geocentric latitude, $\beta$ (in degrees)

  \begin{equation}
    \label{eq:geo_lat}
    \beta = -B
  \end{equation}
\end{enumerate}

\subsection{Calculate the nutation in longitude and obliquity
  ($\Delta\Psi$ and $\Delta\varepsilon$)}

\begin{enumerate}
\item Calculate the mean elongation of the moon from the sun, $X0$ (in
  degrees)
  \begin{equation}
    \label{eq:x0}
    X0 = 297.85036 + 445267.111480 \times JCE - 0.0019142 \times JCE^2 + \frac{JCE^3}{189474}
  \end{equation}

\item Calculate the mean anomaly of the sun (Earth), $X1$ (in degrees)
  \begin{equation}
    \label{eq:x1}
    X1 = 357.52772 + 35999.050340 \times JCE - 0.0001603 \times JCE^2 - \frac{JCE^3}{300000}
  \end{equation}

\item Calculate the mean anomaly of the moon, $X2$ (in degrees),
  \begin{equation}
    \label{eq:x2}
    X2 = 134.96298 + 477198.867398 \times JCE + 0.0086972 \times JCE^2 + \frac{JCE^3}{56250}
  \end{equation}

\item Calculate the moon’s argument of latitude, $X3$ (in degrees),
  \begin{equation}
    \label{eq:x3}
    X3 = 93.27191 + 483202.017538 \times JCE - 0.0036825 \times JCE^2 + \frac{JCE^3}{327270}
  \end{equation}

\item Calculate the longitude of the ascending node of the moon’s mean
  orbit on the ecliptic, measured from the mean equinox of the date,
  $X4$ (in degrees),
  \begin{equation}
    \label{eq:x4}
    X4 = 125.04452 - 1934.136261 \times JCE + 0.0020708 \times JCE^2 + \frac{JCE^3}{450000}
  \end{equation}

\item For each row of table \ref{tbl:nutation_periodic_terms},
  calculate the terms $\Delta\Psi$ and $\Delta\varepsilon$ (in 0.0001of arc seconds)

  \begin{equation}
    \label{eq:delta_psi_i}
    \Delta\Psi_i = (a_i + b_i \times JCE) \times \sin\left(\sum_{j=0}^4 X_j \times Y_{i,j}\right)
  \end{equation}

  \begin{equation}
    \label{eq:delta_epsilon_i}
    \Delta\varepsilon_i = (c_i + d_i \times JCE) \times \cos\left(\sum_{j=o}^4 X_j \times Y_{i,j}\right)
  \end{equation}

  \par where
  \begin{itemize}
  \item $a_i$, $b_i$, $c_i$ and $d_i$ are the values listed in the
    $i$th row and columns $a$, $b$, $c$ and $d$ in table
    \ref{tbl:nutation_periodic_terms};
  \item $X_i$ is the $j$th $X$ calculated by using equation
    \ref{eq:x0} through \ref{eq:x4};
  \item $Y_{i,j}$ is the value listed in the $i$th row and $j$th $Y$
    column in table \ref{tbl:nutation_periodic_terms}.
  \end{itemize}

\item Calculate the nutation longitude $\Delta\Psi$ (in degrees)
  \begin{equation}
    \label{eq:delta_psi}
    \Delta\Psi = \frac{\sum_{i=0}^n\Delta\Psi_i}{36000000}
  \end{equation}

  \par where $n$ in the number of rows in table
  \ref{tbl:nutation_periodic_terms} ($n = 63$ rows in the table)

\item Calculate the nutation in obliquity $\Delta\varepsilon$ (in degrees)
  \begin{equation}
    \label{eq:delta_epsilon}
    \Delta\varepsilon = \frac{\sum_{i=0}^n\Delta\varepsilon_i}{36000000}
  \end{equation}
\end{enumerate}

\subsection{Calculate the true obliquity of the ecliptic $\varepsilon$ (in
  degrees)}

\begin{enumerate}
\item Calculate the mean obliquity of the ecliptic $\varepsilon_0$ (in arc
  seconds)
  \begin{equation}
    \label{eq:epsilon_0}
    \begin{split}
      \varepsilon_0 = & 84381.448 - 4680.93U - 1.55U^2 + 1999.25U^3 - \\
      & 51.38U^4 - 249.67U^5 - 39.05U^6 + 7.12U^7 + \\
      & 27.87U^8 + 5.79U^9 + 2.45U^{10}
    \end{split}
  \end{equation}

  \par where $U = \frac{JME}{10}$;

\item Calculate the true obliquity of the ecliptic, $\varepsilon$ (in degrees),

  \begin{equation}
    \label{eq:epsilon_0}
    \varepsilon = \frac{\varepsilon_0}{3600} + \Delta\varepsilon
  \end{equation}
\end{enumerate}

\subsection{Calculate the aberration correction, $\Delta\tau$ (in degrees)}

\begin{equation}
  \label{eq:delta_t}
  \Delta\tau = -\frac{20.4898}{3600 \times R}
\end{equation}

\subsection{Calculate the apparent sun longitude, $\lambda$ (in degrees)}

\begin{equation}
  \label{eq:lambda}
  \lambda = \Theta + \Delta\Psi + \Delta\tau
\end{equation}

\subsection{Calculate the apparent sidereal time at Greenwich at any
  given time, $\nu$ (in degrees)}

\begin{enumerate}
\item Calculate the mean sidereal time at Greenwich, $\nu_o$ (in
  degrees)

  \begin{equation}
    \label{eq:nu_0}
    \nu_0 = 80.46061837 + 360.98564736629 \times (JD - 2451545) + 0.000387933 \times JC^2 - \frac{JC^3}{38710000}
  \end{equation}

\item Limit $\nu_0$ to the range from \ang{0} to \ang{360} as described
  in step \ref{item:step_6} in section \ref{sec:earth_heliocentric};

\item Calculate the apparent sidereal time at Greenwich, $\nu$ (in
  degrees,

  \begin{equation}
    \label{eq:nu}
    \nu = \nu_0 + \Delta\Psi \times \cos(\varepsilon)
  \end{equation}
\end{enumerate}

\subsection{Calculate the geocentric sun right ascension, $\alpha$ (in
  degrees}

\begin{enumerate}
\item Calculate the sun right ascension, $\alpha$ (in radians),
  \begin{equation}
    \label{eq:alpha}
    \alpha = \arctan2\left(\frac{\sin(\lambda) \times \cos(\varepsilon) - \tan(\beta) \times \sin(\varepsilon)}{\cos(\lambda)}\right)
  \end{equation}

  \par where $\arctan2$ is an arctangent function that is applied to the
  numerator and the denominator (instead of the actual division) to
  maintain the correct quadrant of the $\alpha$ where $\alpha$ is in the range
  from $-\pi$ to $\pi$.
\end{enumerate}

\begin{equation}
  \label{eq:delta}
  \delta = \arcsin\left(\sin(\beta) \times \cos(\varepsilon) + \cos(\beta) \times \sin(\varepsilon) \times \sin(\lambda)\right)
\end{equation}

\begin{equation}
  \label{eq:delta_alpha}
  \Delta\alpha = \arctan2\left(\frac{-x \times \sin(\xi) \times \sin(H)}{\cos(\delta) - x \times \sin(\xi) \times \cos(H)}\right)
\end{equation}

\begin{equation}
  \label{eq:delta_e}
  \Delta e = \frac{P}{1010}\times\frac{283}{273 + T} \times \frac{1.02}{60 \times \tan\left(e_0 + \frac{10.3}{e_0 + 5.11}\right)}
\end{equation}

\appendix

\printindex

\bibliographystyle{ieeetr}
\bibliography{spa}

\end{document}


\documentclass[letterpaper]{article}

\usepackage{fullpage}
\usepackage{nopageno}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{tikz}
\usepackage[utf8]{luainputenc}
\usepackage{aeguill}
\usepackage{setspace}

\tikzstyle{edge} = [fill,opacity=.5,fill opacity=.5,line cap=round, line join=round, line width=50pt]
\usetikzlibrary{graphs,graphdrawing}
\usegdlibrary{trees}

\pgfdeclarelayer{background}
\pgfsetlayers{background,main}

\allowdisplaybreaks

\newcommand{\abs}[1]{\left\lvert #1 \right\rvert}

\begin{document}
\title{Notes}
\date{23 février, 2015}
\maketitle
no class 3/4, 3/6
\section*{6.1 planarity}
if a graph can be drawn on a plane without any crossings, it is called {\bfseries planar}

note that if it is planar, you can draw it without crossings with all straight lines.
\subsection*{examples}
$K_3$, $K_4$

\subsubsection*{drawing:}
geogebra.org

\subsection*{more}
we often think of planar graphs as collections of polygons (remember we can draw all planar graphs in straight lines)

picture on board is pentagon glued to one side of a square, and a triangle glued to another
when we have polygons glued together, then we can count things. things like
\begin{enumerate}
\item
faces, eg the polygons

for faces we have several bounded, and one unbounded

4
\item
edges

10
\item
vertices

8
\end{enumerate}

note that $V-E+F=2$

this generalizes off the plane, but the idea of ``faces'' kind of breaks down and we have to looks at cycles and such.

\section*{theorem}

if a graph is planar then $v-e+f=2$

\subsubsection*{proof}
by induction on edges. if you add an edge, then you are adding a vertex or a face

if $E=0$ and $G$ is connected then $G\cong K_1$. $1-0+1=2$ and so check. assume this is true for $e=k$. suppose $G$ is a tree with $e=k+1$. Now remove an edge that is part of a cycle and we have $e=k$ and number of faces is reduced by 1. Now $v-(e-1)+(f-1)=2$ by inductive hypothesis. adding the edge back in and we have $v-e+f=2$. Removing an edge not in a cycle reduced the number of vertices and $v-e+f=2$ similar to above.

\section*{theorem}
if $G$ is planar and $|G|\ge  4$ then $E\le 3V-6$. Proof crux: every face has at least 3 edges on it's boundary

contrapositive:
if $E>3V-6$ and $|G|\ge 4$ then $G$ is not planar.

\section*{homework}
6.1 numbers 1,2,5
\end{document}


% Created 2021-09-07 Tue 19:04
% Intended LaTeX compiler: pdflatex
\documentclass[presentation,aspectratio=169]{beamer}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{grffile}
\usepackage{longtable}
\usepackage{wrapfig}
\usepackage{rotating}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{amssymb}
\usepackage{capt-of}
\usepackage{hyperref}
\usepackage{khpreamble}
\usepackage{amssymb}
\usepgfplotslibrary{groupplots}
\newcommand*{\shift}{\operatorname{q}}
\pgfplotstableread[col sep=comma]{tank-sim.dta}\tanktable
\usetheme{default}
\author{Kjartan Halvorsen}
\date{\today}
\title{Process Automation Laboratory - Modeling second-order systems}
\hypersetup{
 pdfauthor={Kjartan Halvorsen},
 pdftitle={Process Automation Laboratory - Modeling second-order systems},
 pdfkeywords={},
 pdfsubject={},
 pdfcreator={Emacs 26.3 (Org mode 9.4.6)},
 pdflang={English}}
\begin{document}

\maketitle

\section{Second-order model critically damped}
\label{sec:orgb862bc8}
\begin{frame}[label={sec:orgf5d0ff1}]{Fitting a first-order model}
Assuming a plant model of first-order with time-constant \(T\)
\[  \quad \textcolor{green!50!black}{Y(s)} = \frac{K}{sT + 1}\textcolor{blue!80!black}{U(s)} \quad \overset{U(s) = \frac{u_f}{s}}{\Longrightarrow} \quad \textcolor{green!50!black}{y(t)} = u_f K\big( 1 - \mathrm{e}^{-\frac{t}{T}}\big)u_H(t)\]
\def\Tcnst{3}
\def\tdelay{0.0}
\def\ggain{2}
\def\uampl{0.8}
\pgfmathsetmacro{\yfinal}{\uampl*\ggain}
\pgfmathsetmacro{\yone}{0.283*\yfinal}
\pgfmathsetmacro{\ytwo}{0.632*\yfinal}
\pgfmathsetmacro{\tone}{\tdelay + \Tcnst/3}
\pgfmathsetmacro{\two}{\tdelay + \Tcnst}

\begin{center}
  \small
  \begin{tikzpicture}
    \begin{axis}[
    width=14cm,
    height=3.5cm,
    grid = both,
    xtick = {0,  \two},
    xticklabels = {0, $T$},
    ytick = {0, \ytwo, \uampl, \yfinal},
    yticklabels = {0,  $0.632y_f$, $u_f$, $y_f$},
    xmin = -0.2,
    %minor y tick num=9,
    %minor x tick num=9,
    %every major grid/.style={red, opacity=0.5},
    xlabel = {$t$},
    ]
      \addplot [thick, green!50!black, no marks, domain=0:10, samples=100] {\uampl*\ggain*(x>\tdelay)*(1 - exp(-(x-\tdelay)/\Tcnst)} node [coordinate, pos=0.9, pin=-90:{$y(t)$}] {};
      \addplot [const plot, thick, blue!80!black, no marks, domain=-1:10, samples=100] coordinates {(-1,0) (0,0) (0,\uampl) (10,\uampl)} node [coordinate, pos=0.9, pin=-90:{$u(t)$}] {};
    \end{axis}
  \end{tikzpicture}
\end{center}

\alert{Time-constant:} Find the time \(t=T\) at which the response has reached 63.2\% of its final value

\alert{Gain:} \(y_f = \lim_{t\to\infty}y(t) = Ku_f \quad \Rightarrow \quad K = \frac{y_f}{u_f}\)
\end{frame}

\begin{frame}[label={sec:org4f4a767}]{Second-order models}
\end{frame}
\begin{frame}[label={sec:org023a2dc}]{Two first-order models in series}
\begin{center}
\begin{tikzpicture}
  \node {\includegraphics[width=0.4\linewidth]{../../figures/tank-with-hole-no-variables}};
  \node at (5.2,-2.06) {\includegraphics[width=0.4\linewidth]{../../figures/tank-with-hole-no-variables}};
\end{tikzpicture}
\end{center}

\begin{center}
  \begin{tikzpicture}[node distance=22mm, block/.style={rectangle, draw, minimum width=15mm}, sumnode/.style={circle, draw, inner sep=2pt}]

    \node[coordinate] (input) {};
    \node[block, right of=input, node distance=20mm] (plant1)  {$G_1(s)$};
    \node[block, right of=plant1, node distance=26mm] (plant2)  {$G_2(s)$};
    \node[coordinate, right of=plant2, node distance=20mm] (output) {};

    \draw[->] (input) -- node[above, pos=0.3] {$u(t)$} (plant1);
    \draw[->] (plant1) -- node[coordinate, ] (mp) { } (plant2);
    \draw[->] (plant2) -- node[above, near end] {$y(t)$} (output);
    \draw[red] (plant1.south west) ++(-4mm,-10mm) rectangle ++(49mm, 20mm);

    \node[red,below of=mp, node distance=10mm] {$G(s) = G_1(s)G_2(s)$};
  \end{tikzpicture}
\end{center}
\end{frame}

\begin{frame}[label={sec:orge105e70}]{Fitting second-order critically-damped model}
\alert{Model with two identical time-constants.}
Assuming model
\[ \textcolor{green!50!black}{Y(s)} = \frac{K}{(s\tau + 1)^2}\textcolor{blue!80!black}{U(s)} \quad \overset{U(s) = \frac{u_f}{s}}{\Longrightarrow} \quad \textcolor{green!50!black}{y(t)} = u_f K\Big( 1 - (1+\frac{t}{\tau}\big)\mathrm{e}^{-\frac{t}{\tau}}\Big)u_H(t)\]
\def\Tcnst{2}
\def\tdelay{0.0}
\def\ggain{2}
\def\uampl{0.8}
\pgfmathsetmacro{\yfinal}{\uampl*\ggain}
\pgfmathsetmacro{\ytwo}{\yfinal*(1-2*exp(-1))}
\pgfmathsetmacro{\two}{\tdelay + \Tcnst}

\begin{center}
  \begin{tikzpicture}
    \begin{axis}[
    width=14cm,
    height=4.5cm,
    grid = both,
    xtick = {0, \two},
    xticklabels = {0,  $\tau$},
    ytick = {0, \ytwo, \uampl, \yfinal},
    yticklabels = {0, $ $, $u_f$, $y_f$},
    xmin = -0.2,
    clip = false,
    %minor y tick num=9,
    %minor x tick num=9,
    %every major grid/.style={red, opacity=0.5},
    ]
      \addplot [thick, green!50!black, no marks, domain=0:11, samples=100] {\uampl*\ggain*(x>\tdelay)*(1 - (1+x/\Tcnst)*exp(-(x-\tdelay)/\Tcnst)} node [coordinate, pos=0.9, pin=-90:{$y(t)$}] {};
      \addplot [const plot, thick, blue!80!black, no marks, domain=-1:11, samples=100] coordinates {(-1,0) (0,0) (0,\uampl) (11,\uampl)} node [coordinate, pos=0.9, pin=-90:{$u(t)$}] {};
      \node at (axis cs: 11, -0.3) {$t$};
    \end{axis}
  \end{tikzpicture}
\end{center}

\alert{Individual activity} Evaluate the response \(y(t)\) at the time instants \(t=\tau\)!
\end{frame}

\begin{frame}[label={sec:org65aa28d}]{Fitting second-order critically-damped model}
\alert{Model with two identical time-constants.}
Assuming model
\[ \textcolor{green!50!black}{Y(s)} = \frac{K}{(s\tau + 1)^2}\textcolor{blue!80!black}{U(s)} \quad \overset{U(s) = \frac{u_f}{s}}{\Longrightarrow} \quad \textcolor{green!50!black}{y(t)} = u_f K\Big( 1 - (1+\frac{t}{\tau}\big)\mathrm{e}^{-\frac{t}{\tau}}\Big)u_H(t)\]
\def\Tcnst{2}
\def\tdelay{0.0}
\def\ggain{2}
\def\uampl{0.8}
\pgfmathsetmacro{\yfinal}{\uampl*\ggain}
\pgfmathsetmacro{\ytwo}{\yfinal*(1-2*exp(-1))}
\pgfmathsetmacro{\ytwofactor}{(1-2*exp(-1))}
\pgfmathsetmacro{\two}{\tdelay + \Tcnst}

\begin{center}
  \begin{tikzpicture}
    \begin{axis}[
    width=14cm,
    height=4.5cm,
    grid = both,
    xtick = {0, \two},
    xticklabels = {0,  $\tau$},
    ytick = {0, \ytwo, \uampl, \yfinal},
    yticklabels = {0, $\ytwofactor y_f$, $u_f$, $y_f$},
    xmin = -0.2,
    clip = false,
    %minor y tick num=9,
    %minor x tick num=9,
    %every major grid/.style={red, opacity=0.5},
    ]
      \addplot [thick, green!50!black, no marks, domain=0:11, samples=100] {\uampl*\ggain*(x>\tdelay)*(1 - (1+x/\Tcnst)*exp(-(x-\tdelay)/\Tcnst)} node [coordinate, pos=0.9, pin=-90:{$y(t)$}] {};
      \addplot [const plot, thick, blue!80!black, no marks, domain=-1:11, samples=100] coordinates {(-1,0) (0,0) (0,\uampl) (11,\uampl)} node [coordinate, pos=0.9, pin=-90:{$u(t)$}] {};
      \node at (axis cs: 11, -0.3) {$t$};
    \end{axis}
  \end{tikzpicture}
\end{center}

\[ y_f = \lim_{t\to\infty} y(t) = u_f K \quad \Rightarrow \quad K = \frac{y_f}{u_f}. \]
\end{frame}

\begin{frame}[label={sec:org2f585e4}]{Fitting second-order critically-damped model}
\small

Assuming model
\[ \textcolor{green!50!black}{Y(s)} = \frac{K}{(s\tau + 1)^2}\textcolor{blue!80!black}{U(s)} \quad \overset{U(s) = \frac{u_f}{s}}{\Longrightarrow} \quad \textcolor{green!50!black}{y(t)} = u_f K\Big( 1 - (1+\frac{t}{\tau}\big)\mathrm{e}^{-\frac{t}{\tau}}\Big)u_H(t)\]

\begin{center}
\begin{tikzpicture}
\begin{groupplot}[
group style={
     group name=timeplot,
     group size=1 by 2,
     xlabels at=edge bottom,
     horizontal sep=5mm,
     vertical sep=5mm,
   },
    width=14cm,
    height=2.8cm,
    grid = both,
    minor x tick num=4,
    every major grid/.style={red, opacity=0.8},
    xlabel = {t [s]},
    xmin=0,
    xmax=600,
    ]
    \nextgroupplot[ytick={0.05, 0.065},]
      \addplot [thick, blue!50!black, no marks, ]  table[x = 0, y = 2] from \tanktable;
    \nextgroupplot[ytick={1.28, 2.15}, height=3.6cm, minor y tick num=7,]
      \addplot [thick, green!50!black, no marks, ]  table[x = 0, y = 1] from \tanktable;
    \end{groupplot}
  \end{tikzpicture}
\end{center}

\alert{Activity} Determine the parameters of the model from the experimental data.
\end{frame}

\section{Second-order model under-damped}
\label{sec:orge93ea05}

\begin{frame}[label={sec:orge2eae9b}]{Second-order under-damped models}
A system with ODE
$$ \ddot{y} + 2\zeta\omega_n\dot{y} + \omega_n^2 y = \omega_n^2 u, $$
becomes in the Laplace domain
$$ Y(s) = \frac{\omega_n^2}{s^2 + 2\zeta\omega_n s + \omega_n^2} U(s). $$
\begin{columns}
\begin{column}{0.4\columnwidth}
\begin{itemize}
\item \alert{\(\zeta\)} is called the \emph{damping ratio}.
\item \alert{\(\omega_n\)} is called the \emph{natural frequency} (of the system).
\end{itemize}
\end{column}

\begin{column}{0.6\columnwidth}
\begin{center}
    \includegraphics[width=4cm]{../../figures/implane-second-order-poles}
\end{center}
\end{column}
\end{columns}
\end{frame}

\begin{frame}[label={sec:org7b1d386}]{Second-order under-damped models}
$$ Y(s) = \frac{\omega_n^2}{s^2 + 2\zeta\omega_n s + \omega_n^2} U(s), \qquad \overset{U(s) = \frac{u_f}{s}}{\Longrightarrow} $$
$$     y(t) = 1 - \frac{\mathrm{e}^{-\zeta\omega_nt}}{\sqrt{1-\zeta^2}} \sin\big( \sqrt{1-\zeta^2}\omega_n t + \phi \big) $$

\begin{columns}
\begin{column}{0.3\columnwidth}
\begin{center}
    \includegraphics[width=4cm]{../../figures/implane-second-order-poles}
\end{center}
\end{column}

\begin{column}{0.7\columnwidth}
\begin{center}
    \includegraphics[width=8cm]{../../figures/step-response-specifications}
\end{center}
\end{column}
\end{columns}
\end{frame}

\begin{frame}[label={sec:org6ca1ae1}]{Second-order under-damped models}
\begin{columns}
\begin{column}{0.3\columnwidth}
\begin{center}
    \includegraphics[width=4cm]{../../figures/implane-second-order-poles}
\end{center}

\[    t_r \approx \frac{\pi}{2\omega_n}, \qquad   t_s \approx \frac{4}{\zeta\omega_n}, \]
\end{column}
\begin{column}{0.7\columnwidth}
\begin{center}
    \includegraphics[width=8cm]{../../figures/step-response-specifications}
\end{center}

\[    t_p \approx \frac{\pi}{\sqrt{1 - \zeta^2}\omega_n}, \qquad    \zeta \approx \sqrt{\frac{(\ln \frac{PO}{100})^2}{\pi^2 + (\ln \frac{PO}{100})^2}} \]
\end{column}
\end{columns}
\end{frame}

\begin{frame}[label={sec:orgb1998e9}]{Second-order under-damped models}
\alert{Activity in pairs} Determine the poles of the system!
\begin{columns}
\begin{column}{0.3\columnwidth}
\begin{center}
    \includegraphics[width=4cm]{../../figures/implane-second-order-poles}
\end{center}

\[    t_s \approx \frac{4}{\zeta\omega_n}, \]
\end{column}
\begin{column}{0.7\columnwidth}
\begin{center}
\begin{tikzpicture}
   \node[anchor=south west] {    \includegraphics[width=8cm]{../../figures/step-response-specifications}};
   \draw[red] (2.2,4.2) -- ++(-1.2,0) node[left] {$1.3 y_f$};
   \draw[red, dotted] (3.7,0.8) -- ++(0,-0.3) node[below] {$2$};

\end{tikzpicture}
\end{center}

\[   \zeta \approx \sqrt{\frac{(\ln \frac{PO}{100})^2}{\pi^2 + (\ln \frac{PO}{100})^2}} \]
\end{column}
\end{columns}
\end{frame}
\end{document}


\documentclass[10pt,a4paper]{article}
\usepackage[latin1]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{bbm}
\author{Daniel Frederico Lins Leite}
\begin{document}
	\section{Exercise 2.1}
	Suppose each of K classes has an associated target $t_k$, which is a vector of all zeros, except a one in the k-th position. Show that classifying to the largest element of \^{y} amounts to choosing the closest target, $argmin_k ||t_k - \hat{y}||$, if the elements of \^{y} sum to one.

	\subsection{Interpretation}
	This problem can be interpreted as a "target coding scheme". This specific target coding is can be found in the following papers:

	\url{http://ieeexplore.ieee.org/document/88570/}\\
	\url{https://www.researchgate.net/publication/3191927_Optimized_feature_extraction_and_the_Bayes_decision_in_feed-forwardclassifier_networks}
	\begin{quote}
		This may be viewed as a gain matrix in which the gain of
		assigning to class j a pattern which belongs to class i is zero
		($i \ne j$) , but is unity for correct classification.
	\end{quote}

	\url{http://personal.ie.cuhk.edu.hk/~ccloy/files/aaai_2015_target_coding.pdf}
	\begin{quote}
		The 1-of-K coding, containing vectors of length K, with the k-th element as one and the remaining zeros, is typically used along with a softmax function for classification. Each element in a 1-of-K code represents a probability of a specific class.
	\end{quote}

	This paper also contains a more general definition of target coding, but it is not necessary for this exercise.

	Following, we can say that:

	\begin{align*}
		t = \left[ \begin{array}{c}
		t_1 \\
		t_2 \\
		\vdots \\
		t_K \end{array} \right] = \left[ \begin{array}{cccc}
		1 & 0 & \dots & 0 \\
		0 & 1 & \dots & 0 \\
		\vdots & \vdots & \ddots & \vdots \\
		0 & 0 & \dots & 1 \end{array} \right]
	\end{align*}

	In the problem, $\hat{y}$ can be considered as the prediction of a vector $x$ such that $y_k$ is the probability of $x$ being of the class $k$. That is why the sum of $y_k$ is equal to $1$.This also demands that $y_k$ are greater than $0$, although this does not make difference for this particular exercise.

	And now we arrive to the proof part: the k in which the $\hat{y}_k$ is the greatest, the class that we would choose in our prediction is the same $k$ of the $t_k$ that is nearer to the $\hat{y}$. In mathematical symbols:

	\begin{align*}
		\arg\min_k ||\hat{y}-t_k||\\
	\end{align*}

	\subsection{Solution}

	\begin{align*}
		K &> 0\\
		\\
		x &\in \Re^N\\
		y &= f(x)\\
		&	\sum_{i=1}^{K}{y_i} = 1\\
		&	y_i \ge 0, i \in {1,...,K}\\
		\\
		1 &\ge k \ge K\\
		t_k &= (t_{k1},...,t_{ki},...,t_{kK}), t_{ki} = \begin{cases}
			0 &\mbox{if } i \neq k\\
			1 &\mbox{if } i = k
		\end{cases}
		\\
		\arg\min_k||t_k - \hat{y}|| &= \arg\min_k||y-t_k||^2\\
		&= \arg\min_k\sum_{i=1}^{K}{(y_i-t_{ki})}^2\\
		&= \arg\min_k\sum_{i=1}^{K}{(y_{i}^2-2y_{i}t_{ki}+t_{ki}^2)}\\
		&= \arg\min_k\big[\sum_{i=1}^{K}{y_{i}^2}+\sum_{i=1}^{K}{(-2y_{i}t_{ki}+t_{ki}^2)}\big]
	\end{align*}
	Since $\sum_{i=1}^{K}{y_{i}^2}$ is a constant and does not depend on k
	\begin{align*}
		&= \arg\min_k \sum_{i=1}^{K}{(-2y_{i}t_{ki}+t_{ki}^2)}\\
		&= \arg\min_k\big[\sum_{i=1}^{K}{(-2y_{i}t_{ki})}+\sum_{i=1}^{K}{t_{ki}^2}\big]\\
	\end{align*}
	Since $\sum_{i=1}^{K}{t_{ki}^2} = 1$
	\begin{align*}
		&= \arg\min_k\big[\sum_{i=1}^{K}{(-2y_{i}t_{ki})}+1\big]
	\end{align*}
	Since $\sum_{i=1}^{K}{y_{i}t_{ki}} = y_k$, because $t_k$ is zero in all but $i=k$ position.
	\begin{align*}
		&= \arg\min_k\big[-2*\sum_{i=1}^{K}{y_{i}t_{ki}}+1\big]\\
		&= \arg\min_k\big[-2y_k+1\big] &&\mbox{(argmax plus constant)}\\
		&= \arg\min_k\big[-2y_k\big] &&\mbox{(argmax times constant)}\\
		&= \arg\min_k\big[-y_k\big] &&\mbox{(argmax inverse argmin)}\\
		&= \arg\max_k\big[y_k\big] &&\mbox{(argmax inverse argmin)}
	\end{align*}

	Which give us that:
	\begin{align*}
		\arg\min_k ||\hat{y}-t_k|| &= \arg\max_k\big[y_k\big]
	\end{align*}

	This problem can be interpreted as the proof of why in book the author says:
	\begin{quote}
		With the 0-1 loss function [...] the solution is known as the Bayes classifier, and says that
		we classify to the most probable class, using the conditional (discrete) distribution $Pr(G|X)$.
	\end{quote}

	\section{Exercise 2.2}

	From the previous exercise, we know that the Bayes Classifier, will classify the point to the most probable class. So, the boundary is located exactly where there is no clear most probable class.
	To simplify let us imagine that we have just 2 classes.

	\begin{align*}
		P(K_1|X) = P(K_2|X)\\
		\frac{P(K_1,X)}{P(X)} = \frac{P(K_2,X)}{P(X)}\\
		\frac{P(X|K_1)P(K_1)}{P(X)} = \frac{P(X|K_2)P(K_2)}{P(X)}\\
	\end{align*}

	$P(X|K_i)$ is the same as the likelihood of seeing X using a generative model from the i-th class. If we suppose that all classes come from a Gaussian Distribution, this simplify to:

	\begin{align*}
		\frac{\mathcal{L}(\theta_1|X)P(K_1)}{P(X)} = \frac{\mathcal{L}(\theta_2|X)P(K_2)}{P(X)}\\
	\end{align*}

	To calculate $P(X)$ we can marginalize $X$ over all possibilities, in this case two, so:

	\begin{align*}
		P(X) &= \sum_{k\in K}{P(X|K=k)}\\
		&= \sum_{k\in K}{\mathcal{L}(\theta_k|X)}
	\end{align*}

	So now we have:

	\begin{align*}
		\frac{P(X|K_1)P(K_1)}{\sum_{k\in K}{\mathcal{L}(\theta_k|X)}} = \frac{P(X|K_2)P(K_2)}{\sum_{k\in K}{\mathcal{L}(\theta_k|X)}}\\
	\end{align*}

	But we can simplify it.

	\begin{align*}
		P(X|K_1)P(K_1) = P(X|K_2)P(K_2)\\
	\end{align*}

	We can do the same for $P(K_1)$

	\begin{align*}
		P(K_1) &= \int_{x\in X}{P(K_1|X)P(dx)}\\
		&= \int_{x\in X}{P(K_1|X)P(dx)}\\
		&= \int_{x\in X}{\mathcal{L}(X|\theta_1)P(dx)}
	\end{align*}

	Which give us the final formula:

	\begin{align*}
			P(X|K_1)\int_{x\in X}{\mathcal{L}(X|\theta_1)P(dx)} = P(X|K_2)\int_{x\in X}{\mathcal{L}(X|\theta_2)P(dx)}\\
	\end{align*}

	The first possible simplification is to estimate $P(K_i)$ and two possible ways:
	- First, we can say that they both have the same probability;
	- Second, if we have a dataset we can calculate them by
	\begin{align*}
		P(K_1) = \frac{\sum_{y_i\in Y}{\mathbbm{1}(y_i = k_1)}}{N}\\
		P(K_2) = \frac{\sum_{y_i\in Y}{\mathbbm{1}(y_i = k_2)}}{N}\\
	\end{align*}

	Equal Prior Distributions:

	In this case the equality can be simplified to

	\begin{align*}
	P(X|K_1) = P(X|K_2)\\
	\end{align*}

	For futher simplification we can imagine a two dimensional X:

	\begin{align*}
	P(x_1,x_2|K_1) = P(x_1,x_2|K_2)\\
	\end{align*}

	if we choose another simplification, that x1 and x2 and independent, we arrive at a Naive Bayer Classifier, and the equation become:

	\begin{align*}
	P(x_1|K_1)P(x_2|K_1) = P(x_1|K_2)P(x_2|K_2)
	\end{align*}

	with two classes and Gaussian distribution:
	Different mean, same variance = line/plane
	Same mean, different variance = circle/elipse
	general case = parabolic curve

	with more than two cases will be a piecewise combination of the above three cases.

	\begin{align*}
(\frac{1}{\sqrt{2\pi\sigma_1^2}}e^{-\frac{(x_1-\mu_1)^2}{2\sigma_1^2}})(\frac{1}{\sqrt{2\pi\sigma_1^2}}e^{-\frac{(x_2-\mu_1)^2}{2\sigma_1^2}}) &= (\frac{1}{\sqrt{2\pi\sigma_2^2}}e^{-\frac{(x_1-\mu_2)^2}{2\sigma_2^2}})(\frac{1}{\sqrt{2\pi\sigma_2^2}}e^{-\frac{(x_2-\mu_2)^2}{2\sigma_2^2}})\\
(\frac{1}{\sqrt{2\pi\sigma_1^2}})^2(e^{-\frac{(x_1-\mu_1)^2}{2\sigma_1^2}})(e^{-\frac{(x_2-\mu_1)^2}{2\sigma_1^2}}) &= (\frac{1}{\sqrt{2\pi\sigma_2^2}})^2(e^{-\frac{(x_1-\mu_2)^2}{2\sigma_2^2}})(e^{-\frac{(x_2-\mu_2)^2}{2\sigma_2^2}})\\
	A &= (\frac{1}{\sqrt{2\pi\sigma_1^2}})^2\\
	B &= (\frac{1}{\sqrt{2\pi\sigma_2^2}})^2\\
	C &= -\frac{1}{2\sigma^2}\\
	A(e^{\frac{(x_1-\mu_1)^2}{C}})(e^{\frac{(x_2-\mu_1)^2}{C}}) &= B(e^{\frac{(x_1-\mu_2)^2}{C}})(e^{\frac{(x_2-\mu_2)^2}{C}})\\
	A\frac{(e^{\frac{(x_1-\mu_1)^2}{C}})}{(e^{\frac{(x_1-\mu_2)^2}{C}})} &= B\frac{(e^{\frac{(x_2-\mu_2)^2}{C}})}{(e^{\frac{(x_2-\mu_1)^2}{C}})}\\
	Ae^{\frac{(x_1-\mu_1)^2}{C}*\frac{C}{(x_1-\mu_2)^2}} &= Be^{\frac{(x_2-\mu_2)^2}{C}*\frac{C}{(x_2-\mu_1)^2}}\\
	Ae^{\frac{(x_1-\mu_1)^2}{(x_1-\mu_2)^2}} &= Be^{\frac{(x_2-\mu_2)^2}{(x_2-\mu_1)^2}}\\
	ln(Ae^{\frac{(x_1-\mu_1)^2}{(x_1-\mu_2)^2}}) &= ln(Be^{\frac{(x_2-\mu_2)^2}{(x_2-\mu_1)^2}})\\
	ln(A)ln(e^{\frac{(x_1-\mu_1)^2}{(x_1-\mu_2)^2}}) &= ln(B)ln(e^{\frac{(x_2-\mu_2)^2}{(x_2-\mu_1)^2}})\\
	A'=ln(A)\\
	B'=ln(B)\\
	A'\frac{(x_1-\mu_1)^2}{(x_1-\mu_2)^2} &= B'\frac{(x_2-\mu_2)^2}{(x_2-\mu_1)^2}\\
	A'(\frac{x_1-\mu_1}{x_1-\mu_2})^2 &= B'(\frac{x_2-\mu_2}{x_2-\mu_1})^2\\
	(\frac{x_1-\mu_1}{x_1-\mu_2})^2 &= \frac{B'}{A'}(\frac{x_2-\mu_2}{x_2-\mu_1})^2\\
	\frac{x_1-\mu_1}{x_1-\mu_2} &= \sqrt{\frac{B'}{A'}(\frac{x_2-\mu_2}{x_2-\mu_1})^2}\\
	\frac{x_1-\mu_1}{x_1-\mu_2} &= (\frac{x_2-\mu_2}{x_2-\mu_1})\sqrt{\frac{B'}{A'}}\\
	C' = \sqrt{\frac{B'}{A'}}\\
	\frac{x_1-\mu_1}{x_1-\mu_2} &= C'(\frac{x_2-\mu_2}{x_2-\mu_1})\\
	\end{align*}

	We can simplify the left side of the equation, because:

	\begin{align*}
		\frac{x-\mu_1}{x-\mu_2} &= \frac{x-\mu_2+\mu_2+\mu_1}{x-\mu_2}\\
		&= \frac{x-\mu_2}{x-\mu_2}+\frac{\mu_2+\mu_1}{x-\mu_2}\\
		&= 1 + \frac{\mu_2+\mu_1}{x-\mu_2}
	\end{align*}

	and

	\begin{align*}
	\frac{x_2-\mu_2}{x_2-\mu_1} &= \frac{x_2-\mu_1+\mu_1-\mu_2}{x_2-\mu_1}\\
	&= \frac{x_2-\mu_1}{x_2-\mu_1}+\frac{\mu_1-\mu_2}{x_2-\mu_1}\\
	&= 1 +\frac{\mu_1-\mu_2}{x_2-\mu_1}
	\end{align*}
	cd
	\begin{align*}
	\frac{x_1-\mu_1}{x_1-\mu_2} &= C'(\frac{x_2-\mu_2}{x_2-\mu_1})\\
	1 + \frac{\mu_2+\mu_1}{x_1-\mu_2} &= C'(1 +\frac{\mu_1-\mu_2}{x_2-\mu_1})\\
	\frac{\mu_2+\mu_1}{x_1-\mu_2} &= C'(1 +\frac{\mu_1-\mu_2}{x_2-\mu_1}) - 1\\
	\frac{1}{x_1-\mu_2} &=\frac{C'(1 +\frac{\mu_1-\mu_2}{x_2-\mu_1}) - 1}{\mu_2+\mu_1}\\
	x_1-\mu_2 &=\frac{\mu_2+\mu_1}{C'(1 +\frac{\mu_1-\mu_2}{x_2-\mu_1}) - 1}\\
	x_1 &=\frac{\mu_2+\mu_1}{C'(1 +\frac{\mu_1-\mu_2}{x_2-\mu_1}) - 1} + \mu_2\\
	x_1 &=\frac{\mu_2+\mu_1}{\sqrt{\frac{ln(B)}{ln(A)}}(1 +\frac{\mu_1-\mu_2}{x_2-\mu_1}) - 1} + \mu_2\\
	x_1 &=\frac{\mu_2+\mu_1}{\sqrt{\frac{ln( (\frac{1}{\sqrt{2\pi\sigma_2^2}})^2)}{ln((\frac{1}{\sqrt{2\pi\sigma_1^2}})^2)}}(1 +\frac{\mu_1-\mu_2}{x_2-\mu_1}) - 1} + \mu_2\\
	\end{align*}

\end{document}