\section{Problem Definition}
\label{sec:definition}

Loosely speaking, the high-level objective in transient-detection is to locate intrinsicly(?)-varying objects in each recently shot image of the sky.
More formally and in the concept of this project, this objective can be defined as finding the mapping
\begin{equation}
  \label{eq:def1}
  (I_t,I_s) \longrightarrow S_t
\end{equation}
where $I_s$ is the recently captured image, namely the \emph{science image}. $I_t$ is the \emph{template} or \emph{reference} iamge, and $S_t$ is the set of \emph{true transients} to be detected.

However, this problem has traditionally been broken down into two subprolems, namely, \emph{image differencing}\footnote{or interchangeably, \emph{difference imaging}} and \emph{smart-thresholding}; the latter being the process of finding a threshold above which all the pixels in the diff image, $I_d$, will be seen as candidate transient sources:
\begin{equation}
  \label{eq:def2}
  (I_t,I_s) \xrightarrow{diff} I_d \xrightarrow{threshold} S_t
\end{equation}

\begin{figure}[h]
  \centering
  \includegraphics[width=.8\textwidth]{material/diagram}
  \caption{Coarse illustration of information flow through the Alert Production (AP) pipeline. Paths in blue and green illustrate the ``traditional'' and ``modern'' approaches respectively.}
  \label{fig:diagram}
\end{figure}

The \emph{thresholding} step has traditionally been implemented as a simple $5\sigma$-thresholding, but other auxilliary approaches may wrap this stage to make it \emph{smart}er -- figure~\ref{fig:diagram}

\section{Learning-based Approaches}
\label{sec:learning}
The above process is prone to false positives (contamination) and false negatives (misses). Learning-based approaches come into play to mitigate this...

In the context built in the previous section, a learning based approach can be implemented in two broad ways:
\begin{itemize}
\item starting off $I_d$ -- a.k.a traditional real/bogus classification.
\item starting off $(I_t,I_s)$ -- a.k.a end-to-end, TransiNet-style.
\end{itemize}

\footnote{The term 'detection' in the field of computer vision can be translated to localization+classification in the astrophysics' terminology}

Pros and cons of the two approaches come in the following sections. However, the current decision is to implement and test the two in parallel. Therefore we shall attempt to bring the two implementations close to eachother -- ideally unified.

\subsection{Basic Real/Bogus Classifier}

\begin{figure}[h]
  \centering
  \includegraphics[width=.6\textwidth]{material/rb-classifier}
  \includegraphics[width=.6\textwidth]{material/rb-classifier-mod}
  \caption{Classical Real/bogus classifier (top) and the modified 3D classifier (bottom)}
  \label{fig:rbdiagram}
\end{figure}

Input-output definition of the problem:
\begin{itemize}
  \item input: cutouts from diff image ($I_d$) with the potential transient at the center
  \item output: reliability score for the potential transient
\end{itemize}

Although the output of a classifier is categorical (i.e. a class label), we will be using the output before the last Softmax~\footnote{TBD} layer, which can be intepretted as a probability.

\subsubsection{Drawbacks}
\begin{itemize}
\item has no access to the temporal~\footnote{throughout this document the term ``temporal'' is used to represent the transition from a template/reference image to a science image. It has to do, but should not be confused with the ``real'' time axis!} behaviour of the source. This is by definition outsourced to the upstream image differencing module and hence there is no ``learned intelligence'' in processing the ``transient-ness'' of the candidate.
\item any ``miss'' (false negative) in the upstream modules is inherited and irrecoverable.
\item can only handle single object per cutout -- when there are multiple true transients, it \emph{has to} ignore the others.
\end{itemize}

The first two drawbacks are a result of having separated the temporal processing (i.e. image differencing) from the final classification, whereas the last one has to do with how the problem and solution are defined based on cutouts.

% \paragraph{The case of ambiguous negatives}
% As of now it is not quite clear what a ``negative'' is for training; in the broadest implementation it can be cutout that is not positive. But since the inputs to this module are the outputs of imdiff, one could only use ``bogus candidates'' as negatives, which is closer to what happens in practice, and may give better results.

\subsubsection{Benefits}
\label{sec:rb_benefits}

Although as discussed this is just a sub-optimal learning-based approach to this problem, it still has the advantage of \emph{interpretability}; the generated output might be too contamined with false alarms and (at the same time) missed true transients, but the process is fully transparent to the downstream users of the alerts and they have the possibility to develop their own post-processing blocks per need.

\subsubsection{What will be learned?}
Since the temporal behaviour of the candidates fed to this module is assumed, it is foreseeable that the neural network will eventually learn a concept close to ``PSF-ness'', true to its title; real/bogus classification.

\subsubsection{Modified 3D Real/Bogus Classifier}
In this implementation the classifier has access to the template, science image pairs along with the diff image. This allows the network to make use of the temporal behavior of the source too.
Note however that still the difference image has a key role in the process, as the images are cropped around the sources detected in the difference image.

\subsection{End-to-End Simultaneous Localization and Classification (~TransiNet)}

\begin{figure}[h]
  \centering
  \includegraphics[width=.8\textwidth]{material/transinet-teaser}
  \caption{End-to-end image differencing, localization and classification. The output has to be clean and complete \emph{by definition} }
  \label{fig:transinet-teaser}
\end{figure}

\begin{itemize}
  \item input: a pair of science,template images: $(I_t,I_s)$
  \item output: $S_t$, set of true transients
  \item intermediate output: a ``score image'' where scores are assigned per-pixel
\end{itemize}

Based on TransiNet~\cite{transinet}. Does full detection (localization + classification) simultaneously -- along with any necessary implicit steps.
Since the temporal and spatial behaviors are considered at the same time, the definition of the task of this module would be to find all the time-variable real astronomical sources -- corresponding to the high-level definition of the problem in \ref{sec:definition}.

\subsection{The score}
As the task definition embraces a recognition according to spatial \emph{and} temporal features simultaneously, the score needs to be defined carefully to capture both aspects.

There are multiple available options:
\begin{itemize}
\item simple binary classification -- the resulting score may not be quite informative
\item regression -- more difficult to define
\item multi-class classification -- difficult data annotation
\end{itemize}

If we go with regression... there are bogus detections, variables, ``appearing transients''
\begin{equation}
  s=\left| \frac{A_2-A_1}{A_2+A_1} \right|
\end{equation}

% \section{Notes from the template}

% \subsection{How to handle LSST standard references?}

% The papers should cite standard LSST references\footnote{See \url{https://github.com/lsst-pst/LSSTreferences}},
% where appropriate. For the usage, please see below.  These examples all use the ADS handle, unless they are
% project docs then the use the project handle like LSE-17.

% All are on the lsst-texmf which you can get from \url{http://lsst-texmf.lsst.io}

% \subsubsection{LSST System and Science}

% The LSST system (brief overview of telescope, camera and data management subsystems),
% science drivers and science forecasts are described in:

% \begin{itemize}
% \item LSST Science Requirements Document: \cite{LPM-17}.
% \item LSST overview paper: \cite{2008arXiv0805.2366I}.
% \item LSST Science Book: \cite{abell2009lsst}.
% \end{itemize}
% %------------------------------------------------------------------------------

% \subsubsection{Simulations}

% The LSST simulations are described in a series of papers. Use of the LSST simulations should cite the LSST simulations overview paper \cite{2014SPIE.9150E..14C} and the specific simulation tools used:

% \begin{itemize}
% \item LSST Catalogs (CatSim): \cite{2014SPIE.9150E..14C}
% \item Feature-Based Scheduler: \cite{2018arXiv181004815N}
% \item Operations Simulator (OpSim): Scheduler \cite{2016SPIE.9910E..13D}, SOCS \cite{2016SPIE.9911E..25R}
% \item Metrics Analysis Framework (MAF): \cite{2014SPIE.9149E..0BJ}
% \item Image simulations (Phosim): \cite{2015ApJS..218...14P}
% \item Sky brightness model: \cite{2016SPIE.9910E..1AY}
% \item LSST Performance for NEO (or moving object) discovery: \cite{2018Icar..303..181J}
% \end{itemize}
% %------------------------------------------------------------------------------

% \subsubsection{Data Management}

% LSST data management system and the data products are described in:

% \begin{itemize}
%   \item The LSST Data Management System: \cite{2015arXiv151207914J}
%   \item Data Products Definition Document: \cite{LSE-163}
% \end{itemize}
%  %------------------------------------------------------------------------------

% \subsubsection{Camera}

% \begin{itemize}
%    \item Design and development of the LSST camera: \cite{2010SPIE.7735E..0JK}
% \end{itemize}
% %------------------------------------------------------------------------------

% \subsubsection{Telescope and Site}

% \begin{itemize}
%    \item Telescope and site overview and status in 2014:  \cite{2014SPIE.9145E..1AG}
% \end{itemize}
% %------------------------------------------------------------------------------

% \subsubsection{System Engineering}

% \begin{itemize}
%    \item LSST systems engineering: \cite{2014SPIE.9150E..0MC}
%    \item System verification and validation: \cite{2014SPIE.9150E..0NS}
% \end{itemize}
% %


\documentclass[12pt,a4paper]{article}
\usepackage{algorithm, algpseudocode, amsmath, amssymb, csquotes, empheq, geometry, graphicx, hyperref, listings, multirow, physics, siunitx, subcaption, upgreek}
\usepackage[section]{placeins}
\usepackage[justification=centering]{caption}

\title{Computational Physics\\Problem Set 4}
\author{Saleh Shamloo Ahmadi\\Student Number: 98100872}
\date{October 22, 2021}

\hypersetup{colorlinks=true, urlcolor=cyan}
\newcommand{\percfig}{../fig/percolation}
\newcommand{\rwfig}{../fig/random-walk}

\begin{document}
	\maketitle
	\section{Percolation}
	Note: we simulate \emph{site percolation}.
	\subsection{Correlation Length}
	The correlation length $\xi$ is a measure of the radius of the maximum closed (non-infinite) cluster;
	This shows the maximum length of interactions before phase transition occures and the lattice either becomes
	homogenous or clusters are broken off.

	In our analysis, we use the maximum radius of gyration of closed clusters to measure the correlation length
	(any similar measure is valid).

	The correlation length diverges (or peaks, for a finite lattice) at the critical probability $p_c$ of forming sites
	in the lattice; This is because at higher probabilities, percolation happens frequently and there are less clusters
	and at lower probabilites, clusters break off more at smaller length scales.

	\newgeometry{left=0in, right=0in}
	\begin{figure}
		\centering
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/gyration-full-10}
		\end{subfigure}
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/gyration-full-20}
		\end{subfigure}
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/gyration-full-40}
		\end{subfigure}
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/gyration-full-80}
		\end{subfigure}
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/gyration-full-160}
		\end{subfigure}
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/gyration-full-320}
		\end{subfigure}
	\end{figure}
	\newgeometry{top=0.1in, bottom=0.1in, left=0in, right=0in}
	\thispagestyle{empty}
	\begin{figure}
		\centering
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/gyration-zoom-10}
		\end{subfigure}
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/gyration-zoom-20}
		\end{subfigure}
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/gyration-zoom-40}
		\end{subfigure}
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/gyration-zoom-80}
		\end{subfigure}
	\end{figure}
	\begin{figure}
		\centering
		\includegraphics[width=0.9\linewidth]{\percfig/gyration-zoom-160}
	\end{figure}
	\restoregeometry
	\begin{figure}
		\centering
		\includegraphics[width=\linewidth]{\percfig/gyration-zoom-320}
	\end{figure}
	Close to the critical probability $p_c$, the following relation holds:
	\begin{equation}
		\xi \sim \abs{p - p_c}^{-\nu}
	\end{equation}
	$\nu$ is called the \emph{critical exponent} for the correlation length $\xi$. In finite lattices, because
	the correlation length is bounded by the lattice length, this relation breaks down at probabilites very
	close to $p_c$. We can find the valuse of $\nu$ with two methods: direct calculation from finite lattices
	or extrapolation.

	In direct calculation, we can use linear regression for the relation
	\begin{equation}
		\log{\xi} = -\nu\log(p - p_c) + C.
	\end{equation}
	This is not especially accurate, because it is based on limited lattices that do not accurately represent unbounded
	trends; The edges of these lattices cut off emerging clusters.
	\begin{figure}
		\centering
		\includegraphics[width=\linewidth]{\percfig/critical-exp}
	\end{figure}
	\begin{figure}
		\centering
		\includegraphics[width=\linewidth]{\percfig/extrapolation}
	\end{figure}

	The extrapolation method is as follows. in finite lattices, the maximum correlation length is proportional to the
	lattice size, since the correlation length at $p_c$ is unbounded for infinite lattices, and is only bounded by the
	edges of the lattice in finite lattices. So, we can approximate the behavior of an infinite lattice by the relation
	\begin{equation}
		\abs{p_c(\infty) - p_c(L)}^{-\nu} = L,
	\end{equation}
	where $p_c(\infty)$ is the infinite lattice's critical probablity and $L$ is the size of a finite lattice.
	Extrapolating $p_c(\infty)$ and $\nu$ with a non-linear curve fit, we get
	\begin{equation}
		p_c(\infty) = 0.5925 ,\qquad \nu = 1.346.
	\end{equation}
	It can be proved that the exact value of $\nu$ is $4/3$ and larges simulations have shown that $p_c(\infty)$ for
	site percolation is $0.5927$, so the accuracy of the extrapolated values are quite good, considering the limited
	sample size.

	\subsection{Fractal Dimension}
	The percolation clusters exhibit fractal self-similar behavior. Using a simple depth-frist search algorithm,
	we can generate clusters in a lattice and calculate their size and radius of gyration to find their
	fractal dimension; If $s$ is the size of the cluster and $d_f$ is the fractal dimension
	\begin{equation}
		s \sim \xi^{d_f},
	\end{equation}
	so, by using linear regression for the relation
	\begin{equation}
		\log{s} = d_f\log{\xi} + C
	\end{equation}
	we can calculate the fractal dimension $d_f$.
	\newgeometry{top=0.5in, bottom=1.5in, left=0in, right=0in}
	\begin{figure}
		\centering
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/fractal-vis-50}
		\end{subfigure}
		\begin{subfigure}{0.45\linewidth}
			\centering
			\includegraphics[width=\linewidth]{\percfig/fractal-vis-65}
		\end{subfigure}
	\end{figure}
	\restoregeometry
	\newgeometry{top=1in, bottom=1.5in}
	\begin{figure}[htb!]
		\centering
		\includegraphics[width=\linewidth]{\percfig/fractal-vis-55}
	\end{figure}
	\restoregeometry
	\newgeometry{top=0.3in, bottom=0.3in, left=0in, right=0in}
	\thispagestyle{empty}
	\begin{figure}[htb!]
		\centering
		\includegraphics[width=0.8\linewidth]{\percfig/fractal-vis-59}
	\end{figure}
	\begin{figure}[htb!]
		\centering
		\includegraphics[width=0.8\linewidth]{\percfig/fractal-50}
	\end{figure}
	\begin{figure}[htb!]
		\centering
		\includegraphics[width=0.9\linewidth]{\percfig/fractal-55}
	\end{figure}
	\thispagestyle{empty}
	\begin{figure}[htb!]
		\centering
		\includegraphics[width=0.9\linewidth]{\percfig/fractal-59}
	\end{figure}
	\restoregeometry
	\section{1D Random Walk}
	\subsection{Variance}
	We can use the recurrence relation
	\begin{equation}
		x(t) = x(t-\tau) + al,
	\end{equation}
	where $a$ is $+1$ with probability $p$ and $-1$ with probability $q$, to find the variance.
	The calculation is as follows:
	\begin{align}
		\expval{x^2(t)} &= \expval{x^2(t-\tau)} + 2l\expval{ax(t-\tau)} + \expval{a^2}l^2 \\
		&= \expval{x^2(t-\tau)} + l^2 + 2l(p - q)\expval{x(t-\tau)} \\
		&= \expval{x^2(t-\tau)} + l^2 + 2l^2\qty(\frac{t}{\tau}-1)(p - q)^2
	\end{align}
	(Note that $a^2$ is always $1$, and since $a$ is dependant from $x$, $\expval{ax} = \expval{a}\expval{x}$.
	Also, I used $\expval{x(t)} = \frac{l}{\tau}(p-q)t$, which has already been proven in the lecture notes) \\
	Repeating the recurrence relation until it reaches $x(0) = 0$
	\begin{align}
		\expval{x^2(t)} &= \frac{tl^2}{\tau} + \frac{2l^2}{\tau}(p - q)^2 \sum_{n=1}^{t/\tau - 1} n\tau \\
		&= \frac{tl^2}{\tau}\qty[1 + \qty(\frac{t}{\tau} - 1)(p - q)^2].
	\end{align}
	Substituting into the variance,
	\begin{align}
		\sigma^2(t) &= \expval{x^2(t)} - \expval{x(t)}^2 \\
		&= \frac{tl^2}{\tau}\qty[1 + \qty(\frac{t}{\tau} - 1)(p - q)^2] - \frac{t^2l^2}{\tau^2}(p-q)^2 \\
		&= \frac{tl^2}{\tau}\qty[1 - (p - q)^2].
	\end{align}
	But
	\begin{equation}
		p+q = 1 \implies (p+q)^2 = 1 \implies p^2 + q^2 = 1 - 2pq,
	\end{equation}
	and using this to simplify the expression
	\begin{equation}
		\sigma^2(t) = \frac{tl^2}{\tau}\qty[1 - (p^2 + q^2) + 2pq] = \frac{tl^2}{\tau}\qty[1 - 1 + 2pq + 2pq]
	\end{equation}
	\begin{empheq}[box=\fbox]{equation}
		\sigma^2(t) = \frac{4l^2}{\tau}pqt
	\end{empheq}
	\subsection{Simulation}
	\begin{figure}
		\centering
		\includegraphics[width=\linewidth]{\rwfig/randomwalk-50}
	\end{figure}
	\begin{figure}
		\centering
		\includegraphics[width=\linewidth]{\rwfig/randomwalk-60}
	\end{figure}
	\begin{figure}
		\centering
		\includegraphics[width=\linewidth]{\rwfig/randomwalk-70}
	\end{figure}
	\begin{figure}
		\centering
		\includegraphics[width=\linewidth]{\rwfig/randomwalk-80}
	\end{figure}
	\FloatBarrier
	\subsection{Trapping (Absorbing) Boundary}
	In the following figures, $L$ is the length of the \enquote{path} i.e. the number of cells in the 1D grid.
	\begin{figure}[htb!]
		\centering
		\includegraphics[width=\linewidth]{\rwfig/randomwalk-trap-sim}
		\caption{Averaged over 100000 walks}
	\end{figure}
	\begin{figure}[htb!]
		\centering
		\includegraphics[width=\linewidth]{\rwfig/randomwalk-trap-exp}
		\caption{Calculated up to $t=100L$ where $t$ is the number of steps}
	\end{figure}
	\begin{figure}[htb!]
		\centering
		\includegraphics[width=\linewidth]{\rwfig/randomwalk-trap}
		\caption{As you can see, the expected lifetime is nearly equal to the average lifetime in the simulations}
	\end{figure}
\end{document}


% ===> this file was generated automatically by noweave --- better not edit it
\section{Introduction}

As a convenience to users, we provide a mechanism for declaring
nested coordinate systems.  This is particularly useful
for creating \emph{substructures} or \emph{subnets}.  Different
instances of a subnet may have the same relative placements
of nodes, but at different translations and orientations.

\section{Interface}

We support nested coordinate systems via a \emph{transformation stack}.
The entries in this stack data structures are all affine transformations that
take the current coordinate system to the global system.  New transformations
are \emph{composed} with the previous top-of-stack, so that if
$T_0$ is the current transformation to global coordinates and a
transformation $S$ is pushed onto the stack, then $T_0 S$ will
be the new transformation from current to global coordinates.

The transformation $T = Ax + b$ is given by a table of twelve entries
which represents the components of the matrix $[A; b]$ in column major
order.  A vector $x$ is given by a table with coordinate entries at
indices 1 to 3.  Note that the table can contain additional information
(e.g. a node name).  Part of the reason the transformation functions
overwrite the input vector table is so that entries besides those
at indices 1 to 3 can be retained unchanged.

The functions provided by this module are
\begin{itemize}
  \item {\Tt{}xform{\_}push(T)\nwendquote}: compose a transformation onto the stack
  \item {\Tt{}xform{\_}pop\nwendquote}: pop a level off the transformation stack
  \item {\Tt{}top{\_}xform(x)\nwendquote}: overwrite $x$ with $T_\mathit{top} x$,
        where $T_\mathit{top}$ is the top transform on the stack
  \item {\Tt{}xform{\_}apply(T,\ x)\nwendquote}: overwrite $x$ with $Tx$.
  \item {\Tt{}xform{\_}applyA(t,\ x)\nwendquote}: overwrite $x$ with $A_T x$,
        where $A_T$ is the linear part of the affine transform $T$.
  \item {\Tt{}xform{\_}compose(T,\ S)\nwendquote}: return $TS$
  \item {\Tt{}xform{\_}identity\nwendquote}: return the identity transform
  \item {\Tt{}xform{\_}ox(r),\ xform{\_}oy(r),\ xform{\_}oz(r)\nwendquote}:
        return right-handed rotations about the coordinate axes
  \item {\Tt{}xform{\_}translate(z)\nwendquote}: return a translation by the
        vector $z$
  \item {\Tt{}subnet(f)\nwendquote}: return a function which creates a nested
        coordinate system according to any {\Tt{}ox\nwendquote}, {\Tt{}oy\nwendquote},
        and {\Tt{}oz\nwendquote} parameters, calls {\Tt{}f\nwendquote}, and then pops the
        nested coordinate system.
\end{itemize}

\section{Implementation}

\nwfilename{xformstack.nw}\nwbegincode{1}\sublabel{NW4ZsHyK-4TVv9z-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-4TVv9z-1}}}\moddef{xformstack.lua~{\nwtagstyle{}\subpageref{NW4ZsHyK-4TVv9z-1}}}\endmoddef\nwstartdeflinemarkup\nwenddeflinemarkup
\LA{}data~{\nwtagstyle{}\subpageref{NW4ZsHyK-3zsvuH-1}}\RA{}
\LA{}functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}\RA{}
\nwnotused{xformstack.lua}\nwendcode{}\nwbegindocs{2}\nwdocspar

\subsection{The transform stack}

The size of the stack is maintained in the field $n$.

\nwenddocs{}\nwbegincode{3}\sublabel{NW4ZsHyK-3zsvuH-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-3zsvuH-1}}}\moddef{data~{\nwtagstyle{}\subpageref{NW4ZsHyK-3zsvuH-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwenddeflinemarkup
xform_stack = \{n = 0\};

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{4}\nwdocspar

Note that we compose new transformations onto the stack, interpreting
the transformation argument as a transformation into the current coordinates
instead of a transformation into the global coordinates.

\nwenddocs{}\nwbegincode{5}\sublabel{NW4ZsHyK-nRuDO-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{\relax}{NW4ZsHyK-nRuDO-2}\nwenddeflinemarkup
function xform_push(T)
  local n = xform_stack.n + 1
  if n == 1 then
    xform_stack[n] = T
  else
    xform_stack[n] = xform_compose(xform_stack[n-1], T);
  end
  xform_stack.n = n;
end

\nwalsodefined{\\{NW4ZsHyK-nRuDO-2}\\{NW4ZsHyK-nRuDO-3}\\{NW4ZsHyK-nRuDO-4}\\{NW4ZsHyK-nRuDO-5}\\{NW4ZsHyK-nRuDO-6}\\{NW4ZsHyK-nRuDO-7}\\{NW4ZsHyK-nRuDO-8}\\{NW4ZsHyK-nRuDO-9}\\{NW4ZsHyK-nRuDO-A}\\{NW4ZsHyK-nRuDO-B}\\{NW4ZsHyK-nRuDO-C}}\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{6}\nwdocspar

\nwenddocs{}\nwbegincode{7}\sublabel{NW4ZsHyK-nRuDO-2}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-2}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{NW4ZsHyK-nRuDO-1}{NW4ZsHyK-nRuDO-3}\nwenddeflinemarkup
function xform_pop()
  xform_stack.n = xform_stack.n - 1
end

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{8}\nwdocspar

\nwenddocs{}\nwbegincode{9}\sublabel{NW4ZsHyK-nRuDO-3}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-3}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{NW4ZsHyK-nRuDO-2}{NW4ZsHyK-nRuDO-4}\nwenddeflinemarkup
function top_xform(x)
  local n = xform_stack.n
  if n > 0 then
    return xform_apply(xform_stack[n], x)
  else
    return x
  end
end

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{10}\nwdocspar

\subsection{Transformation functions}

\nwenddocs{}\nwbegincode{11}\sublabel{NW4ZsHyK-nRuDO-4}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-4}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{NW4ZsHyK-nRuDO-3}{NW4ZsHyK-nRuDO-5}\nwenddeflinemarkup
-- Overwrite x with Tx
function xform_apply(T, x)
  local y1 = T[1]*x[1] + T[4]*x[2] + T[7]*x[3] + T[10];
  local y2 = T[2]*x[1] + T[5]*x[2] + T[8]*x[3] + T[11];
  local y3 = T[3]*x[1] + T[6]*x[2] + T[9]*x[3] + T[12];
  x[1] = y1;
  x[2] = y2;
  x[3] = y3;
  return x;
end

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{12}\nwdocspar

\nwenddocs{}\nwbegincode{13}\sublabel{NW4ZsHyK-nRuDO-5}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-5}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{NW4ZsHyK-nRuDO-4}{NW4ZsHyK-nRuDO-6}\nwenddeflinemarkup
-- Overwrite x with A_T * x
function xform_applyA(T, x)
  local y1 = T[1]*x[1] + T[4]*x[2] + T[7]*x[3];
  local y2 = T[2]*x[1] + T[5]*x[2] + T[8]*x[3];
  local y3 = T[3]*x[1] + T[6]*x[2] + T[9]*x[3];
  x[1] = y1;
  x[2] = y2;
  x[3] = y3;
  return x;
end

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{14}\nwdocspar

Recall that
\[
  T(S(x)) = A_T (A_S x + b_S) + b_T = (A_T A_S) x + T(b_T)
\]

\nwenddocs{}\nwbegincode{15}\sublabel{NW4ZsHyK-nRuDO-6}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-6}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{NW4ZsHyK-nRuDO-5}{NW4ZsHyK-nRuDO-7}\nwenddeflinemarkup
-- Return TS
function xform_compose(T, S)
  local TS = \{\};
  for k = 1,4 do
    local base = 3*k-3;
    TS[base+1] = T[1]*S[base+1] + T[4]*S[base+2] + T[7]*S[base+3];
    TS[base+2] = T[2]*S[base+1] + T[5]*S[base+2] + T[8]*S[base+3];
    TS[base+3] = T[3]*S[base+1] + T[6]*S[base+2] + T[9]*S[base+3];
  end
  TS[10] = TS[10] + T[10];
  TS[11] = TS[11] + T[11];
  TS[12] = TS[12] + T[12];
  return TS;
end

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{16}\nwdocspar

\nwenddocs{}\nwbegincode{17}\sublabel{NW4ZsHyK-nRuDO-7}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-7}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{NW4ZsHyK-nRuDO-6}{NW4ZsHyK-nRuDO-8}\nwenddeflinemarkup
-- Return the identity
function xform_identity()
  return \{ 1, 0, 0,
           0, 1, 0,
           0, 0, 1,
           0, 0, 0 \};
end

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{18}\nwdocspar

Getting right hand rotations correct is always a trick.
Important note -- remember that the transformation matrix is
interpreted as column-major, but is ``typographically'' row
major.  So put on your transposing hat before reading the
following three functions.

\nwenddocs{}\nwbegincode{19}\sublabel{NW4ZsHyK-nRuDO-8}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-8}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{NW4ZsHyK-nRuDO-7}{NW4ZsHyK-nRuDO-9}\nwenddeflinemarkup
-- Return a rotation about the x axis
function xform_ox(r)
  local c = cos(r)
  local s = sin(r)
  return \{ 1,   0,  0,
           0,   c,  s,
           0,  -s,  c,
           0,   0,  0 \}
end

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{20}\nwdocspar

\nwenddocs{}\nwbegincode{21}\sublabel{NW4ZsHyK-nRuDO-9}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-9}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{NW4ZsHyK-nRuDO-8}{NW4ZsHyK-nRuDO-A}\nwenddeflinemarkup
-- Return a rotation about the y axis
function xform_oy(r)
  local c = cos(r)
  local s = sin(r)
  return \{ c,   0, -s,
           0,   1,  0,
           s,   0,  c,
           0,   0,  0 \}
end

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{22}\nwdocspar

\nwenddocs{}\nwbegincode{23}\sublabel{NW4ZsHyK-nRuDO-A}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-A}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{NW4ZsHyK-nRuDO-9}{NW4ZsHyK-nRuDO-B}\nwenddeflinemarkup
-- Return a rotation about the z axis
function xform_oz(r)
  local c = cos(r)
  local s = sin(r)
  return \{ c,   s,  0,
          -s,   c,  0,
           0,   0,  1,
           0,   0,  0 \}
end

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{24}\nwdocspar

\nwenddocs{}\nwbegincode{25}\sublabel{NW4ZsHyK-nRuDO-B}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-B}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{NW4ZsHyK-nRuDO-A}{NW4ZsHyK-nRuDO-C}\nwenddeflinemarkup
-- Return a translation
function xform_translate(z)
  return \{ 1,    0,    0,
           0,    1,    0,
           0,    0,    1,
           z[1], z[2], z[3] \}
end

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{26}\nwdocspar

\subsection{{\Tt{}node\nwendquote} and {\Tt{}subnetize\nwendquote} functions}

We assume that node positions are expressed in the current coordinate
system (at least, that's what we assume for most purposes).
So the {\Tt{}nodex\nwendquote} (``node transformed'') function transforms
the input coordinates from local to global, and them makes a node.

We still want to leave the option of expressing node coordinates
directly in the global coordinate system, though.  For instance,
we may want to put a node halfway between two other nodes which
have already been transformed into global coordinates.  For this
reason, we leave the {\Tt{}node\nwendquote} function alone.

\nwenddocs{}\nwbegincode{27}\sublabel{NW4ZsHyK-nRuDO-C}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-C}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW4ZsHyK-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-4TVv9z-1}}\nwprevnextdefs{NW4ZsHyK-nRuDO-B}{\relax}\nwenddeflinemarkup
function nodex(p)
  if p[1] then
    top_xform(p)
  end
  return node(p)
end

\nwused{\\{NW4ZsHyK-4TVv9z-1}}\nwendcode{}\nwbegindocs{28}\nwdocspar

\subsection{Test code}

\nwenddocs{}\nwbegincode{29}\sublabel{NW4ZsHyK-pcrvx-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-pcrvx-1}}}\moddef{xformtst.lua~{\nwtagstyle{}\subpageref{NW4ZsHyK-pcrvx-1}}}\endmoddef\nwstartdeflinemarkup\nwenddeflinemarkup
use("xformstack.lua")

\LA{}test transform constructors~{\nwtagstyle{}\subpageref{NW4ZsHyK-1zasbh-1}}\RA{}
\LA{}test composition~{\nwtagstyle{}\subpageref{NW4ZsHyK-2X3VkV-1}}\RA{}
\nwnotused{xformtst.lua}\nwendcode{}\nwbegindocs{30}\nwdocspar

\nwenddocs{}\nwbegincode{31}\sublabel{NW4ZsHyK-1zasbh-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-1zasbh-1}}}\moddef{test transform constructors~{\nwtagstyle{}\subpageref{NW4ZsHyK-1zasbh-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-pcrvx-1}}\nwenddeflinemarkup
-- First check out the basics

rx45 = xform_ox(45)
ry45 = xform_oy(45)
rz45 = xform_oz(45)
trans = xform_translate \{1, 2, 3\}

x1 = xform_apply(rx45,  \{1, 0, 0\})
x2 = xform_apply(ry45,  \{1, 0, 0\})
x3 = xform_apply(rz45,  \{1, 0, 0\})
x4 = xform_apply(trans, \{1, 0, 0\})
x5 = xform_applyA(trans, \{1, 0, 0\})

print("Rotate e1 by rx45: ",     x1[1], x1[2], x1[3])
print("Rotate e1 by ry45: ",     x2[1], x2[2], x2[3])
print("Rotate e1 by rz45: ",     x3[1], x3[2], x3[3])
print("Translate e1 by 1,2,3: ", x4[1], x4[2], x4[3])
print("Apply A e1 by 1,2,3: ",   x5[1], x5[2], x5[3])

\nwused{\\{NW4ZsHyK-pcrvx-1}}\nwendcode{}\nwbegindocs{32}\nwdocspar

\nwenddocs{}\nwbegincode{33}\sublabel{NW4ZsHyK-2X3VkV-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW4ZsHyK-2X3VkV-1}}}\moddef{test composition~{\nwtagstyle{}\subpageref{NW4ZsHyK-2X3VkV-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW4ZsHyK-pcrvx-1}}\nwenddeflinemarkup
-- Now check out composition

T = xform_compose(trans, rz45)
x = xform_apply(T, \{1, 0, 0\})

print("Rotate then translate: ", x[1], x[2], x[3])

undoT = xform_compose(xform_oz(-45), xform_translate\{-1,-2,-3\})
xform_apply(undoT, x)

print("After undo operation: ", x[1], x[2], x[3])

\nwused{\\{NW4ZsHyK-pcrvx-1}}\nwendcode{}

\nwixlogsorted{c}{{data}{NW4ZsHyK-3zsvuH-1}{\nwixu{NW4ZsHyK-4TVv9z-1}\nwixd{NW4ZsHyK-3zsvuH-1}}}%
\nwixlogsorted{c}{{functions}{NW4ZsHyK-nRuDO-1}{\nwixu{NW4ZsHyK-4TVv9z-1}\nwixd{NW4ZsHyK-nRuDO-1}\nwixd{NW4ZsHyK-nRuDO-2}\nwixd{NW4ZsHyK-nRuDO-3}\nwixd{NW4ZsHyK-nRuDO-4}\nwixd{NW4ZsHyK-nRuDO-5}\nwixd{NW4ZsHyK-nRuDO-6}\nwixd{NW4ZsHyK-nRuDO-7}\nwixd{NW4ZsHyK-nRuDO-8}\nwixd{NW4ZsHyK-nRuDO-9}\nwixd{NW4ZsHyK-nRuDO-A}\nwixd{NW4ZsHyK-nRuDO-B}\nwixd{NW4ZsHyK-nRuDO-C}}}%
\nwixlogsorted{c}{{test composition}{NW4ZsHyK-2X3VkV-1}{\nwixu{NW4ZsHyK-pcrvx-1}\nwixd{NW4ZsHyK-2X3VkV-1}}}%
\nwixlogsorted{c}{{test transform constructors}{NW4ZsHyK-1zasbh-1}{\nwixu{NW4ZsHyK-pcrvx-1}\nwixd{NW4ZsHyK-1zasbh-1}}}%
\nwixlogsorted{c}{{xformstack.lua}{NW4ZsHyK-4TVv9z-1}{\nwixd{NW4ZsHyK-4TVv9z-1}}}%
\nwixlogsorted{c}{{xformtst.lua}{NW4ZsHyK-pcrvx-1}{\nwixd{NW4ZsHyK-pcrvx-1}}}%
\nwbegindocs{34}\nwdocspar

\nwenddocs{}


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

\begin{XtoCtabular}{Inports}
In & Integer input\tabularnewline
\hline
\end{XtoCtabular}

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

\begin{XtoCtabular}{Mask Parameters}
Scale & Scaling factor from integer to real\tabularnewline
\hline
\end{XtoCtabular}

\subsubsection*{Description:}
Conversion block from integer (fixed point) datatypes to real (floating point) datatypes.

  Out = In * Scale

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

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

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

8 Bit Fixed Point to 32 Bit Floating Point Implementation

\begin{XtoCtabular}{Controller Parameters}
scale & Scaling factor\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int8          *In;
     float32       Out;
     float32       scale;
} INT2REAL_FIP8_FLOAT32;
\end{lstlisting}

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

16 Bit Fixed Point to 32 Bit Floating Point Implementation

\begin{XtoCtabular}{Controller Parameters}
scale & Scaling factor\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int16         *In;
     float32       Out;
     float32       scale;
} INT2REAL_FIP16_FLOAT32;
\end{lstlisting}

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

32 Bit Fixed Point to 32 Bit Floating Point Implementation

\begin{XtoCtabular}{Controller Parameters}
scale & Scaling factor\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int32         *In;
     float32       Out;
     float32       scale;
} INT2REAL_FIP32_FLOAT32;
\end{lstlisting}

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

8 Bit Fixed Point to 64 Bit Floating Point Implementation

\begin{XtoCtabular}{Controller Parameters}
scale & Scaling factor\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int8          *In;
     float64       Out;
     float64       scale;
} INT2REAL_FIP8_FLOAT64;
\end{lstlisting}

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

16 Bit Fixed Point to 64 Bit Floating Point Implementation

\begin{XtoCtabular}{Controller Parameters}
scale & Scaling factor\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int16         *In;
     float64       Out;
     float64       scale;
} INT2REAL_FIP16_FLOAT64;
\end{lstlisting}

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

32 Bit Fixed Point to 64 Bit Floating Point Implementation

\begin{XtoCtabular}{Controller Parameters}
scale & Scaling factor\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int32         *In;
     float64       Out;
     float64       scale;
} INT2REAL_FIP32_FLOAT64;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/General/Doc/Test_Int2Real_FiP32_Float64.tex}{}{}
\fi


\section*{Welcome to SnuggleTeX!}

\begin{itemize}
  \item This is an itemized list.

  \item This is some inline maths: $x^2+ y^2 = 1$

  \item Some block maths:
        \[ \sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6} \]
        (\textbf{Note}: This currently doesn't display nicely in Firefox 3. Boo\ldots)

  \item A $2\times 2$ matrix created via a user-defined command:
        \newcommand{\mat}[4]{\left( \begin{array}{cc} #1 & #2 \\ #3 & #4 \end{array} \right)}
        \[ A = \mat{\alpha}{\beta}{\gamma}{\delta} \]

\end{itemize}

Here is an example of a SnuggleTeX error message. You can set it up to display the messages inline (as we have here) or report them in various other ways:

\doh


% declare document class and geometry
\documentclass[12pt]{article} % use larger type; default would be 10pt
\usepackage[margin=1in]{geometry} % handle page geometry

% import packages and commands
\input{../header2.tex}

\newcommand{\Gr}{\opname{Gr}}

\title{Math 217 -- Geometry and Physics -- Lec10}
\author{UCLA, Fall 2014}
\date{\formatdate{24}{10}{2014}} % Activate to display a given date or no date (if empty),
         % otherwise the current date is printed

\begin{document}
\maketitle

\section{Universal vector bundles}

Let's start with complex vector bundles. Recall the grassmannian
\begin{eqn}
\opname{Gr}(n,N) = \set{V \subseteq \complexes^N | \dim V = n},
\end{eqn}
which has the property
\begin{eqn}
\begin{matrix}
\opname{Gr}(n,N) & \subseteq & \opname{Gr} (n,N+!) & \subseteq \dots \\
(z_1, \dots, z_N) & \mapsto & (z_1, \dots, z_N, 0) &
\end{matrix}
\end{eqn}
The ``infinite'' Grassmannian is denoted
\begin{eqn}
BU(n) = \opname{Gr}(n, \infty)
\end{eqn}
and has a universal subbundle $S \rightarrow \Gr(n,\infty) = BU(n)$. Furthermore, we find that
\begin{align}
\opname{Vect}_n(M) &= \set{ \text{complex vector bundles on $M$} } \\
	& \cong [M, BU(n)] = \set{ \text{homotopy classes of $f: M \rightarrow BU(n)$} }.
\end{align}
Then we have
\begin{eqn}
H^*(BU(n), \ints) \cong \ints[c_1, \dots, c_n], \quad \text{where} \quad c_i = c_i(S).
\end{eqn}
We also have
\begin{eqn}
c_i(E) = f^* c_i (S) = f^* c_i.
\end{eqn}

For grassmannians on real vector bundles, we have the infinite grassmannian
\begin{eqn}
BO(n) = \Gr_\reals (n, \infty).
\end{eqn}
Then
\begin{align}
\opname{Vect}_n (M) &\cong [M, BO(n)] \\
H^* (BO(n), \irrats) &= \irrats[p_1, \dots, p_{\lceil n/2 \rceil}] \\
H^*(BO(n), \ints_2) &= \ints[w_1, \dots, w_n]
\end{align}
where $P_j (E) = f^* p_j(S)$, $w_j(E) = f^* w_j(S)$, and $w_j = w_j(S)$ (Universal Stiefle-Whitney [?])

[$O(n) \rightarrow U(n)$, $BO(n) \rightarrow BU(n)$, $H^*(BU(n), \ints) \rightarrow H^*(BO(n),\ints)$, $p_j = (-1)^j c_{2j}$]

\subsection{Axioms of SW [Stiefle-Whitney?] classes}
Given real vector bundle $E$ over closed $M$, there exist $\set{w_i(E)}$ in $H^*(M, \ints_2)$ ($w_i \in H^i(M, \ints_2)$) such that
\begin{enumerate}
\item $w_0 = 1$,
\item $w_i (f^*E') = f^* w_i (E)$,
\item $w(E \oplus E') = w(E) w(E')$,
\item $\gamma_1$ (Universal [subdim?] bundle) $\rightarrow \RP^1$, where $w_1(\gamma_1)$ the generator of $H^1(\RP^1, \ints_2)$.
\end{enumerate}

\subsubsection{stuff}

[missed some stuff here]

so we have
\begin{eqn}
c_j = \sigma_j(x_1, \dots, x_n)
\end{eqn}

\subsubsection{stuff}

[missed bit more here]

\subsection{Axioms for Chern classes}

Given complex vector bundle $E^n \rightarrow M$,
\begin{enumerate}
\item $c_0(E) = 1$, $c_j(E) = 0$ for $j > n$.
\item $f^* c_j(E') = c_j (f^* E')$,
\item $c(E \oplus E') = c(E) c(E')$,
\item $\bigO(-1) = L \rightarrow \CP^\infty$ and $c_1(L) = x$ is generator of $H^*(\CP^\infty, \ints)$.
\end{enumerate}

We can write
\begin{eqn}
i \partial \bar\partial \log(1 + \abs{z}^2) = c_1 (\bigO(-1)),
\end{eqn}
where $\bigO(-1) \rightarrow \CP^1$ (exercise). We find that
\begin{eqn}
\int_{\CP^1} c_1 \bigO(-1) = \int_{z \in \complexes} i \partial \bar\partial \log(1 + \abs{z}^2) = \pm 1.
\end{eqn}
We have $\pi^* c_j(E) = \sigma_j (x_1, \dots, x_n)$, where $x_j = c_1(L_j)$, where
\begin{eqn}
\pi^* : H^*(M) \hookrightarrow H^*(F(E)).
\end{eqn}
So we have
\begin{eqn}
\CP^{n-1} \hookrightarrow P(E) \overset{\pi}{\rightarrow} M
\end{eqn}
Let $t = -c_1(L)$, and note that
\begin{eqn}
\pi^* E \cong \underbrace{L}_{\bigO(-1)} \oplus \underbrace{Q}_\text{quotient bundle}.
\end{eqn}
Writing out our expansion
\begin{eqn}
c_t = \det (tI + \frac{i}{2\pi} \Omega) = t^n + c_1 t^{n-1} + \dots + c_n,
\end{eqn}
since we have
\begin{eqn}
c_t(\pi^* E) = \underbrace{c_t(L)}_{=0} c_t(Q),
\end{eqn}
so that
\begin{eqn}
0 = t^n + \pi^* c_1(E) t^{n-1} + \dots + \pi^* c_n(E).
\end{eqn}
So we've found \textit{Grothendieck's characterization of Chern classes},
\begin{eqn}
H^*(P(E), \irrats) = H^*(M) [x_E] \Big/ \set{x_E^n + \pi^* c_1(E) x_E^{n-1} + \dots + \pi^* c_n(E) = 0}.
\end{eqn}

The most useful characteristic classes is probably Hirzebruch's:

1. $L$-classes, $TM \rightarrow M^{2n}$. We have
\begin{eqn}
L(TM) = \prod_{j=1}^n \frac{x_j}{\tanh x_j} = \text{a symmetric function in $\set{x_j^2}$}
\end{eqn}
As an exercise, for $n=2$, can show
\begin{eqn}
L(TM)^\text{top} = \frac{x_1}{\tanh x_1} \frac{x_2}{\tanh x_2} = \frac{1}{3} P_1 (TM).
\end{eqn}
Then $\hat{A} (TM^4) = -\frac{1}{24} P_1 (TM)$

2. The $\hat{A}$-classes are given by
\begin{eqn}
\hat{A} (TM) = \prod_{j=1}^n \frac{x_j / 2}{\sinh (x_j/2} = f(p_1, \dots, p_n)
\end{eqn}

\end{document}


%&LaTeX

\section{The Matlab Lab, or How to Not Teach a Programming Language}

Labs in this class will make liberal use of the Matlab numerical
programming environment. Because this class assumes that you are an
experienced computer science student, you are expected to be able to
learn how to use computer tools, and how to program in new programming
languages, pretty much on your own. So, the first thing you should do
is check out the Matlab documentation built into the Matlab help
system, or online at
\url{http://www.mathworks.com/help/matlab/index.html}. Of course, you
can always search online for Matlab tutorials and the like. We'll
include a very brief overview of Matlab below, and then more detailed
information about the code developed specifically for this class that
you will be using.

\subsection{Matlab in a (Very Small) Nutshell}
\label{sc:basic-matlab}

The Matlab GUI environment is very similar to IDEs that you are
already familiar with. As you might expect, there are some
idiosyncrasies here and there, but nothing terribly unexpected. The
major areas of difference are tools and panes that have to do with
viewing variables (something in other IDEs that you'd only see when
debugging a program), the command pane, and figure windows that open
to display graphs. The first two of these differences have to do with
the fact that Matlab is an interpreted language/programming
environment. You primary area of interaction with the Matlab
interpreter will be through the command window, with variable
information panes providing views of variables and their contents
related to your interaction. It's interesting to note that, if you
want, you can run Matlab without the GUI, providing just a command
line interface.

Interpreted languages have their advantages and disadvantages.  One
advantage is that anything you can use as a line of code in a program
you can use immediately as a command on the command line. This lets
you test code interactively and then copy it into the script or
function you're writing. Like any IDE, Matlab includes an editor with
syntax highlighting and debugger integration.

The disadvantage is the interpreted programs are slower. In Matlab, we
get around this by using built-in functions that operate on entire
vectors or arrays as single data objects. The core loops of the
built-in functions are compiled for speed. If you make good use of
those functions, Matlab code can often be as fast as completely
compiled code.

Here are some things to try:
\begin{enumerate}
\item Immediate calculations and variables:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
radius = 5    % Comments start with "%"
circumference = 2 * pi * radius
area = pi * radius^2
\end{lstlisting}
\item Complex numbers:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
sqrt(-1)
x = 7 + 14j
conj(x)       % complex conjugate
abs(x)        % magnitude (e.g., for polar representation)
angle(x)      % and angle for polar rep
real(x)
imag(x)
\end{lstlisting}

\item Complex exponentials:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
exp(j * pi)
exp(j * pi/2)
exp(j * pi/4)
\end{lstlisting}

\item Vectors:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
v1 = [0 1 2 3]    % Four elements
v2 = [0 : 2 : 10] % like a loop (start value : increment : end value)
v3 = pi * [-0.5 -0.25 0 0.25 0.5] % All operations are vectorized
exp(j * v3)
mistake = v1 * v1     % a mistake; vector mult doesn't work this way
dotproduct = v1 * v1' % transposing will work, if you want to do this
arrayprod = v1 .* v1  % element-by-element ops include: .+, .-, .*, ./
\end{lstlisting}

\item Simple plots (note that ``;'' suppresses outputting results to
  the command window --- useful if that would generate massive amounts
  of text, or just if you want things neat):
\label{it:simple-plots}
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
t = [0 : 0.01 : 2*pi];
x = sin(t);
plot(t, x);       % default plots points connected by lines in blue
plot(t, x, 'r');  % change the line color
plot(t, x, 'r.'); % change the plot style; zoom in to see individual points
xlabel('t, ms');  % X axis label (all of your plots should have this)
ylabel('Mag');    % Y axis label (all of your plots should have this)
title('Triangle');% Graph title (all of your plots should have this)
\end{lstlisting}

\end{enumerate}

If you take a sequence of commands and save them in a file with an
extension of \texttt{.m}, the result is a \emph{script}. Assuming that the
script is saved in a directory in the MATLAB search path, you can then
execute the script by just typing its name (without the \texttt{.m}),
just as if it were a command. If you want your code to take
parameters, return a return value, and have local variables, start
your code with a line like:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
function retval = funcname(parm1, parm2)
\end{lstlisting}

Your code is now a function. MATLAB functions can take variable
numbers of arguments and even return variable numbers of return
values, but that's getting beyond what we need right now.

\paragraph{Step 1.1} It's easy to create, concatenate, extract, and modify
vectors or parts of vectors. Execute the following lines of Matlab
code and explain what each echoes out:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
a = ones(1,3)
b = zeros(1,5)
x = [b, a, [1:2:12]]
x(7:end)
length(x)
x(1:2:12)
\end{lstlisting}

Also, explain the difference between the square bracket notation
\verb|[1:2:12]| and the parenthetical notation \verb|(1:2:12)|.

\paragraph{Step 1.2} Consider the result of the following assignment:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
x(7:11) = pi*(1:5)
\end{lstlisting}

Write a \emph{single} statement that will replace the odd-indexed
elements of \texttt{x} with the constant -10 (i.e., \texttt{x(1)},
\texttt{x(3)}, etc).

\paragraph{Step 1.3} One of the side benefits of learning Matlab is
that it trains you to think in terms of parallel operations --- an
increasingly important skill in a profession becoming dominated by
multi-core, GPU, and distributed computing. That doesn't mean you
can't write loops in Matlab; it's just that your code will be more
concise and efficient if you can avoid that. The efficiency arises
from the fact that the vectorized Matlab commands are mostly compiled;
while the loops you write are interpreted. Consider the following loop:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
for k=0:7,
   x(k+1) = cos(k*pi/4);
end
x
\end{lstlisting}

Why is \verb|x| indexed by \verb|k+1| rather than \verb|k|? What
happens to the length of \verb|x| for each iteration of the loop?
Rewrite this computation without using the loop (as in list
item~\ref{it:simple-plots}). Besides the increase in efficiency from
avoiding an interpreted loop, what other major efficiency results from
this change?

\paragraph{Step 1.4} Consider the following code that plots a
sinusoid:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
t = [0 : 0.01 : 1]; % time in seconds
f = 5;              % freq in Hertz
x = sin(2*pi*f*t);
plot(t, x);
xlabel('Time (sec)');
\end{lstlisting}

Use the MATLAB editor to create a script file called
\texttt{firstsin.m}, verify that you've saved it in a directory in the
MATLAB path (or add that directory to the path), and test its
execution by typing \texttt{firstsin} at the MATLAB command
prompt. Note that you can also do:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
type firstsin   % prints out contents of the script
which firstsin  % shows directory (useful when your code shadows built-ins)
\end{lstlisting}

If you included documentation for this script (comments at the
beginning), the command \verb|help firstsin| would also produce useful
output.

Add three lines of code to your script, so that it will plot a cosine
using the same axes as the sine (i.e., ``on top of the sine''). Use
the \texttt{hold} function to add a plot of
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
0.75*cos(2*pi*f*t)
\end{lstlisting}
to the plot. So, your final graph will have two functions
plotted. Save the plot using the MATLAB \texttt{print} command as a
PNG file named \texttt{step14.png} by typing:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
print -dpng step14
\end{lstlisting}

You should include all plots and code snippets in your lab report,
following the instructions in the report rubric.

\paragraph{Step 1.5} You can also use Matlab to generate sounds. A
pure tone is merely a sinusoid, which you already know how to
generate. Let's generate one with a frequency of 3 kHz and a duration
of 1 second:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
T = 1.0;
f = 3000;
fs = 8000;
t = [0 : (1/fs) : T];
x = sin(2*pi*f*t);
soundsc(x, fs)
\end{lstlisting}

The vector of numbers \texttt{x} are converted into a sound waveform
at a certain rate, \verb|fs|, called the \emph{sampling rate} (we will
learn a lot more about this in this class). In this case, the sampling
rate was set to 8000 samples/second. What is the length of
the vector \texttt{x}?

\paragraph{Step 1.6} Write a new function that performs the same task
as the following function without using any loops. Use the idea in
step~1.3 and also consult the section on the \verb|find| function,
relational operators, and vector logicals in the MATLAB documentation.
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
function B = denegify(A)
% DENEGIFY Replace negative elements of matrix with zeros
% Usage:
%    B = denegify(A)
%
[W,H] = size(A);
for i=1:W
   for j=1:H
      if A(i,j) < 0
         B(i,j) = 0;
      else
         B(i,j) = A(i,j);
      end
   end
end
\end{lstlisting}

\subsection{Trigonometric Functions and Complex Mathematics in Matlab}

\paragraph{Step 2.1} In this step, you are asked to complete a Matlab
function to synthesize a waveform in the form of:
\begin{equation*}
x(t) = \sum_{k=1}^N a_k\cos(2\pi f t + \phi_k)
\end{equation*}
This is a sum of cosines, all at the same frequency but with different
phases and amplitudes.  Use the following function prototype to start you off:
\begin{lstlisting}[style=Matlab-editor,basicstyle=\mlttfamily\small]
   function x = sumcos(f, phi, a, fs, dur)
   % SUMCOS Synthesize a sum of cosine waves
   % Usage:
   %    x = sumcos(f, phi, a, fs, dur)
   %        Returns sum of cosines at a single frequency f, sampling
   %        rate fs, and duration dur, each with a phase phi and
   %        amplitude a.
   %    f = frequency (scalar)
   %    phi = vector of phases
   %    a = vector of amplitudes
   %    fs = the sampling rate in Hz (scalar)
   %    dur = total time duration of signal (scalar)
\end{lstlisting}

Include your code in your writeup. Additionally, include a plot of
\texttt{x = sumcos(20, [0 pi/4 pi/2 3*pi/2], [1 2 3 4], 200, 0.25);} versus
time.

Hint: the MATLAB \verb|length| function is useful in determining the
number of elements in a vector; the \verb|size| function returns both
dimensions of a vector or an array.

\paragraph{Step 2.2} Now, let's see how complex exponentials can
simplify things. Re-implement your \texttt{sumcos} function using
complex exponentials. Take advantage of the fact that multiplying a
complex sinusoid $e^{j2\pi f t}$ by the complex amplitude
$a_ie^{j\phi}$ will shift its phase and change its amplitude. Thus,
you should be able to create a \emph{single} complex sinusoid at the
given frequency \texttt{f} and then multiply it by different \texttt{a
  * exp(j * phi)} to get multiple phase shifted cosines. Remember that
we want a real value to plot; the cosine is the real part of a complex
sinusoid. Include your code in your writeup and provide a plot that
demonstrates that this function produces the same result as the
original implementation.

\paragraph{Step 2.3} Generate four sinusoids with the following
amplitudes and phases:
\begin{align}
x_1(t) &= 6 \cos(2\pi(10)t - 0.5\pi) \\
x_2(t) &= 3 \cos(2\pi(10)t + 0.25\pi) \\
x_3(t) &= 2 \cos(2\pi(10)t - 0.3\pi) \\
x_4(t) &= 8 \cos(2\pi(10)t + 0.9\pi)
\end{align}

\begin{enumerate}\renewcommand{\theenumi}{\alph{enumi}}
\item Make a single plot of all four signals together over a range of
  $t$ that will generate approximately 3 cycles. Make sure the plot
  includes negative time so that the phase at $t = 0$ can be
  measured. In order to get a smooth plot make sure that your have at
  least 20 samples per period of the wave. Include your plot in your
  writeup.

\item Verify that the phase of all four signals is correct at $t = 0$,
  and also verify that each one has the correct maximum amplitude. Use
  \verb|subplot(3,2,i)| to make a six-panel subplot that puts all of
  these plots in the same figure, with space for two additional plots
  at the bottom. Use the \verb|xlabel|, \verb|ylabel|, and
  \verb|title| functions so that the reader can figure out what the
  plots mean; reinforce this with your report's figure caption. (You
  should include the final figure, with all subplots, that results
  from finishing all of the parts of this step.)

\item Create the sum sinusoid,
  $x_5(t)=x_1(t)+x_2(t)+x_3(t)+x_4(t)$. Plot $x_5(t)$ over the same
  range of time as used in the last plot. Include this as the lower
  left panel in the plot by using \verb|subplot(3,2,5)|.

\item Now do some complex arithmetic; create the complex amplitudes
  corresponding to the sinusoids $x_i(t)$: $z_i = A_ie^{j\phi_i}$,
  $i=1,2,3,4,5$. Include a table in your report of the $z_i$ in polar
  and rectangular form, showing $A_i$, $\phi_i$, $\Real\{z_i\}$, and
  $\Imag\{z_i\}$.
\end{enumerate}

\subsection{Representing Analog, Discrete, and Digital Signals}

In our class, we will need to manipulate analog signals (real-valued
signals that are functions of continuous time), discrete signals
(real-valued signals that are functions of discrete time), and digital
signals (discrete-valued signals that are functions of discrete
time). No need to worry about the details or these; that will become
clear later. The trickiest part of this is representing anything other
than digital signals on a digital computer, because you can't. So,
we'll need to employ two key elements of software design: information
hiding and make-believe.

\begin{figure}
\begin{center}
\includegraphics[width=0.75\textwidth]{lab1/AnalogSignal-help}
\end{center}
\caption{Example help screen for the \texttt{AnalogSignal}
  class. This example may be out-of-date; use the Matlab
  \texttt{doc AnalogSignal} command to get current
  documentation.\label{fg:analogsignal-help}}
\end{figure}

Information hiding is used in our implementation of analog signals. We
make use of the object-oriented programming aspects of Matlab to
create an \texttt{AnalogSignal} class. If you look up the
documentation for \texttt{AnalogSignal} (using
\verb|doc AnalogSignal|), you'll see something like
figure~\ref{fg:analogsignal-help}. The key operations on these analog
signals are:
\begin{itemize}
\item Creating an analog signal (ex: \texttt{a =
    AnalogSignal('sawtooth', 2.0, 1.0, 10.0)}).
\item Scaling an analog signal (ex: \texttt{b = a * 5})
\item Adding two analog signals (ex: \texttt{c = a + b})
\item Subtracting two analog signals (ex: \texttt{d = c - a})
\item Plotting an analog signal (ex: \texttt{plot(d)})
\item Sampling an analog signal (ex: \texttt{x = d.samplehold(0.1)})
\end{itemize}

You will get a lot more experience working with analog signals shortly
in this class, so for the time being just play with this a bit.


Role of BNN. List the parameters predicted $\xi_{lens}$ and which of the $\xi_{light}$ (source position, lens effective radius). Input, output. Build up to hierarchical inference. Focus on consistency between \cite{hezaveh2017fast} and \cite{wagnercarena2019double}.

\subsection{Training set generation}
Cite baobab paper in prep and link the GH. Say that we experimented with two different conditional PDFs, from which we sampled the macromodel parameters. One was where each parameter was sampled independently. Have a table like the TDLMC table? See \ref{table:conditional_pdf}. Another was where the parameters followed empirical distributions.

Training set is samples from the interim prior...

\begin{table}
\label{table:conditional_pdf}
\centering
\caption{Parameter distribution}\label{para_config}
\begin{tabular}{ l l}
\hline
Simulating ingredient & model and parameter values \\
\hline\hline
A): redshift \\\hline
deflector redshift & $z_d \in {\rm Norm} (0.5\pm0.2)$ \\
source redshift & $z_s \in {\rm Norm} (2.0\pm0.4)$ \\
 \hline\hline
% Rung1 and Rung2\\ \hline
\\B): deflector (image plane) \\
\hline
lensing galaxy mass & elliptical power-law \\
\hline
SIS velocity dispersion & $v_d\in {\rm Norm} (250\pm25)$ km/s \\
Einstein radius$^a$ &$R_{\rm Ein} = 4\pi v_d^2 \frac{D_{ds}}{D_{s}}$ \\
mass slope & $s \in {\rm Norm} (2.0\pm 0.1)$ \\
ellipticity & $q \in {\rm Uni} (0.7 \sim 1.0)$ \\
elliptical axis angle & $\phi \in {\rm Uni} (0 \sim \pi) $ \\
\hline
lensing galaxy SB & \sersic\ profile \\
\hline
total magnitude$^{b}$ & $ mag \in {\rm Uni} (17.0 \sim 19.0) $ magnitude \\
effective radius & $R_{\rm eff} = R_{\rm Ein} * {\rm Uni} (0.5 \sim 1.0) $ \\
\sersic\ index & $n \in {\rm Uni} (2.0 \sim 4.0) $\\
ellipticity & $q \in {\rm Uni} (0.7 \sim 1.0)$ \\
elliptical axis angle & $\phi \in {\rm Uni} (0 \sim \pi) $ \\
\hline \hline

\\C): AGN (source plane) \\
\hline
host galaxy SB & realistic galaxy\\
\hline
total magnitude & $ mag \in {\rm Uni} (22.5 \sim 20.0) $ magnitude \\
effective radius$^c$ & $R_{\rm eff} \in {\rm Uni} (0\farcs{}37, 0\farcs{}45), $ {\scriptsize $1.0<z_s<1.5$ \par} \\
&$R_{\rm eff} \in {\rm Uni} (0\farcs{}34, 0\farcs{}42), $  {\scriptsize $1.5<z_s<2.0$  \par} \\
&$R_{\rm eff} \in {\rm Uni} (0\farcs{}31, 0\farcs{}35), $  {\scriptsize $2.0<z_s<2.5$  \par} \\
&$R_{\rm eff} \in {\rm Uni} (0\farcs{}23, 0\farcs{}33), $  {\scriptsize $2.5<z_s<3.0$  \par} \\
\hline
active nuclear light & scaled point source \\
\hline
source plane total flux & $f_{\rm AGN} = f_{\rm host} * {\rm Uni} (0.8 \sim 1.25) $ \\
 \\\hline \hline
external shear \\
\hline
amplitudes & $ \gamma\ \in {\rm Uni} (0 \sim 0.05) $ \\
shear axis angle & $\phi \in {\rm Uni} (0 \sim \pi) $ \\
\hline
external convergency \\
\hline
external kappa$^d$ & $ \kappa_{\rm ext} \in {\rm Norm} (0 \pm 0.025) $ \\
\hline
\hline
\end{tabular}
  \begin{tablenotes}
 	 \footnotesize
 	 \item Notes:- In Rung3, the non-parameterized deflector (i.e., lensing galaxy mass and surface brightness) are adopted. Thus, the B part in the table is not adoptable for this rung. The distribution of ``Norm" means normal distribution and the ``Uni" means uniform distribution.
	 \item ~~~~a: The scale of Einstein Radius by is in range [1$\farcs$00, 1$\farcs$20].
	 \item ~~~~b: The flux value and the magnitude value are related by the equation: \\ $mag= -2.5 * log10(flux) + zp$, where $zp$ is the filter zeropoint in AB system. For filter WFC3/F160W, $zp = 25.9463$.
	 \item ~~~~c: The effective radius of the realistic galaxy is measured by the Galfit, by considering them as \sersic\ profile.
	 \item ~~~d: The value of $\kappa_{\rm ext}$ is randomly generated to calculate the time delay data. The information of this distribution is provided to the ``Good" teams as a measurement data.
  \end{tablenotes}
\end{table}

\subsection{BNN posterior}
What's the term to use for this? Cite \cite{wagnercarena2019double} and say the form was double Gaussian.

\subsection{Posterior on $H_0$}
Time delays, velocity dispersion are external data. Conditional PDF
Introduce training set are samples from the interim prior.

With importance sampling,
\begin{align}
    &p(\Omega | \Delta t_{AB}, \sigma_V, d_{HST}) \\
    &\propto p(\Omega) \prod_{k} \int p(\Delta t_{AB}^{(k)} | \Omega, \xi_{lens}^{(k)}, \kappa_{ext}^{(k)})  \nonumber \\
    & \quad \times p(\sigma_V^{(k)} | \Omega, \xi_{lens}^{(k)}, \xi_{light}^{(k)}, \kappa_{ext}^{(k)}, \beta_{ani}^{(k)})  \nonumber \\
    & \quad \times p(\xi_{lens}^{(k)}, \xi_{light}^{(k)} | d_{HST}^{(k)}, \Omega_i) \times \frac{p(\xi_{lens}^{(k)}, \xi_{light}^{(k)} | \Omega)}{ p(\xi_{lens}^{(k)}, \xi_{light}^{(k)} | \Omega_i)} \nonumber \\
    & \quad \times p(\kappa_{ext}^{(k)}) p(\beta_{ani}^{(k)})
    \quad d \left( \xi_{lens}^{(k)}, \xi_{light}^{(k)} \right) d \kappa_{ext}^{(k)} d \beta_{ani}^{(k)} \nonumber
\end{align}


\section{Conclusion}
\label{sec:conclusion}

In this paper, we studied the relationship between adversarial robustness, specifically considering robust overfitting \cite{RiceICML2020}, and flatness of the robust loss (\RCE) landscape \wrt perturbations in the weight space. We introduced both average- and worst-case measures for flatness in \RCE that are scale-invariant and allow comparison across models. Considering adversarial training (AT) and several popular variants, including TRADES \cite{ZhangICML2019}, AT-AWP \cite{WuNIPS2020} or AT with additional unlabeled examples \cite{CarmonNIPS2019}, we show a \textbf{clear relationship between adversarial robustness and flatness} in \RCE. More robust methods predominantly find flatter minima. Vice versa, approaches known to improve flatness, \eg, Entropy-SGD \cite{ChaudhariICLR2017} or weight clipping \cite{StutzMLSYS2021} can help AT become more robust, as well. Moreover, even simple regularization methods such as AutoAugment \cite{CubukARXIV2018}, weight decay or label noise, are effective in increasing robustness by improving flatness. These observations also generalize to pre-trained models from RobustBench \cite{CroceARXIV2020b}.


The chapter addresses the problem of optimally controlling an industrial micro-grid featuring a large share of renewable energy and a high volatility of electricity prices. We consider a micro-grid as a localized group of energy sources, loads and storage components that can operate in two distinct modes: grid-connected mode and isolated mode. In grid-connected mode, the micro-grid system has the possibility to buy/sell energy from/to the macro-grid in order to meet the load demand. The challenge in connected mode is to reduce the total energy cost. In isolated mode, the micro-grid can function autonomously in the sense that enough energy can be generated in the grid to supply the loads. In this case the challenge is to meet the load demand and to balance the power flow between the components of the grid. In our setting, the grid is executed in mixed mode. In other words, the industrial micro-grid, we are considering, can switch from one mode to another.

\subsection{System Model}
\label{subsec:31}

% For figures use
%
\begin{figure}[b]
%\sidecaption
% Use the relevant command for your figure-insertion program
% to insert the figure file.
% For example, with the graphicx style use
\includegraphics[scale=.65]{images/System_Model}
%
% If no graphics program available, insert a blank space i.e. use
%\picplace{5cm}{2cm} % Give the correct figure height and width in cm
%
\caption{System Overview. Every grid-component is controlled by a reinforcement learning agent.}
\label{fig:system_model}       % Give a unique label
\end{figure}

As illustrated in Fig.\ref{fig:system_model}, the micro-grid system consists of the following components: renewable energy sources such as photovoltaic systems, electricity loads representing production machines, regenerative energy consumers, energy storages systems such as batteries and auxiliary process loads for air compressors and cooling systems. The components share the same energy bus, enabling a transfer of electrical energy between the components. The proposed system model is equally applicable to ac and dc micro-grids and a simple formal description of the components can be described as follow:
\begin{itemize}
\item{\textit{\textbf{ Renewable energy sources}} are renewable energy generators such as photovoltaic systems or wind turbines. The power generated depends on environmental and weather factors such as solar radiation profile and wind speed. It is therefore not predictable. Energy generators are characterized by two operating states: $on$ and $off$. The generators are considered to be in the $off$-state when the electrical power generated by the energy sources is negligible for example because of weather conditions such as cloudy weather or nighttime. We assume that if the generators are not in $off$ state, then the power generated is constant and equal to the maximum electricity power that can be produced by the source. Therefore
%
\begin{equation}
 P_G =
 \begin{cases}
      0 & \text{if}\ state=off \\
      P_Gmax & \text{otherwise}
    \end{cases} \;
\end{equation}
%
 }
\item{\textit{\textbf{Energy storage systems}}. In order to take full advantage of renewable energy sources, it is vital to have energy storage systems capable of handling variations in energy production. In our environment, we consider batteries or super-capacitor systems that consume a constant energy when charging and produce a constant energy when discharging. In addition, the operation of energy storage systems has to be carefully designed and controlled to protect them from damages that are: overcharging and overdischarging. Therefore, each storage system is also characterized by a maximum and minimum state-of-charge (SoC). The energy storage systems have three required states: $charging$, $discharging$ and $idle$. The electrical power consumed or released by the component highly depends on the current operational state and the component\rq{s} state-of-charges.}

 \item{\textit{\textbf{Energy loads}} represent production machines that consume energy in order to execute a production task. A production machine can have different operation states: $powered off$, $executing$, $stand by$, etc… Depending on the production task and the operation state, a production machine can follow a predefined or a characteristic load profile. For a fixed set of production tasks, the load profile of a machine can be measured and approximated. In our setting, we consider 3 basic load profile as illustrated in Fig. \ref{fig:load_profile}. Any machine\rq{s} load profile can be seen as a linear combination of this basic load profiles. In isolated mode, the micro-grid cannot guarantee continuous power supply to the load because it is often influenced by the unpredictable power generation. When the generated power is not able to drive the loads, the noncritical loads must shut down.}

 % For figures use
%
\begin{figure}[h!]
%\sidecaption
% Use the relevant command for your figure-insertion program
% to insert the figure file.
% For example, with the graphicx style use
\includegraphics[scale=.40]{images/load_profile}
%
% If no graphics program available, insert a blank space i.e. use
%\picplace{5cm}{2cm} % Give the correct figure height and width in cm
%
\caption{Basic load profiles of the energy loads. In $execute$-state,  the electrical power consumed $P_i$ can be constant and equal to $P_{max}$ (a), increase linearly (b) or exponentially (c) to $P_{max}$.}
\label{fig:load_profile}       % Give a unique label
\end{figure}

\item{\textit{\textbf{Regenerative energy consumers}} are energy consumers with the exception that these consumers can recuperate energy for a small period of time (less than a minute). In this case we consider the load to be constant and negative. Fig. \ref{fig:recuperative_load_profile} shows a typical load profile.}

 % For figures use
%
\begin{figure}[h!]
\sidecaption
% Use the relevant command for your figure-insertion program
% to insert the figure file.
% For example, with the graphicx style use
\includegraphics[scale=.40]{images/Recuperative_Energy_Load_Profile}
%
% If no graphics program available, insert a blank space i.e. use
%\picplace{5cm}{2cm} % Give the correct figure height and width in cm
%
\caption{Basic load profiles of regenerative energy consumers. In $execute$-state,  the electrical power consumed $P_i$ can be negative for a short period of time.}
\label{fig:recuperative_load_profile}       % Give a unique label
\end{figure}

\item{\textit{\textbf{Auxiliary processes}} are energy consumer processes in the factory floor that do not execute a manufacturing task directly, but are required by the production task. These are for example compressors or cooling systems. Auxiliary processes have two required states: $off$ and $on$.}

\item{The \textit{\textbf{grid component}} represents the main grid and is responsible for buying/selling electricity from/to the main grid. It has three state: $buying$, $selling$, $idle$. If the grid agent is in $idle$-state or in $off$-state, the industrial micro-grid can be considered to be executed in isolated mode because there are no interaction with the main grid.}
\end{itemize}

\subsection{Problem Formulation}\label{subsec:32}
The main objective is to minimize the total cost the energy bought from the main grid to achieve a high productivity while considering future energy prices and weather dependent renewable energy generators. Let $\mathrm{M}$ denotes the set of components of the micro-grid (or controllable machine components), such that $M_i \in \mathrm{M}, \forall i \in [0, M-1]$  with $ M \in \mathbb{N}$. We assume that each component $M_i$ can take an energy state $s_{i,t}$ (i.e. “stopped”, “running”, “aborted”, “standby”, etc.) at the time step $t  \in \mathbb{N}$ and the dynamic power consumption $P_i^t$ of $M_i$ solely depends on the current state $s_{i,t}$ of the component and the current time step $t$: $P_i^t=P_i (t, s_{i,t})$. The total energy requested/sold from/to the main grid $E_i^t$ at time interval $\triangle t$ over the complete time horizon $T \in \mathbb{N}$ is therefore the sum of the power consumed/generated of all components during the time horizon. Please notice that $P_i^t$ can also be negative in the case of renewable energy sources or regenerative energy consumers for example.

%
\begin{equation}
E_i =\sum_{t=0}^{T-1}{ P_i^t \cdot \triangle t}, \forall i \in [0, M-1]
\end{equation}
%

 If $\lambda_t^- \in \mathbb{R}$ is the actual energy price and $\lambda_t^\sim \in \mathbb{R}$ the forecasted energy price at a time step $t$, the optimization problem can be formulated for the time horizon $T$ as follow:

%
\begin{equation}
\label{eq:problem}
minimize \sum_{k=0}^{t}{ {\lambda_t^-} \cdot ({ \sum_{i=0}^{M-1}{ P_i (k, s_{i,k}) \cdot \triangle t } })}+  \sum_{l=t+1}^{T-1}{\lambda_t^\sim \cdot ({ \sum_{i=0}^{M-1}{ P_i (l, s_{i,l}) \cdot \triangle t  } }) }
\end{equation}

If $a_l (s_{i,l-1},s_{i,l})$ denotes the action of changing the state of the component $M_i$ at time $l$ from the state $s_(i,l-1)$ to the state $s_(i,l)$, the Eq. \ref{eq:problem} can be rewritten as follow:

\begin{equation}
\label{eq:problem_reformulated}
minimize \sum_{k=0}^{t}{ {\lambda_t^-} \cdot ({ \sum_{i=0}^{M-1}{ P_i (k, s_{i,k}) \cdot \triangle t } })}+  \sum_{l=t+1}^{T-1}{\lambda_t^\sim \cdot ({ \sum_{i=0}^{M-1}{ P_i (l, a_l (s_{i,l-1},s_{i,l})) \cdot \triangle t  } }) }
\end{equation}

Several constraints should be taken into consideration. One of them is the power balance between the energy demand of the micro-grid and the energy supply from the main grid:

\begin{equation}
\label{eq:constraint_energy_balance}
	\sum_{i=0}^{M-1}{ E_i} \leq E_{max}^\sim,  \forall i \in [0, M-1]
\end{equation}
where $E_i$ denotes the total energy demand of the micro-grid component $M_i$ over the time horizon $T$ and $E_{max}^\sim$ the total available energy from the main grid.

In addition, the total energy consumption of the micro-grid at each time interval $t$ should satisfy the upper and lower bound given by the overall load profile and a tolerance interval. This constraint can be expressed as follows:

\begin{equation}
\label{eq:constraint_load_profile}
	L_{target}^\sim - \triangle L^\sim \leq {\sum_{i=0}^{M-1}{ P_i (t, s_{i,t})} } \leq L_{target}^\sim + \triangle L^\sim
\end{equation}
with $L_{target}^\sim$  being the target load at time step $t$, $\triangle L^\sim$  a symmetric tolerance around $L_{target}^\sim$ and $ i \in [0, M-1]$

As expressed above, solving the optimization problem is equivalent to compute at each time step the optimal state (by choosing the action $a_l (s_{i,l-1},s_{i,l})$ ) so that the resulting total energy cost of the micro-grid for a complete time horizon is globally minimized. If every component of the micro-grid is controlled by an agent, then the optimization problem is equivalent to finding a coordinated strategy for all the agents. In this case, the main challenge lies in the volatility of future energy prices and the direct dependence of future energy consumption from actual decisions. Furthermore, other constraints such as the the throughput, production time, the product quality, the production cost, etc. have to be considered.

\subsection{Markov Game Formulation}
The formulated optimization problem can be transformed into a reinforcement learning task, where each agent controlling a component of the grid has to learn a policy that maximizes a cumulative reward signal derived from the objective function and is conditioned by the constraints formulated in Eq. \ref{eq:constraint_energy_balance} and Eq. \ref{eq:constraint_load_profile}.

If we consider the global state of the environment as the aggregation of the observations of all agents, then the observed state of the environment solely depends on the actions of all the agents and the previously observed global state of the environment. In other words, no external factors besides the actions of all the agents will affect the dynamics of the environment. Under this assumption, the multi-agent reinforcement-learning task satisfies the Markov property and can be therefore formulated as a Markov decision process (MDP).

In this work, we consider a multi-agent extension of Markov decision processes called observable Markov games \cite{Littman1994multiagent}. A Markov game for $N$ agents is defined by a set of states $\mathrm{S}$ describing the possible configurations of all agents, a set of actions $\mathrm{A}_1, \mathrm{A}_2, \ldots, \mathrm{A}_N$ and a set of observations $\mathrm{O}_1,\mathrm{O}_2, \ldots, \mathrm{O}_N$ for each agent. To choose actions, each agent $i ( i= 1,2,\ldots, N)$ uses a stochastic policy $\pi_{\theta_i} : \mathrm{O}_i \times \mathrm{A}_i \mapsto [0; 1]$, where $\theta_i$ are the parameters of the policy. The policy produces the next state according to the state transition function $T : \mathrm{S} \times  \mathrm{A}_1 \times ...  \times \mathrm{A}_N \mapsto \mathrm{S}$. Each agent $i$ obtains rewards as a function of the state and agent’s action $r_i : \mathrm{S} \times \mathrm{A}_i  \mapsto \mathbb{R}$, and receives a private observation correlated with the environment state $o_i : \mathrm{S} \mapsto \mathrm{O}_i$. The initial states are determined by a distribution  : $\mathrm{S} \mapsto [0; 1]$. Each agent $i$ aims to maximize its own total expected return $R_i = \sum_{t=0}^{T}{\gamma^t \cdot r_i^t}$ where $\gamma^t$ is a discount factor at time step $t$ and $T$ is the time horizon. The \textit{action-value function} is defined as $\mathrm{Q}^{\pi_i}(s_{i,t}, a_t^i)=\mathbb{E}[\mathrm{R}_i^t|s_{i,t},a_t^i]$, while the \textit{state-value function} is defined as $\mathrm{V}^{\pi_i}(s_{i,t})=\mathbb{E}[\mathrm{R}_i|s_{i,t}]$. The
\textit{advantage function} $\mathrm{A}^{\pi_i}(s_{i,t}, a_t^i) = \mathrm{Q}^{\pi_i}(s_{i,t}, a_t^i) - \mathrm{V}^{\pi_i}(s_{i,t})$ describes whether taking action $a_t^i$ is better or worse for agent $i$ when in state $s_{i,t}$ than the average action of policy $\pi_{\theta_i}$.

For our micro-grid, we provide a uniform representation of the operational state of the grid components which is illustrated in Fig. \ref{fig:state_chart}. The state space of every agent is represented by the operation state of the grid component it controls aggregated with the target load of the grid, the current  time step within  the production shift, the amount of production tasks to execute as well as the current energy price. Notice that we do not assume inter-dependencies between the production tasks. The action space of each agent is represented by all the actions that can change the operational state of a grid component (See Fig. \ref{fig:state_chart}). The reward of each agent depends on the type of the grid component it controls and therefore is use case dependent. See Eq. \ref{eq:total_reward} in section \ref{subsec:42} for more details.

 % For figures use
%
\begin{figure}[h!]
%\sidecaption
% Use the relevant command for your figure-insertion program
% to insert the figure file.
% For example, with the graphicx style use
\includegraphics[scale=.40]{images/StateMachine_EFlex}
%
% If no graphics program available, insert a blank space i.e. use
%\picplace{5cm}{2cm} % Give the correct figure height and width in cm
%
\caption{Uniform state representation of a grid component. Every component can be stopped, halted, suspended, powered up or aborted. Once the component reach the $execute$-state then it begins to execute a production task, to generate energy or to store/release energy.}
\label{fig:state_chart}       % Give a unique label
\end{figure}


\chapter*{Introduction}
\addcontentsline{toc}{chapter}{Introduction}
Nowadays, there are only a few aspects of everyday life that are not affected by modern technologies, and the rise of technologies like \textit{Internet of Things} lowers this number even more. These technologies produce large amounts of data with temporal stamp, also recognized as time series. As the amount and speed, at which we are getting new data, are making it impossible to process and analyze them manually, we are in need for fast analytics tools for time series data.

Our work focuses on methods for analyzing large datasets of long time series, demonstrating it on a power consumption dataset.  We are using the approach to transform the dataset into a spatial feature space representation. Using this representation, we prepare multiple visualizations for exploring the structures within the dataset and detailed views for examining time series details. To supply the analysis, we apply clustering and anomaly detection methods. This work is divided into four chapters.

Chapter 1 will discuss metrics used for time series, their complexity, advantages and disadvantages, and their application in practical analysis. Afterwards, it explores the representations of time series datasets in artificial feature space. Finally, it examines clustering and anomaly detection methods available for large datatasets.

Chapter 2 will discuss techniques for visual representation and analysis of time series datasets. Firstly, it analyzes the dimensionality reduction techniques for transforming the datasets into low-dimensional embeddings. Secondly, it goes through algorithms for downsampling time series with a specific focus on visual analysis.

Chapter 3 applies the methods from the first two chapters to analyze a large power consumption dataset, while introducing a novel approach for time series transformation.

Chapter 4 is a conclusion of our work, containing the discussion of the benefits and drawbacks of our novel approach about the novel approach for time series transformation, and possible future research directions in this field.


\subsection{part a}
\begin{itemize}
    \item $K=0.5$
    \begin{figure}[H]
        \caption{Nichols chart for $KG, (K=0.5)$}
        \centering
        \includegraphics[width=16cm]{../Figure/Q1/Q1_a/Q1_aK_0.5.png}
    \end{figure}
    \item $K=1$
    \begin{figure}[H]
        \caption{Nichols chart for $KG, (K=1)$}
        \centering
        \includegraphics[width=16cm]{../Figure/Q1/Q1_a/Q1_aK_1.png}
    \end{figure}
    \item $K=5$
    \begin{figure}[H]
        \caption{Nichols chart for $KG, (K=5)$}
        \centering
        \includegraphics[width=16cm]{../Figure/Q1/Q1_a/Q1_aK_5.png}
    \end{figure}
\end{itemize}
Phase margin and gain margin are shown in above figures and all closed loop systems are unstable with $K$ form 1 to 5. In all of them phase margin is negetive.