\documentclass[twocolumn]{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{hyperref}

\newcommand{\sample}{This is a normal text. \\ \textsf{This is a text sans serif.} \\ \texttt{This is a typewriter text.} \\ $\int_{4}^{8}xdx + \sum_{k=0}^{10} k^{2}+0.123456789 $}

\begin{document}

\section*{Common font families list}

More font families and information can be found on this page: \url{https://en.wikibooks.org/wiki/LaTeX/Fonts#Font_families}

\subsection*{Computer Modern Roman (default)}

\fontfamily{cmr}\selectfont
\sample

\subsection*{Latin Modern Roman}

\fontfamily{lmr}\selectfont
\sample

\subsection*{Latin Modern Dunhill}

\fontfamily{lmdh}\selectfont
\sample

\subsection*{Bookman}

\fontfamily{pbk}\selectfont
\sample

\subsection*{Charter}

\fontfamily{bch}\selectfont
\sample

\subsection*{New Century Schoolbook}

\fontfamily{pnc}\selectfont
\sample

\subsection*{Palatino}

\fontfamily{ppl}\selectfont
\sample

\subsection*{Times}

\fontfamily{ptm}\selectfont
\sample

\end{document}


\documentclass[12pt]{article}
\begin{document}
\newcounter{problem}
\thispagestyle{empty}

\section*{NYU Physics 1---Problem set 0}

Due Tuesday 2009 September 15 at the beginning of lecture.

\paragraph{Problem~\theproblem:}\refstepcounter{problem}%
\textsl{(a)}~What is the maximum amount of cash you can obtain by
successfully robbing an armored truck?  Assume that it is packed with
twenties; that is, estimate an answer by considering the volume of the
truck, and (harder to estimate) the volume of a 20-dollar bill.  State
your assumptions and explain your work, but please don't attempt an
experiment.  Be sure to explain exactly how you estimated the volume
of a 20-dollar bill.  \emph{Hint: think of a stack of bills to
  estimate the volume.  Feel free to \emph{check} any part of your
  answer on the internet, but make sure you actually make a justified,
  quantitative estimate independently.}

\textsl{(b)}~Do you think that many of the armored trucks in Manhattan
are fully packed with 20-dollar bills?

\textsl{(c)}~Would a similar truck weigh more, less, or about the same
if it contained the same amount of money but in the form of gold bars
instead of 20-dollar bills?

\paragraph{Problem~\theproblem:}\refstepcounter{problem}%
After having read the dropped bucket write-up, answer the following
approximate questions about air resistance:

\textsl{(a)}~Two pennies are dropped (carefully) from a tall building,
one so that it falls precisely edge-on, and one so that it falls
precisely face-on (difficult but not impossible in practice).  What is
the ratio of terminal velocities
$v_{\mathrm{edge}}/v_{\mathrm{face}}$?

\textsl{(b)}~If the building is 50 stories tall, what is the ratio
$v_{\mathrm{ff}}/v_{\mathrm{edge}}$ of the free-fall velocity
$v_{\mathrm{ff}}$ you would naively calculate if you ignored air
resistance to the terminal velocity of the penny dropped edge-on?

\textsl{(c)}~Roughly how far does a typical American car have to drive
to ``sweep up'' or drive through a column of air that is comparable in
weight to the car itself?  You will have to estimate the
cross-sectional area and weight of a typical car (or look both things
up on the web; if you look them up, give the make and model).

\paragraph{Extra Problem (will not be graded for credit):}%
Describe in words the \emph{environmental significance} of the
distance you calculated in the second part of the previous problem.

\end{document}


% !TEX root = main.tex

\chapter{Introduction}\label{chap:intro}

\input{01A_events}
\input{01B_elementary}
\input{01C_classical_and_frequentist}


\documentclass[11pt,fullpage]{article}
\usepackage{graphicx}
\usepackage{fullpage}

\usepackage{amsmath}
\usepackage{mathtools}

\usepackage[utf8]{inputenc}

\usepackage{listings}
\usepackage{xcolor}

\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\lstdefinestyle{mystyle}{
    backgroundcolor=\color{backcolour},
    commentstyle=\color{codegreen},
    keywordstyle=\color{magenta},
    numberstyle=\tiny\color{codegray},
    stringstyle=\color{codepurple},
    basicstyle=\ttfamily\footnotesize,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    keepspaces=true,
    numbers=left,
    numbersep=2pt,
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize=1
}
\lstset{style=mystyle}

%\usepackage{afterpage}
%\usepackage{fullpage}
%
% \usepackage{fancyhdr}
% \pagestyle{fancy}
% \rhead{Y.  Ben Asher  No.1438/17}
% \lhead{}

\begin{document}
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \newtheorem{theorem}{Theorem}[section]
 \newtheorem{corollary}{Corollary}[section]
 \newtheorem{lemma}{Lemma}[section]
 \newtheorem{exercise}{Exercise}
 \newtheorem{claim}{Claim}[section]
 \newtheorem{definition}{Definition}[section]
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %\hsize=6in
 %\vsAXe=9in
 %indent=.25in
 %skip=.080in
 %\baselineskip=.05in
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\def \n { \{1..n \} }
\def\proof{\noindent{\bf Proof:~}}
\def\Proof{\noindent{\bf Proof:~}}
\def\blackslug{\hbox{\hskip 1pt \vrule width 4pt height 8pt
    depth 1.5pt \hskip 1pt}}
\def\QED{\quad\blackslug\lower 8.5pt\null\par}
\def\mul {\times}
\def \lr {\longrightarrow}
\def \sr {\longrightarrow}
\def \Lr {\longleftarrow}
\def \dr {{\downarrow}}
\def \bs {\backslash }
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand \nxt[1]{
             \stackrel{#1}{\lr}
}

\newcommand \sss[1]{
            \begin{array}[t]{l}
             #1\stackrel{\mbox{\tiny no}}{\lr}\\
             \dr
            \end{array}
}
\newcommand {\spp}[1] {
           \begin{picture}(30,30)
           \put(10,20){\sequence(1,0){20}}
           \put(10,20){\sequence(0,-1){20}}
           \put(16,22){n}
           \put(6,10){y}
           \put(0,22){#1}
           \end{picture}
         }

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand{\utrans}[3]{
\begin{center}\tt
\renewcommand{\arraystretch}{1.4}
\begin{tabular}{|p{#3 mm}|}
\hline
\vspace*{-3ex}~\parbox{0pt}{\begin{tabbing} #1 \end{tabbing}} \\ \hline
#2 \\
\hline
\end{tabular}
\end{center}
}

%
\title{Scheduling on restricted uniformly related machines.}
\author{Ebrahim Kashkoush   \\
course Adviser Prof. leah epstein \\
 University of Haifa
      }

\date{}

\maketitle

\section{Abstract}

in this project we try to solve scheduling problem by using three Heuristics Local search,Branch and bound and genetic heuristic. we write three unattached projects in each one we use one heuristic,we can get better  and faster algorthim by Combining more than one heuristic or by using more complex algorthims like evaluate pairs of chromosomes instead of chromosomes ,and use more complex target function in genitic. but the main idea of the project was to learn the basic concept of the following heuristics.\newline

The problem is Scheduling on restricted uniformly related machines, where the Input is An integer number of machines m $\geq$ 2. A set of n jobs J=\{1,2,...,n\}
where job j has an integer processing time  $P_j > 0$ Machines speeds $s_i \in \{1,2,4\}$  for i= 1,2,...,m , we solve the same problem in the three heuristics
\section{Local Search}
The local search algorthim It consists of several steps we will Explain the algorithm step by step
\subsection{pre preparing(initial solution)}
to start running the local search algorthim  first we need initial solution. we have as input two files: the first file is for tasks , where we have on each line  task time (integer value) .  the second file is for machines , where each line contains machine speed    (integer 1,2,4). from the input we build two vectors the first one hold the tasks and the second hold the machines . after having data structure hold the tasks and the machines , we should Hand out the tasks into  the machines and make initial soulation , so we need  greedy algorithm . its not important how good is the greedy algorthim . also if we hand out the task randomly , at the end we will have the same result .  so for convenience we insert the numbers to minmum heap  to sort the tasks and then we handing out the tasks into machines In a fair way (we go through the machines In a circular) and  each time  we give the same amount tasks as the current machine speed value to the machine . for example if we have machine with speed 2 we will give it two task each time ,and if the machine speed 4 we will give it 4 tasks each time . we do that while we still have tasks, and when we hand out all the tasks
we have an initial solution.
\subsection{Local Search for two machines}
on this subsection and on the next subsections we will solve small problems , and then we will combine all of them together in the last subsection , creating the full problem solution. \newline
the current problem is given two machines $m_1$  and $m_2$ we want to find the best tasks from $m_1$  and $m_2$   that if we
swap them bettwen  $m_1$  and $m_2$  we get the best Improvement to achive the Goal . so now we should define what is the goal that we want to achive.\newline
givin two machines   $m_1$  and $m_2$ where the time of $m_1$ is X and the time of $m_2$ is Y . let assume that we chose $k$ tasks from $m_1$ and $r$ tasks from $m_2$  now we should evaluate the time after swapping the tasks (simulation) between the two machines by passing $k$ tasks from $m_1$ to $m_2$ and removing the $k$ tasks from $m_1$ ,and the same by passing $r$ tasks from $m_2$ to $m_1$ and removing the tasks from $m_2$. lets define the time of $m_1$ after the change is A and the time of $m_2$ after the change (swaping the tasks) is B .  our goal that we want to achive:\newline
 (max\{A,B\}$<$max\{X,Y\} $ ||$ ( max\{A,B\}=max\{X,Y\}  and (A+B)$<$(X+Y))) \newline
that means if we save the best solution and we find new soultion by swaping $k , r$ tasks bettwen $m_1$ and $m_2$ and that soulation  better than the best soulation for now, we save it as the best soulation and we save $r, k$ tasks and then we check the other $k, r$ compinition with the
new best solution after we check all possible to choice  $r, k$ we have the best $r,k$ that by swaping them we achive our goal NOTE($k $ and $ r$ is constant).\newline
the idea of adding ( max\{A,B\}=max\{X,Y\}  and (A+B)$<$(X+Y)) is to give priority to machines with high speed we want to fill machines with high speed also
if the final soulation still the same (max\{A,B\}), because that help us to find bigger task to swap in the future.
\subsection{All posible combination of r,k}
as we saw in previous section we need to go through all possible  combinations of choosing $k$ tasks from $m_1$ (the same about $r$) as we know from mathematics we have  $\binom{n}{k}$ different combination. where $n$ is the number of tasks on $m_1$ and $k$ is the number of taskt that we want to choose from $m_1$ to swap them.\newline
we can solve the combination problem easily by using recursion and array with size $k$  (int data[k]) , we go through all the $n$ tasks we start from first task (first function call) and we call the function recursively twice the first call with array data that we add to it task1 and the second one with array data without adding to it task1, in general in the $p$ funcion $call$ we call the function recursively twice ,the first time with adding $task_k$ to data array and the second with out adding it.
and when data array is full and we fill all the k cells we have new  combination.\newline
in other words the idea that each task has two possibilities the first one is to be part of the combination and the second its not part of the combination.
\subsection{combination of two machines}
i go through all possible cobinations of two machines twice on different order the code is so easy so writing the code is more simple than to dscribe it :\newline
\lstinputlisting[language=c]{e.txt}
\subsection{all togther}
we show above how to go  through all posible combinations of pair of two machine.  and on each  combination of two machines  how to go through all possible combination of $k$ tasks from $m_1$ and $r$ tasks from $m_2$ (where $k$ and $r$ is constant) and how to choose the best combination of choosing $k$,$r$(how we applay LocalSearch on this two machines) (we check all the combination of choose $k$ from $machine_1$ with all the combination of choose $r$ from $machine_2$ "each combination from $machine_1$ with all the combination of $machine_2$ ")

so we can write one function $LocalSearchNxM(k,r)$ and applied LocalSearch that swap $k$ tasks from first machine with $r$ from second machine  and we go through all combination of two machine like we said above \newline
this is the main LocalSearch Function:\newline
Where: \newline
LevelZero(): is function implement local search that only pass one task each time from $machine_1$ to $machine_2$ with the same roles above.\newline
 LocalSearchNxM(k,r): function implement localsearch where we want to swap each time $k$ tasks from $m_1$ with $r$ tasks from $m_2$ \newline
if  there is no improvement in the current level we did not run the next level , and if there is no level on this itertion has improvement we stop the while .and after we stop we print the result
 \lstinputlisting[language=c]{Local.txt}

\section{Branch and bound}
on this heuristic we should build tree, each node on the tree has lower bound and higher bound , each edge bettwen father and son represent handing out task to the son, where each node represent machine , so each father has at most children's as the number of machines, so the path from the root to each node in the level-$k$ (node with deapth $k$) represents handing out the first $k$ task where $edge_j$ represent handing out $task_j$  . but we will not build all the tree because if there node that have lower bound equal or greater than any upper bound on any node on the tree there is no need to continue to his son's becouse we will not get better soultion than the node with the upper bound, for that reason we have also a global upper bound that his value is the minimum value on all  the upper bounds that we have on all the nodes that we build to that point.(on building each node we update his value if the node upper bound is less than the global). upper bound can be greedy algorithm  result but unlike Local search the greedy algorithm is important because bad greedy algorithm mean that we need to build more nodes on the tree, and as result we will have to wait more time to get the solution, so here for example its good idea to set the result of local search as upper bound but we did not do that because  most of the time we get optimal soultion using local search and  our goal to learn the  heuristic and to find the best way to calculate the upper and lower bounds.\newline
so our greedy algorthim is LPT ( Longest Processing Time Algorithm) . also the sequence of handing out the tasks on branch and bound algorthim is important by handing out the big tasks first can help us to build less nodes because  the lower bound grow and get bigger faster, also this issue in line with LPT ,so $task_1$ is the biggest task and $task_n$ is the smallest task , and on each path  $edge_p$ represent handing out the $task_p$.\newline
 At the end we want to run the program on personal computer and our challenge is to build algorthim with good Space complexity (use less amount of memory space ) . if we use BFS tree traversals algorthim we need a huge memory because on the first levels of the tree we can't determine if the path is good and we need to build  and save more nodes that we can't remove node before we make sure that this path is bad path and we will not continue to his son's, also if we be satisfied  to save only one level (depth) each time (save the last level of depth nodes and one each nood save the path from the root (each task to each machine))  the amount of nodes could be huge , despite that the BFS does not guarantee better soultion, on the other hand , using , DFS we can build solution with linear space complexity and also that help the global upper bound to decrease faster because we cant to determine tight upper bound if we still have many tasks to handing out because the upper bound will be for all possible different solution of handing out the other tasks (maximum possible upper bound), so going deeper help us make tighted upper bound, and DFS go deeper fast. we can build solution using DFS that his maximum space complixty $m*n$ where $m$ is the number of machines and $n$ is the number of tasks.\newline
we have customized DFS in our soluation the defult is to going to the worst son first (son's with the highest time first ) we have the option going to the best son's first (have lowest time first (where the time is the time of the worst machine)) by deleting ($\#$define BadFirst) on file scheduling.h . the idea of choosing  best son's first is to get tight upper bound faster and that help us to build less nodes, on the other hand the idea of choosing worst son's first is to  make the lower bound grow faster and as result we build less nodes, we try the three options without sorting( orginal DFS) ,bad first and best first we get the result of bad son's first is the best. and we also have to option to sort the tasks at the beginning like we said above big tasks first  or run without sorting by removint the define ($\#$define \_WithSort) but as we explain with sort is more better .
to save time also i added some rules: if we have optimal solution we stop, and if there two son's or more with the same speed and the same time we call recursively only one of them, and if i have solution better than the global upper boung we  update the upper bound to it.
\section{Genetic algorithm}
our default Genetic algorithim has on each generation 100 Chromosome ,and we build new generation by four mutation and 48 pairing ,where by mutation we can make one new Chromosome ,and by pairing we can make two new Chromosomes the default number of generation is one thousand, all the parameters above you can change them on scheduling.h they they defined as $\#define$ . we have also about twenty fitness function where the defult is function number 17 you can also  choose more than one function and the program print different files  for each function as result, you can choose interval of function to run by changing the defines($\#define   $ Bf ,  $\#define  $ Ef)
\subsection{first generation}
we have function that builds vector with size $m$ where $m$ is machines number and the sum of the values on the vector is $n$ where $n$ is the number of tasks, assume the name of the vector is $vec$ we give each $machin_j$ , $vec[j]$ tasks and on this way we have one solution and we build on Chromosome we repeat that 100 times making 100 Chromosomes (each time we build from scratch  $vec$ and handing out the tasks to the machines randomly) we make the survival Chromosome the best chrmosome  time
\subsection{mutation}
we pick random numbers $k,m$ where $k,m \leq n$ and $m-k <n$ where $n$ is the tasks number ,and in Chromosome class we have hashmap that have pairs $<$task index, machine index$>$ we use that hash map to change the machine for each $k\leq$ task index $\leq m$ for each task index we pick randomly a machine the defult is that new machine should be different than the old ,but there is an option to enable pick the same machine (it will be like to randomly choose who from this interval we change).\newline
its ok that we  change   interval of sequence of indexs and we didn't  pick randomly tasks because the tasks it self random and doesn't sorted ,we change the machine index in the hash map and also pass the task from the old machine to the new one the we pick randomly.\newline
 \subsection{pairing}
as we saw in mutation we have hash map the same thing we pick randomly $k,m$ but here if we have $j$ where $k<j<m$ and in $Chromosome_1$  $task_j$ in machine $m_A$ and in $Chromosome_2$  $task_j$ in machine $m_C$ we swap between the machines in the two Chromosomes that means after the change we will find $task_j$ in $Chromosome_1$ at $m_C$ , and $task_j$ in $Chromosome_2$ at $m_A$
there are two option of pairing the defult that $Chromosome_1$ $\neq$  $Chromosome_1$ (we can't pair Chromosome with it self) the second option allows that as kind of mutation
\subsection{Fitness function}
for each Chromosome we call the fitness function and build probability vector see 4.5 ,we have 20 Fitness function that they combination of:\newline
Y: Chromosome time (the time of maximum machine)\newline
X:Optimal time (the sum of tasks dividing the sum of machines speed)\newline
a : median time (the machine that have the median time on this Chromosome )
worsGM : the worst machine in all the Chromosomes\newline
min : the machin with the smallest time in the current Chromosomes (local)\newline
max (the same Y) : the machin with the biggest time in the current Chromosomes (local) == Y\newline

\subsection{randomly picking Chromosome for mutation/pairing  }
for each Chromosome we call the fitness function and enter the result into vector then we normalize the vector to probability  that the sum of all the cells on the vector is one $\sum\limits_{i=0}^{vector.size} vector.at(i) ==1$ now we have on $vector_i$ the probability of $Chromosome_i$ after that we applay to the vector that code
\lstinputlisting[language=c]{com-f.c}
 now we have monotonically increasing  vector bettwen zero to one we pick random number between zero and one and find out where it fall in the vector and return the appropriate Chromosome\newline
here the default is repeating random but there is an option to enable non-repeating random

  \subsection{ build new generation}
 as we said above we build it by 4 mutation and 48 pairing.
\bibliographystyle{plain}

\bibliography{pr}
\end{document}


% Question  ##################################################################################################################
\section{Question 1}\label{ssec:pt2q1}
\textbf{Consider an investment portfolio consisting of \$100K in Aluminium and \$400K in Zinc. The daily
volatility of Aluminium is 0.70\% and for Zinc is 0.20\%. The correlation coefficient between them is
0.70.}
% END Question  ##############################################################################################################

% Question (i) ###############################################################################################################

\subsection{Q1 (i)}\label{sssec:pt2q1i}
\textbf{Calculate the 15-day, 99\% Value at Risk (VaR) of the portfolio.}

\noindent
Code to calculate the 15-day, 99\% Value at Risk (VaR) of the portfolio for this question can be found in ‘Question 1 (i)’ in the python notebook.

\noindent
The 15-day VaR(99\%) for the portfolio is \$12,484.54 with a portfolio volatility of \$5,358.17.

% END Question (i) ###########################################################################################################

% Question (ii) ##############################################################################################################

\subsection{Q1 (ii)}\label{sssec:pt2q1ii}
\textbf{Comment on the impact of diversification on the portfolio VaR (what would be the VaR if the total \$500K is invested in only Aluminium and Zinc?).}

\noindent
After answering question (i) the VaR(99\%) was calculated as if the full \$500K was to be invested in Aluminium only. The 15-day VaR(99\%) for this asset would be $(2.33 \times 0.007 \times \sqrt{15} \times 500K)$ which is equal to \$31,584.18. On the other hand, if the \$500K was invested in Zinc only the 15-day VaR(99\%) would be $(2.33 \times 0.002 \times \sqrt{15} \times 500K)$ which is equal to \$9024.05.

\noindent
With a a correlation of 0.70 between Aluminium and Zinc, both assets are likely to move in the same direction which means if one increases or decreases in price the other is likely to do so, since they are positively correlated. This correlation alone already indicates that the diversification in this portfolio is not ideal, since the reason of diversification is to invest in non-correlated assets. In fact although the VaR(99\%) of the portfolio (\$12,484.54) is less than the VaR(99\%) when investing in Aluminium only (\$31,584.18), it is still higher than the VaR(99\%) when investing in Zinc only (\$9024.05).

\noindent
So this indicates that using diversification in this case in not beneficial since the reason for diversification is to decrease risk. If both assets were less correlated, say with a 0.1 correlation the diversification for this portfolio would be beneficial as the VaR(99\%) for the portfolio would be \$7,877.33 but in this specific case both assets have a high positive correlation of 0.70 which makes diversification not beneficial.

% END Question (ii) ##########################################################################################################


\documentclass[handout]{beamer}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
  \ifdim\Gin@nat@width>\linewidth
    \linewidth
  \else
    \Gin@nat@width
  \fi
}
\makeatother

\definecolor{fgcolor}{rgb}{0.345, 0.345, 0.345}
\newcommand{\hlnum}[1]{\textcolor[rgb]{0.686,0.059,0.569}{#1}}%
\newcommand{\hlstr}[1]{\textcolor[rgb]{0.192,0.494,0.8}{#1}}%
\newcommand{\hlcom}[1]{\textcolor[rgb]{0.678,0.584,0.686}{\textit{#1}}}%
\newcommand{\hlopt}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlstd}[1]{\textcolor[rgb]{0.345,0.345,0.345}{#1}}%
\newcommand{\hlkwa}[1]{\textcolor[rgb]{0.161,0.373,0.58}{\textbf{#1}}}%
\newcommand{\hlkwb}[1]{\textcolor[rgb]{0.69,0.353,0.396}{#1}}%
\newcommand{\hlkwc}[1]{\textcolor[rgb]{0.333,0.667,0.333}{#1}}%
\newcommand{\hlkwd}[1]{\textcolor[rgb]{0.737,0.353,0.396}{\textbf{#1}}}%
\let\hlipl\hlkwb

\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
 \def\at@end@of@kframe{}%
 \ifinner\ifhmode%
  \def\at@end@of@kframe{\end{minipage}}%
  \begin{minipage}{\columnwidth}%
 \fi\fi%
 \def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
 \colorbox{shadecolor}{##1}\hskip-\fboxsep
     % There is no \\@totalrightmargin, so:
     \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
 \MakeFramed {\advance\hsize-\width
   \@totalleftmargin\z@ \linewidth\hsize
   \@setminipage}}%
 {\par\unskip\endMakeFramed%
 \at@end@of@kframe}
\makeatother

\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX

\usepackage{alltt}
%\documentclass{beamer}
% ***************************************************************

\usepackage{graphicx}
%\usepackage{psfrag, pstricks}
\usepackage{amsmath,amssymb,array,comment,eucal}
\input{macros}
\title{Bayesian Variable Selection}

\author{Hoff Chapter 9,  Mixtures of g-Priors Liang et al JASA}
\date{\today}
%\Logo(-1.9,7.3){\includegraphics[width=.5in]{../eps/duke}}
% Optional: text to put in the bottom of each slide.
% By default, the title of the talk will be placed there.
%\slideCaption{\textit{October 28, 2005 }}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
% make the title slide
\maketitle
\begin{frame}[fragile]  \frametitle{US Air Example}

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}

{\centering \includegraphics[width=\maxwidth]{figure/data-1}

}

\end{knitrout}

\end{frame}

\begin{frame}[fragile] \frametitle{lm summary}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{verbatim}
lm(formula = log(SO2) ~ temp + log(firms) + log(popn) + wind +
    precip + rain, data = usair)
Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept)  6.7142760  1.6475086   4.075 0.000261 ***
temp        -0.0649495  0.0227711  -2.852 0.007333 **
log(firms)   0.3698588  0.1934076   1.912 0.064289 .
log(popn)   -0.1771293  0.2335520  -0.758 0.453428
wind        -0.1738606  0.0656713  -2.647 0.012204 *
precip       0.0156032  0.0132718   1.176 0.247893
rain         0.0009153  0.0057335   0.160 0.874104
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5108 on 34 degrees of freedom
Multiple R-squared:  0.5503,	Adjusted R-squared:  0.471
F-statistic: 6.936 on 6 and 34 DF,  p-value: 7.12e-05

\end{verbatim}
\end{kframe}
\end{knitrout}

\end{frame}

\begin{frame}\frametitle{Zellner's g-prior}
  Centered model:  $$\Y = \1 \alpha + \X^c \b + \epsilon$$
  where $\X^c$ is the centered design matrix where all variables have
  had their mean subtracted \pause
\begin{itemize}
\item  $p(\phi) \propto 1/\phi$  \pause
\item   $p(\alpha \mid \phi) \propto 1$ \pause
\item  $\b \mid \alpha, \phi, \g \sim \N(0, g \phi^{-1}
  ({\X^c}^\prime \X^c)^{-1})$ \pause
%\item  take $g=n$
\end{itemize}

$$\b \mid \Y, \alpha, \phi \sim N\left(\frac{g}{1 + g} \bhat, \phi^{-1}\frac{g}{1 + g} (\X^T\X)^{-1} \right)$$
$$ \phi \mid \Y \sim \Gam \left(\frac{n-1}{2}, \frac{\SSE + \frac{1}{1 + g} \bhat^T (\X^T\X) \bhat}{2} \right) $$
\end{frame}

\begin{frame} \frametitle{joint posterior draws of beta's}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}

{\centering \includegraphics[width=\maxwidth]{figure/sim-1}

}

\end{knitrout}

\end{frame}

\begin{frame} \frametitle{Bayesian Variable Selection}
  \begin{itemize}
   \item Avoid the use of redundant variables (problems with
    interpretations) \pause
   \item Inclusion of un-necessary terms yields less precise
  estimates, particularly if explanatory variables are highly
  correlated with each other \pause
  \item reduced MSE: reduced variance but possibly higher bias  \pause
  \item it is too ``expensive'' to use all variables
  \end{itemize}
\end{frame}

\begin{frame}\frametitle{Bayesian Model Choice}
  \begin{itemize}
  \item
Models for the variable selection problem  are based on a subset of
  the $\X_1, \ldots \X_p$ variables  \pause

\item Encode models with a  vector $\g = (\gamma_1, \ldots
  \gamma_p)$  where  $\gamma_j \in \{0,1\}$
  is an indicator for whether variable $\X_j$ should be included in
  the model $\Mg$.  $\gamma_j = 0 \Leftrightarrow \beta_j
  = 0$  \pause
\item Each value of $\g$ represents one of the $2^p$ models.
\pause
\item Under model $\Mg$:
 $$\Y \mid \alpha, \b, \sigma^2, \g \sim \N(\one \alpha + \Xg \b_\gamma,
 \sigma^2 \I) $$
Where $\Xg$ is design matrix  using the columns in $\X$ where
 $\gamma_j = 1$ and $\b_{\g}$ is the subset of $\b$ that are non-zero.

\end{itemize}

\end{frame}

\begin{frame}\frametitle{Posterior Probabilities of Models}

  \begin{itemize}
  \item Posterior model probabilities
$$p(\M_j \mid \Y) = \frac{ p(\Y \mid \M_j)p(\M_j)}{\sum_jp(\Y \mid
  \M_j)p(\M_j)} $$ \pause
Marginal likelihod of a model is proportional to
$$ p(\Y \mid \Mg) = \iint p(\Y \mid \b_\gamma,
  \sigma^2)p(\b_\gamma \mid \g, \sigma^2)p(\sigma^2 \mid \g)
  d\b\, d\sigma^2$$\pause
  \item Probability $\beta_j \ne 0$: $\sum_{\M_j:  \beta_j \ne 0}
    p(\M_j \mid \Y)$ (marginal posterior inclusion probability) \pause
  \end{itemize}
\end{frame}

\begin{frame}\frametitle{Prior Distributions}
  \begin{itemize}
  \item Bayesian Model choice requires  proper prior distributions on
  regression coefficients (exception parameters that are included in all models) \pause
  \item Vague but proper priors may lead to paradoxes! \pause
  \item Conjugate Normal-Gammas lead to closed form expressions for
  marginal likelihoods, Zellner's g-prior is one of the most popular.
  \end{itemize}

\end{frame}
\begin{frame}\frametitle{Zellner's g-prior within Models}
Centered model:  $$\Y = \1 \alpha + \Xg^c \b_\gamma + \epsilon$$

\begin{itemize}
\item Common parameters $$p(\alpha, \phi) \propto \phi^{-1}$$  \pause
\item Model Specific parameters
$$\b_\gamma \mid \alpha, \phi, \g \sim \N(0, g \phi^{-1}
  ({\Xg^c}^\prime \Xg^c)^{-1})$$ \pause
%\item  take $g=n$
\item Marginal likelihood of $\Mg$  is proportional
to $$ p(\Y \mid \Mg) = C (1 + g)^{\frac{n-p-1}{2}} ( 1 + g (1 -
 R^2_\gamma))^{- \frac{(n-1)}{2}}$$
where $R^2_\gamma$ is the usual $R^2$ for model $\Mg$ and $C$ is a constant that is $p(\Y \mid \M_0)$ (model with intercept alone)
\pause
\item  uniform distribution over space of models $p(\Mg) = 1/(2^p)$
\end{itemize}
\end{frame}

\begin{frame}[fragile] \frametitle{USair Data: Enumeration of All Models}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{library}\hlstd{(devtools)}
\hlkwd{suppressMessages}\hlstd{(}\hlkwd{install_github}\hlstd{(}\hlstr{"merliseclyde/BAS"}\hlstd{))}  \hlcom{# current version}
\hlkwd{library}\hlstd{(BAS)}
\hlstd{poll.bma} \hlkwb{=} \hlkwd{bas.lm}\hlstd{(}\hlkwd{log}\hlstd{(SO2)} \hlopt{~} \hlstd{temp} \hlopt{+} \hlkwd{log}\hlstd{(firms)} \hlopt{+}
                             \hlkwd{log}\hlstd{(popn)} \hlopt{+} \hlstd{wind} \hlopt{+}
                             \hlstd{precip}\hlopt{+} \hlstd{rain,}
                  \hlkwc{data}\hlstd{=usair,}
                  \hlkwc{prior}\hlstd{=}\hlstr{"g-prior"}\hlstd{,}
                  \hlkwc{alpha}\hlstd{=}\hlnum{41}\hlstd{,}    \hlcom{# g = n}
                  \hlkwc{n.models}\hlstd{=}\hlnum{2}\hlopt{^}\hlnum{7}\hlstd{,}\hlcom{# enumerate (can omit)}
                  \hlkwc{method}\hlstd{=}\hlstr{"deterministic"}\hlstd{)}   \hlcom{# fast enumeration}
\end{alltt}
\end{kframe}
\end{knitrout}

\end{frame}

\begin{frame}\frametitle{residual plot)}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{plot}\hlstd{(poll.bma,} \hlkwc{which}\hlstd{=}\hlnum{1}\hlstd{)}
\end{alltt}
\end{kframe}

{\centering \includegraphics[width=\maxwidth]{figure/resplots-1}

}

\end{knitrout}
\end{frame}

\begin{frame}\frametitle{Model Complexity)}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{plot}\hlstd{(poll.bma,} \hlkwc{which}\hlstd{=}\hlnum{3}\hlstd{)}
\end{alltt}
\end{kframe}

{\centering \includegraphics[width=\maxwidth]{figure/sizeplots-1}

}

\end{knitrout}
\end{frame}

\begin{frame}\frametitle{Inclusion Probabilities)}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{plot}\hlstd{(poll.bma,} \hlkwc{which}\hlstd{=}\hlnum{4}\hlstd{)}
\end{alltt}
\end{kframe}

{\centering \includegraphics[width=\maxwidth]{figure/pipplots-1}

}

\end{knitrout}
\end{frame}

\begin{frame}[fragile]\frametitle{Model Space}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{summary}\hlstd{(poll.bma)}
\end{alltt}
\begin{verbatim}
##            P(B != 0 | Y)  model 1   model 2    model 3   model 4   model 5
## Intercept      1.0000000 1.000000 1.0000000 1.00000000 1.0000000 1.0000000
## temp           0.9762282 1.000000 1.0000000 1.00000000 1.0000000 1.0000000
## log(firms)     0.7659857 1.000000 1.0000000 1.00000000 1.0000000 1.0000000
## log(popn)      0.4075393 0.000000 1.0000000 1.00000000 0.0000000 0.0000000
## wind           0.8080832 1.000000 1.0000000 1.00000000 1.0000000 1.0000000
## precip         0.6615960 1.000000 1.0000000 1.00000000 1.0000000 0.0000000
## rain           0.4166394 0.000000 0.0000000 1.00000000 1.0000000 1.0000000
## BF                    NA 1.000000 0.2093987 0.03277353 0.1544798 0.3022674
## PostProbs             NA 0.209600 0.1097000 0.10300000 0.0809000 0.0634000
## R2                    NA 0.542700 0.5500000 0.55030000 0.5427000 0.5130000
## dim                   NA 5.000000 6.0000000 7.00000000 6.0000000 5.0000000
## logmarg               NA 7.616228 6.0527128 4.19809382 5.7485360 6.4197847
\end{verbatim}
\end{kframe}
\end{knitrout}
\end{frame}

\begin{frame}\frametitle{Summary}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{image}\hlstd{(poll.bma)}
\end{alltt}
\end{kframe}

{\centering \includegraphics[width=\maxwidth]{figure/summary-1}

}

\end{knitrout}
\end{frame}

\begin{frame}[fragile] \frametitle{Coefficients}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
 \hlstd{beta} \hlkwb{=} \hlkwd{coef}\hlstd{(poll.bma,} \hlkwc{n.models}\hlstd{=}\hlnum{1}\hlstd{)}
 \hlstd{beta}
\end{alltt}
\begin{verbatim}
##
##  Marginal Posterior Summaries of Coefficients:
##
##  Based on the top  1 models
##             post mean  post SD   post p(B != 0)
## Intercept    3.15300    0.07818   1.00000
## temp        -0.07130    0.01268   0.97623
## log(firms)   0.23428    0.08573   0.76599
## log(popn)    0.00000    0.00000   0.40754
## wind        -0.17998    0.06128   0.80808
## precip       0.01884    0.00729   0.66160
## rain         0.00000    0.00000   0.41664
\end{verbatim}
\end{kframe}
\end{knitrout}
\end{frame}

\begin{frame}[fragile] \frametitle{Coefficients}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
 \hlkwd{par}\hlstd{(}\hlkwc{mfrow}\hlstd{=}\hlkwd{c}\hlstd{(}\hlnum{2}\hlstd{,}\hlnum{2}\hlstd{));}  \hlkwd{plot}\hlstd{(beta,} \hlkwc{subset}\hlstd{=}\hlkwd{c}\hlstd{(}\hlnum{3}\hlstd{,} \hlnum{6}\hlstd{))}
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/coefplot-1}

\end{knitrout}

\end{frame}

\begin{frame}[fragile] \frametitle{Bayesian Confidence Intervals}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{confint}\hlstd{(beta)}
\end{alltt}
\begin{verbatim}
##                  2.5  %     97.5  %        beta
## Intercept   2.994993257  3.31101398  3.15300362
## temp       -0.096926645 -0.04567203 -0.07129934
## log(firms)  0.061014518  0.40753936  0.23427694
## log(popn)   0.000000000  0.00000000  0.00000000
## wind       -0.303835463 -0.05612195 -0.17997871
## precip      0.004105874  0.03357242  0.01883915
## rain        0.000000000  0.00000000  0.00000000
## attr(,"Probability")
## [1] 0.95
## attr(,"class")
## [1] "confint.bas"
\end{verbatim}
\end{kframe}
\end{knitrout}
\end{frame}

\end{document}

\begin{frame}
  \frametitle{Problem with g Prior}

The Bayes factor for comparing $\Mg$ to the null
model:
$$
 BF(\Mg : \M_0) =    (1 + g)^{(n - 1 - p_\g)/2} (1 + g(1 - \R^2))^{(n-1)/2}
$$

\begin{itemize}
\item Let $g$ be a fixed constant and take $n$ fixed.
\item Let $F = \frac{R_g^2/\pg}{(1 - R_\g^2)/(n - 1 - \pg)}$
\item As $R^2_\g \to 1$, $F \to \infty$ LR test would reject $H_0$
\end{itemize}

usual $F$ statistic for  comparing model $\Mg$ to $\M_0$

\end{frame}
\section{Mortality}
\begin{frame}[fragile]
\frametitle{Mortality \& Pollution}
  \begin{itemize}
  \item Data from Statistical Sleuth 12.17 \pause
  \item 60 cities \pause
\item response Mortality \pause
\item measures of HC, NOX, SO2 \pause
\item Is pollution associated with mortality after adjusting for other
  socio-economic and meteorological factors? \pause
\item 15 predictor variables implies $2^{15} = 32,768$ possible models
  \pause
\item Use Zellner-Siow Cauchy prior  $1/g \sim  G(1/2, n/2)$
  \end{itemize}
\begin{verbatim}
mort.bma = bas.lm(MORTALITY ~ ., data=mortality,
                  prior="ZS-null",
                  alpha=60,  n.models=2^15,
                  update=100, initprobs="eplogp")
\end{verbatim}
\end{frame}

\begin{frame}\frametitle{Posterior Distributions}
  \includegraphics[height=3.5in]{mort-sum}
\end{frame}

\begin{frame}[fragile]
\frametitle{Posterior Probabilities}
  \begin{itemize}
  \item What is the probability that there is no pollution effect? \pause
\item Sum posterior model probabilities over all models that include
  no pollution variables \pause
\begin{verbatim}
> which.mat = list2matrix.which(mort.bma,1:(2^15))
> poll.in = (which.mat[, 14:16] %*% rep(1, 3)) == 0
> sum(poll.in * mort.bma$postprob)
[1] 0.9889641
\end{verbatim}\pause
\item Posterior probability is $0.011$ \pause
\item Odds that there is an effect  $(1 - .011)/(.011) = 89.6$ \pause
\item Prior Odds $7.9 = (1 - .2^3)/.2^3$ \pause
\item Bayes Factor for a pollution effect $ 89.6/7.9 = 11.3$ \pause
\item Bayes Factor for NOX based on marginal inclusion probability
  $0.917/(1 - 0.917) = 11.0$ \pause
\item Marginal inclusion probability for logHC =  0.427144
\item Marginal inclusion probability for logSO2 = 0.218978
\end{itemize}
Bayes Factors are not additive!
\end{frame}
\begin{frame}\frametitle{Model Space}
  \includegraphics[height=3.5in]{mort-image}
\end{frame}
\begin{frame}\frametitle{Coefficients}
  \includegraphics[height=3.5in]{mort-beta1}
\end{frame}

\begin{frame}\frametitle{Coefficients}
  \includegraphics[height=3.5in]{mort-beta2}
\end{frame}

\begin{frame}
  \frametitle{Effect Estimation}
  \begin{itemize}
  \item  Coefficients in each model are adjusted for other variables
    in the model
\item OLS:  leave out a predictor with a non-zero coefficient then
  estimates are biased!
\item Model Selection in the presence of high correlation, may leave
  out "redundant" variables;
\item improved MSE for prediction (Bias-variance tradeoff)
\item Bayes is biased anyway so should we care?
\item What is meaning of $\sum_{\g} \beta_{j \g} \gamma_j P(\Mg \mid \Y)$
  \end{itemize}
  Problem with confounding!  Need to change prior?

\end{frame}

\begin{frame}\frametitle{Model Selection}
  Selection of a single model has the following problems \pause
  \begin{itemize}
  \item When the criteria suggest that several models are equally
    good, what should we report?  Still pick only one model? \pause
\item What do we report for our uncertainty after selecting a model?  \pause
  \end{itemize}
Typical analysis ignores model uncertainty! \pause
\vfill

Winner's Curse
\end{frame}

\begin{frame}\frametitle{ Other Problems}

  \begin{itemize}
  \item Computational \pause
  if $p > 35$  enumeration is difficult \pause
  \begin{itemize}
  \item Gibbs sampler or Random-Walk algorithm on $\g$ \pause
  \item poor convergence/mixing with high correlations \pause
  \item Metropolis Hastings algorithms more flexibility \pause
  \item "Stochastic Search" (no guarantee samples represent posterior) \pause
  \item in BMA all variables are included, but coefficients are
   shrunk to 0; alternative is to use Shrinkage methods \pause
  \end{itemize}
\item Prior Choice: Choice of prior distributions on $\b$ and on $\g$ \pause
\end{itemize}

\bigskip Model averaging versus Model Selection  -- what are objectives?

\end{frame}
\end{document}


% !TeX encoding = UTF-8
% !TeX program = lualatex
% !TeX spellcheck = en_US
% !TeX root = thesis.tex

\chapter{Building aerodynamics}
\label{chap:building_aerodynamics}

This chapter gives an overview on flow characteristics for bluff bodies as well as the basics of fluid dynamics necessary for understanding natural ventilation. The chapter ends with a summary of prediction models for natural ventilation, how they have evolved and which limitations should be considered.

%
% %
% % %
% % % %
% % %
% %
%

\section{Basics of fluid dynamics}
\label{sec:basic_of_fluid_flow}

\subsection{Flow characteristics around bluff bodies}

Geometries in building aerodynamics are often simplified to cuboids. These geometries, characterized by flat surfaces and sharp corners are commonly referred to as "bluff bodies". Streamlines around those bodies do not follow their shape. Flow separation occurs at sharp edges or corners where the flow momentum exceeds weaker viscous forces. This leads to a development of shear layers as well as a  turbulent wake area behind the body (see \fref{fig:flowaroundbuilding}).

\begin{figure}[htb]
	\centering
	\includegraphics[width=0.9\linewidth, trim= 0cm 1cm 0cm 0cm, clip]{images/flow_around_building}
	\captionsetup{format=plain}%,labelsep=newline}
	\caption[Flow characteristics around a bluff body]{Horizontal section of flow characteristics around a bluff body. The Bernoulli's equation for airflow is valid for the mean flow along a streamline. Adapted from \cite{Aynsley1999}.}
	\label{fig:flowaroundbuilding}
\end{figure}

\subsection{Bernoulli equation}

The Bernoulli equation relates fluid pressure energy, kinetic energy, as well as potential energy of fluid flow along a streamline to each other. It may be considered as a measure of conservation of energy appropriate for fluid flows. Despite small pressure variations, density is considered to be constant for most flows of liquids and gases at low Mach numbers ($Ma \leq \num{0.3}$) \citep{fischer2008experimentelle, Hucho2011}. A further assumption is that the fluid is non-viscous and its flow is steady. The equation for any arbitrary point along a streamline is:

\begin{equation}
p_{tot} = p_{stat} + p_{dyn} + \rho \cdot g \cdot z = constant
\end{equation}

The total pressure refers to the sum of the aforementioned parts. If the variation in temperature is to be neglected or sufficiently small to be ignored, there is no significant change in potential energy along the streamline. Thus,  the above equation reduces to the following simplified form:

\begin{equation}
p_{tot} = p_{stat} + p_{dyn} = constant
\end{equation}

Static pressure is the pressure at a specific point in a fluid acting in all directions. Static pressure can always
be defined, whether or not the fluid is in motion.
Dynamic pressure represents kinetic energy per unit volume of a fluid particle acting in direction of the flow. It is defined as:

\begin{equation}
q = \frac{1}{2} \cdot \rho \cdot u^2
\end{equation}

This equation forms the basis of most air flow calculations used. When using the equation for a streamline around a bluff body, it is evident that the maximum pressure occurs at a point where the flow is brought to rest. This is commonly referred to as the stagnation point. Here, the kinetic energy of the approaching flow is converted into static pressure. Thus, the maximum dynamic pressure is equal to $0.5 \rho u^2$ (see \fref{fig:flowaroundbuilding}).

%The velocity then can be calculated as:
%
%
%\begin{equation}
%u = \sqrt{ \frac{2 \cdot q}{\rho} }
%\end{equation}

A flow occurs if an opening is placed onto a wall separating two regions of air with different pressure levels.
By evaluating the discharge coefficient, the volumetric flow rate is given by:

\begin{equation}
Q  = S \cdot C_d \cdot A  \sqrt{ \dfrac{2\cdot|\Delta p|}{\rho}}
\end{equation}

where

\begin{equation}
S  = Sign [\Delta p]
\end{equation}

For a rectangular opening, the discharge coefficient $C_d$ is usually assumed to be in the range of \num{0.6} and \num{0.7} \citep{Chu2009}.

%\begin{equation}
%C_d  = \frac{\dot{m}}{A} \sqrt{\frac{\rho}{2\Delta p}}
%\end{equation}

%Rearranging the definition of $C_d$, the flow rate through the opening is given by

For a cross-ventilation layout with two openings on opposite walls, a more advanced equation can be defined as:

\begin{equation}
q = \frac{Q}{u_{H} A_{1}} = C_{d_1} \left[ \frac{r_{a}^2 C_{d_r}^2 }{1+ r_{a}^2 C_{d_r}^2} |c_{p_1}-c_{p_2}| \right ] ^\frac{1}{2}
\label{eq:theory:flowrate_advanced}
\end{equation}

where $A_1$ is the opening area of the windward opening, $u_H$ is the external wind velocity at the building height and $c_p$ is the pressure coefficient on the external wall. The ratio of opening areas $r_a$ is defined as  $A_2/A_1$ and the ratio of discharge coefficients is $C_{d_r}  = C_{d_2}/C_{d_1}$, representing the (1) windward and (2) leeward facades, respectively \citep{Chu2014}.
\Fref{eq:theory:flowrate_advanced} can be used to calculate the flow-rate of cross ventilation, though it does not take into account flow resistance caused by furniture or wall friction, which imposes limitations on its usage.

\subsection{Pressure coefficients}
\label{sec:theory:pressure_coefficients}

In order to compare different geometries, it is useful to introduce a normalized pressure coefficient.
The pressure coefficient is a dimensionless number which describes the relative pressures throughout a flow field.  The pressure coefficient at a point near a body is independent of the body size. It is defined as:

\begin{equation}
c_p = {p_{node} - p_\infty \over \frac{1}{2} \rho_\infty u_{\infty}^2 }
\end{equation}

%\begin{equationitem}
%	\item $p_{node}$ is the pressure at the point at which pressure coefficient is being evaluated
%	\item $p_{\infty}$ is the pressure in the free-stream (i.e. remote from any disturbance). In this case it is the static pressure
%	\item $\rho_{\infty}$ is the free-stream fluid density
%	\item $u_{\infty}$ is the free-stream velocity of the fluid
%\end{equationitem}

where
$p_{node}$ is the pressure at the point at which the pressure coefficient is being evaluated,
$p_{\infty}$ is the pressure in the free-stream (free from any disturbance),
$\rho_{\infty}$ is the free-stream fluid density, and
$u_{\infty}$ is the free-stream velocity of the fluid.
We can also write:

\begin{equation}
c_p = {p_{node} - p_{tot} + q  \over q }
\end{equation}

With this conversion we can say that a $c_{p}$ of \num{0} indicates that the pressure is the same as the free-stream pressure, a
$c_{p}$ of \num{1} indicates the pressure is the stagnation pressure and the point is a stagnation point, and a
$c_{p}$ within $-{\infty} \leq c_{p} \leq 0$  is a significant under pressure region in the flow-field.

%\begin{equationitem}
%	\item $c_{p}$ of 0 indicates the pressure is the same as the free stream pressure.
%	\item $c_{p}$ of 1 indicates the pressure is stagnation pressure and the point is a stagnation point.
%	\item $c_{p}$ within $-{\infty} \leq c_{p} \leq 0$  is significant under-pressure domain in the flow-field
%\end{equationitem}

\subsection{Reynolds number}
\label{sec:reynolds_number}

Turbulent flows face flow separation.
In order to predict in which condition a flow separation happens, the relative intensity of inertia forces related to the momentum of the moving fluid in terms of its viscous forces needs to be evaluated. This ratio is called the Reynolds number.

%Generally speaking, for Reynolds numbers below 2000, the flow is laminar. For greater numbers $Re_{crit}$ a transition zone occurs until flow happens to be fully turbulent if $Re \gg Re_{crit}$.

When comparing flows around similar geometries with different scales, the Reynolds numbers should be similar. This is important for wind tunnel models, as the geometry is often a limiting factor (cf. \fref{sec:theory:limitations}).

\subsection{Boundary Layers}
\label{sec:theory:boundary-layer}

The fluid molecules at the surface of solid objects stick to that surface, which leads to shear stress that is caused by the interaction of stationary and moving molecules. The layer between those stationary particles and the point where molecules have reached \SI{99}{\percent} of the free-stream velocity is called boundary layer.

Boundary layers are characterized by their flow properties. For boundary layers where viscous forces are dominant, a laminar flow will be established. For air flows, the laminar boundary layer is very unstable due to the air's low viscosity \cite{Aynsley1999}. The transition from a laminar to a turbulent boundary layer is depicted in \fref{fig:boundarylayer}. The low-law, buffer and viscous sub-regions and their importance is further discussed in  \fref{sec:CFD:boundary_layer}.

\begin{figure}[bht]
	\centering
	\includegraphics[width=1\linewidth]{images/boundary_layer.pdf}
	\captionsetup{format=plain}
	\caption[Development of a boundary layer over a flat plate]{Development of a boundary layer over a flat plate, including the transition from the laminar to the turbulent region. Adapted from \citep{Cengal2006}.}
	\label{fig:boundarylayer}
\end{figure}

\subsection{Atmospheric boundary layer}
\label{sec:atmABLbasics}

%Wind evolves because of pressure differences.
%Let $\Delta p$ be a pressure difference of $\Delta p = p_1 < p_2$. As a result, a fluid motion initiated which we call wind.
On an atmospheric scale, the pressure differences are the result of density gradients which are created by incoming solar irradiation that heats up the surface of the globe in different magnitudes.
The warm air rises which leads to jet streams at an altitude where the ground friction can be neglected.
The further these jet streams reach the earth's surface, the more influence the ground friction has.
Close to the surface, the roughness of the earth creates a turbulent layer which is called the \gls{ABL}.
\Fref{fig:theory:ABL_example} (a) shows the \gls{ABL} over three types of surface roughnesses, city, suburbia and sea. For each category, the plots ends when $u = \SI{4}{\metre\per\second}$ is reached.

\begin{figure}[!bt]
	\subfloat[][]%
	{\includegraphics[height=0.4\textwidth, trim = 30 250 35 300, clip=true]{images/atmospheric_boundary_layer_comparison}}
	\subfloat[][]%
	{\includegraphics[height=0.4\textwidth]{images/atmospheric_boundary_layer}}
	\captionsetup{format=plain}
	\caption[Atmospheric boundary layer over three types of surface roughnesses]{Atmospheric boundary layer over three types of surface roughnesses. \textbf{(a)} The \ABL\ over city, suburbia and sea. For each surface, the plots ends when $u = \SI{4}{\metre\per\second}$ is reached. \textbf{(b)} All plots shown up to a height of $\SI{300}{\metre}$ for comparison. }
	\label{fig:theory:ABL_example}
\end{figure}

The wind shear is quantified by the exponent $\alpha$ in the power law equation \ref{eq:power_law} that relates wind velocities at two different altitudes.

\begin{equation}
u(z)=u_{ref}\left( \frac{z}{z_{ref}}\right )^\alpha
\label{eq:power_law}
\end{equation}

%\begin{itemize}
%	\item $\alpha$ is the wind shear exponent
%	\item $z$ is the height above ground
%\end{itemize}

%where $\alpha$ is the wind shear exponent and
where $z$ is the height above the reference height. The larger the exponent $\alpha$, the larger the vertical gradient in the wind speed. This equation is accurate for altitudes from \SI{100}{\metre} up tp the top of the atmospheric boundary layer.
For altitudes closer to the ground level, the following logarithmic relation is more applicable \citep{Ghiaus2012,Hucho2011}.

\begin{equation}
u(z) = \frac{u^*}{\kappa} ln \left( \frac{z+z_0}{z_0}\right)
\end{equation}

where \gls{symb:u*} is the \glsdesc{symb:u*}, \gls{symb:kappa} is the \glsdesc{symb:kappa} and \gls{symb:z_0} is the \glsdesc{symb:z_0}. The \glsdesc{symb:z_0}s for different terrains may be found in  \fref{tab:davenport_roughness_class} in the appendix.

Measured wind data have to be converted to a specific site, as wind data is usually collected at airport sites, which correspond to a roughness range of \SIrange{0.0024}{0.03}{} \cite{Ragheb2016}. Translation the data to a specific location is not an easy task because of the irregularities of the urban texture \citep{Ratti2002}.

%\enlargethispage*{3cm}
The \gls{DIN} \citep{DIN105542005} suggests a modified profile in which the equation is tailored to certain terrains with the help of the constant $C_{terrain}$. \Fref{tab:boundary_layer_roughness_alpha} shows certain terrain types that can be used with their own specific characteristics described.
Note that the $z_0$ values by \gls{DIN} are not consistent with the ones provided in the appendix, which stresses the point that these are empirical values.

\begin{equation}
u(z)=C_{terrain} \cdot u_{ref}\left( \frac{z}{z_{ref}}\right )^\alpha
\end{equation}

\begin{table}[hbt]
	\small
	\centering
	\captionsetup{format=plain}
	\caption[Coefficient of terrain for different surface roughnesses]{Coefficient of terrain for different surface roughnesses. Both values are needed to transfer data in a homogeneous site \citep{DIN105542005}.}
	\label{tab:boundary_layer_roughness_alpha}
	\begin{tabular}{llSSS}
		\toprule
		Category&  	Description									& {$C_{terrain}$}   & {$\alpha$} 		& {$z_0$} \\
		\midrule
		I 	&	Sea, flat landscape             			& 1.18 				& 0.12     			& 0.01  \\
		II 	&	Agricultural landscape         				& 1.0  				& 0.16     			& 0.05  \\
		III &	Suburbia, forest              				& 0.77 				& 0.22     			& 0.3   \\
		IV 	&	Cities 										& 0.56 				& 0.30    			& 1.0   \\
		\bottomrule
	\end{tabular}
\end{table}


\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}

% \usepackage{fullpage}
% \usepackage[top=1in, bottom=1in, left=1in, right=1in]{geometry}
\usepackage[margin=1in, paperwidth=8in, paperheight=8in]{geometry}

\usepackage{amsfonts}

\title{Introduction to \LaTeX}
\author{Nelson Estevão}
\date{\today}

\begin{document}

\maketitle

\section{Introduction}

I really like stuff. The set of Natural numbers are, usually, represented by $\mathbb{N}$.

\end{document}


\chapter{\label{a5-extractors}Charge Extractor Investigations}

\minitoc

\section{Introduction}

In Chapter~\ref{ch6-reduction}, the different algorithms for extracting charge from a waveform are extensively discussed, as well as the important considerations one must be vigilant of when producing a charge-extraction algorithm. The purpose of this appendix is to demonstrate the performance of the \textit{Cross Correlation} charge-extraction method, in contrast to the simpler \textit{Window Integration} approach. I performed this investigation in the context of the \gls{chec-s} prototype.

\section{Integration Window}

\begin{figure}
  \includegraphics[width=\textwidth]{charge_extraction_window_wf}
  \caption[Definition of integration window on a waveform.]{Example waveform from a Monte Carlo simulation of CHEC-S, containing an approximately \SI{50}{\pe} signal. The ``on'' and ``off'' regions used to extract the signal-to-noise are illustrated. The window start position is defined as the peak position subtracted by the window shift. The window end position is defined as the window start plus the window size. A window size of 5 corresponds to 5 samples being included in the integration.}
  \label{fig:charge_extraction_window_wf}
\end{figure}

\begin{figure}
  \begin{subfigure}[b]{0.49\textwidth}
    \includegraphics[width=\textwidth]{amp1nsb5}
    \caption{1~p.e. illumination, 5~MHz noise.}
    \label{fig:amp1nsb5}
  \end{subfigure}
  \hfill
  \begin{subfigure}[b]{0.49\textwidth}
    \includegraphics[width=\textwidth]{amp1nsb125}
    \caption{1~p.e. illumination, 125~MHz noise.}
    \label{fig:amp1nsb125}
  \end{subfigure}
  \hfill
  \begin{subfigure}[b]{0.49\textwidth}
    \includegraphics[width=\textwidth]{amp50nsb5}
    \caption{50~p.e. illumination, 5~MHz noise.}
    \label{fig:amp50nsb5}
  \end{subfigure}
  \hfill
  \begin{subfigure}[b]{0.49\textwidth}
    \includegraphics[width=\textwidth]{amp50nsb125}
    \caption{50~p.e. illumination, 125~MHz noise.}
    \label{fig:amp50nsb125}
  \end{subfigure}
  \caption[Optimal integration-window parameters.]{Contour plot of signal-to-noise as a function of window width and shift, for different amplitudes and noise values. The maximum, annotated with the cross and position, indicates the optimal integration-window parameters when applied to a CHEC-S waveform. The contours are split into percentiles of the range; the top \SI{5}{\percent} of values are contained in the brightest yellow contour. Negative values correspond to an integration window concentrated on the undershoot of the pulse.}
  \label{fig:snr_noc}
\end{figure}

As an alternative to the \textit{Cross Correlation} integration approach, one may instead use a simple integration window, defined by the number of samples inside the ``window width'', and the number of samples the window is ``shifted'' from the peak time. The definitions of ``window width'' and ``window shift'' are illustrated in Figure~\ref{fig:charge_extraction_window_wf}. In order to investigate the performance of the integration-window approach fairly, one must first optimise the values for the width and shift of the window when extracting charge from a \gls{chec-s} waveform. This exercise was performed using a Monte Carlo simulation of the lab set-up, where the camera was uniformly illuminated. The pulse time is consistent in simulations of this nature, therefore the same pulse time is manually chosen for every waveform. This allows the following investigation to be solely on the integration approach, avoiding any dependence on the peak finding.

\subsection{Optimal Integration Window Parameters}

As explained in Chapter~\ref{ch6-reduction}, the optimal integration window parameters are noise dependent; a larger integration window is likely to include more noise (\gls{nsb} and \gls{dcr}). However, a larger window size results in more of the signal being captured. In Figure~\ref{fig:snr_noc}, the signal-to-noise ($S/N$) as a function of integration-window parameters is shown for different amplitude and noise values. The $S/N$ investigation was performed as follows. Assume an ``on'' region of the waveform, where the extracted value contains the signal plus the noise, and an ``off'' region where the extracted value contains solely the noise contributions (Figure~\ref{fig:charge_extraction_window_wf}). The optimal window for a constant signal on top of a fluctuating background is then found by:
\begin{equation} \label{eq:snr}
S/N = \frac{\mu_\text{on}}{\sigma_\text{off}},
\end{equation}
where $\mu_\text{on}$ is the average signal extracted from the ``on'' region, and $\sigma_\text{off}$ is the standard deviation of the signal extracted from the ``off'' region. The approach of Equation~\ref{eq:snr} is an alternative to looking for the optimal window for a fluctuating signal on top of a fluctuating background ($S/N = \frac{\mu_\text{on}}{\sigma_\text{on}}$), which, due to the inclusion of the signal deviations from the ``on'' region, is much less sensitive to the noise fluctuations and has a strong dependence on the signal level, i.e.\@ the Poisson fluctuations of the signal increases with amplitude.

In Figure~\ref{fig:snr_noc} the conflict between a large window size to contain the full signal, and a small window to minimise noise is evident, resulting in a limited region in which a high signal-to-noise can be achieved. In conclusion, an integration window width of 5 samples and a shift of 2 samples appeared to be optimal for a noise of \SI{125}{MHz}, for both small and large amplitudes (Figures~\ref{fig:amp1nsb125} and \ref{fig:amp50nsb125} respectively). This integration window is demonstrated in Figure~\ref{fig:charge_extraction_window_wf}. As the \textit{Charge Resolution} requirements are defined at an \gls{nsb} of \SI{125}{MHz}, these window parameters are adopted for the following investigations.

\subsection{Comparison with \textit{Cross Correlation}}

As described previously in the thesis, the most appropriate performance criterion for a charge extraction technique used for a \gls{cta} camera is the \textit{Charge Resolution}. Outlined in Section~\ref{section:crprocedure} are the names I have defined to distinguish between different \textit{Charge Resolution} procedures, each using different datasets and/or procedures. In order to evaluate the performance of the \textit{Cross Correlation} technique with respect to a simple integration window, their resulting \textit{Charge Resolutions} were compared in investigations that explore the relevant parameter space.

\begin{figure}
  \includegraphics[width=0.9\textwidth]{cr_8_ce_comparison_lab}
  \caption[\textit{Charge Resolution} comparison between \textit{Cross Correlation} and \textit{Window Integration} for \textit{Lab} data.]{\textit{Charge Resolution} of the \textit{Cross Correlation} charge extraction approach applied to uniformly illuminated lab data, compared to the \textit{Charge Resolution} of the integration window approach for the same dataset. The Y axis is limited to exclude the high values that arise from saturation.}
  \label{fig:cr_8_ce_comparison_lab}
\end{figure}

The first comparison is shown in Figure~\ref{fig:cr_8_ce_comparison_lab}. It explores the comparative performance in the context of the measurements using the \textit{Lab} dataset (i.e.\@ using the real camera). A small performance improvement is observed with the cross-correlation technique for $Q_\text{Exp} > 10$~\si{\pe}.

\begin{figure}
  \includegraphics[width=0.9\textwidth]{cr_8_ce_comparison_opct40}
  \caption[\textit{Charge Resolution} comparison between \textit{Cross Correlation} and \textit{Window Integration} for \textit{MCLab} data with an optical crosstalk of \SI{40}{\percent}.]{\textit{Charge Resolution} of the \textit{Cross Correlation} charge extraction approach compared to the \textit{Charge Resolution} of the integration window approach, for both \SI{5}{MHz} and \SI{125}{MHz} \gls{nsb} noise. The dataset used is produced by Monte Carlo simulations of the camera uniformly illuminated, replicating the lab set-up (i.e.\@ the \textit{MCLab} procedure). The optical crosstalk of the photosensors in the simulation is \SI{40}{\percent}.}
  \label{fig:cr_8_ce_comparison_opct40}
\end{figure}

In a comparison of the two extraction approaches when used in a simulation using the \gls{chec-s} model, shown in Figure~\ref{fig:cr_8_ce_comparison_opct40}, it is evident that the \textit{Cross Correlation} approach performs worse than the \textit{Window Integration}, especially at higher \gls{nsb}.

\begin{figure}
  \includegraphics[width=0.9\textwidth]{cr_8_ce_comparison_opct20}
  \caption[\textit{Charge Resolution} comparison between \textit{Cross Correlation} and \textit{Window Integration} for \textit{MCLab} data with an optical crosstalk of \SI{20}{\percent}.]{Same as Figure~\ref{fig:cr_8_ce_comparison_opct40}, but with a dataset containing an optical crosstalk value of \SI{20}{\percent}.}
  \label{fig:cr_8_ce_comparison_opct20}
\end{figure}

Figure~\ref{fig:cr_8_ce_comparison_opct20} shows a similar comparison to the previous one, however the optical crosstalk of the simulation model was reduced to \SI{20}{\percent}. The result is an improved performance when using the \textit{Cross Correlation} technique at low \gls{nsb} rate. However, at high \gls{nsb}, the \textit{Window Integrator} performs slightly better.

\begin{figure}
  \includegraphics[width=0.9\textwidth]{cr_8_ce_comparison_high_noise}
  \caption[\textit{Charge Resolution} comparison between \textit{Cross Correlation} and \textit{Window Integration} for \textit{MCLab} data with a high amount of electronic noise.]{Same as Figure~\ref{fig:cr_8_ce_comparison_opct40}, but with a dataset containing a factor of 10 higher electronic noise.}
  \label{fig:cr_8_ce_comparison_high_noise}
\end{figure}

Finally, in Figure~\ref{fig:cr_8_ce_comparison_high_noise} a simulation of \gls{chec-s} is used, but with a factor of 10 higher electronic noise. As a result, the \textit{Cross Correlation} technique significantly improves the performance with respect to the \textit{Window Integrator}.

\subsection{Conclusion}

The comparisons of \textit{Charge Resolution} have confirmed our understanding of the \textit{Cross Correlation} method:
\begin{itemize}
\item The \textit{Cross Correlation} method amplifies anything correlated with reference pulse shape. This includes \gls{nsb} and optical crosstalk factors. Therefore, when these are the dominant noise factors in the waveforms, the \textit{Window Integrator} performs slightly better.
\item When noise that is uncorrelated with the reference pulse shape is present in the waveform, such as a high amount of electronic noise, the \textit{Cross Correlation} is an extremely useful tool to resolve the signal.
\end{itemize}
It would appear that with the current simulation model of \gls{chec-s}, the major noise components are those correlated with the reference pulse shape. Therefore, not much improvement is available through the \textit{Cross Correlation} technique. However, when the optical crosstalk of the \glspl{sipmt} is lowered to \SI{10}{\percent} (see Section~\ref{section:sipmt_future}), the other noise factors such as electronic noise could become a relatively significant contribution to the total noise (as occurs in Figure~\ref{fig:cr_8_ce_comparison_opct20}). This would therefore justify the use of the \textit{Cross Correlation} technique.

Despite the conclusion obtained from the simulations, there does appear to be an improvement when using the \textit{Cross Correlation} method for measurements of the real camera (Figure~\ref{fig:cr_8_ce_comparison_lab}). The only likely source of uncorrelated noise at $Q_\text{Exp} > 10$~\si{\pe} is from the residuals in the Transfer Function calibration. It would appear that the \textit{Cross Correlation} method suppresses this additional noise component introduced by the calibration.  As the Transfer Functions are not present in the simulations, this affect is not apparent in the \textit{Charge Resolution} results obtained from them.

A further investigation into the actual parameter regions of Equation~\ref{eq:charge_res_req} which justify the use of the \textit{Cross Correlation} approach is intended for the future.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UMB-CS110-2015S: Introduction to Computing
% Copyright 2015 Pejman Ghorbanzade <pejman@ghorbanzade.com>
% Creative Commons Attribution-ShareAlike 4.0 International License
% More info: https://github.com/ghorbanzade/UMB-CS110-2015S
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def \topDirectory {.}
\def \texDirectory {\topDirectory/src/main/tex}

\documentclass[12pt,letterpaper,twoside]{article}
\usepackage{\texDirectory/template/style/directives}
\usepackage{\texDirectory/template/style/assignment}
\input{\texDirectory/template/config}

\begin{document}

\doc{title}{Solution to Quiz 3(a)}
\doc{date-pub}{Mar 31, 2015 at 01:00 PM}
\doc{date-due}{Apr 01, 2015 at 11:00 PM}
\doc{points}{4}

\prepare{header}

\section*{Question 1}

You are asked to develop a simple ticket printing machine for box-office of a small cinema with a total of 50 seats, 10 seats in each row.
Ticketing procedure is based on a few simple policies as follows:

\begin{enumerate}[itemsep=-2mm,label={}]
	\item Rows closer to screen are always prioritized.
	\item Seats in a row are filled from the leftmost to the rightmost.
	\item All seats assigned to a group of people must be in the same row.
\end{enumerate}

Develop a class \texttt{Theater.java} with class members that you think are required for this objective and use your class in a program \texttt{TicketSale.java} that prompts ticket seller for number of tickets to print, showing the number of total available seats at the same time.
If sufficient number of seats are available in a single row, your program should print the list of seats assigned to the group.
Otherwise, it should show a warning indicating tickets are not available for the group.
Program terminates when all tickets are sold and no more seats are available.

\subsection*{Solution}

\begin{enumerate}
\item Class \texttt{Theater.java}
\lstset{language=java}
\begin{lstlisting}
public class Theater {
	// First, let's define attributes of the Theater
	// We use private access modifier to perform encapsulation
	// Number of available seats
	private static int availableSeats;
	// State of seats of theater: true if available, false if already sold
	private static boolean[][] seats = new boolean[5][10];
	// Number of available seats in each row
	private static int[] availableSeatsInRow = new int[seats.length];
	// Now, it's time for Methods
	// This method sets all seats to false and initializes available seats
	public static void initialize() {
		for (int i = 0; i < seats.length; i++) {
			for (int j = 0; j < seats[i].length; j++) {
				seats[i][j] = false;
			}
		}
		for (int i = 0; i < seats.length; i++) {
			availableSeatsInRow[i] = seats[0].length;
		}
		availableSeats = seats.length * seats[0].length;
	}
	// A public method that is called to sell tickets to 'num' people
	public static boolean sellTicket(int num) {
		for (int row = 0; row < seats.length; row++) {
			if (sellTicket(num, row)) {
				return true;
			}
		}
		return false;
	}
	// Let's define a private method to see if we can sell tickets for 'num' people from row 'row'
	private static boolean sellTicket(int num, int row) {
		// first check if 'num' seats are available for row 'row'
		if (num <= availableSeatsInRow[row]) {
			int i = 0;
			// skip those seats that are already sold
			while (seats[row][i]) {
				i++;
			}
			// sell 'num' rows from this row
			for (int j = 0; j < num; j++) {
				seats[row][i+j] = true;
				availableSeats --;
				availableSeatsInRow[row] --;
				System.out.printf("Sold seat %d of row %d\n", i+j+1, row+1);
			}
			return true;
		}
		else {
			return false;
		}
	}
	// An accessor to get available seats
	public static int getAvailableSeats() {
		return availableSeats;
	}
	// As we have only one theater and we don't want to allow instantiation for this class, not only should we avoid developing constructors, we must only override the default constructor with private modifer
	private Theater() {};
}
\end{lstlisting}
\item Class \texttt{TicketSale.java}
\lstset{language=java}
\begin{lstlisting}
import java.util.Scanner;
public class TicketSale {
	public static void main(String[] args) {
		// First empty the theater
		Theater.initialize();
		Scanner input = new Scanner(System.in);
		// Execute loop until all seats are sold
		while (Theater.getAvailableSeats() > 0) {
			System.out.println(Theater.getAvailableSeats()+" seats still available.");
			System.out.print("Number of tickets to print? ");
			int num = input.nextInt();
			// Call Theater.sellTicket(num) method which returns true if tickets can be sold for the group and returns false if not
			System.out.println(Theater.sellTicket(num) ? "" : "Tickets not available for group of "+num+".\n");
		}
		System.out.println("All seats sold out!");
		input.close();
	}
}
\end{lstlisting}
\end{enumerate}

\end{document}


\documentclass{article}

%%%%%% Include Packages %%%%%%
\usepackage{sectsty}
\usepackage{amsmath,amsfonts,amsthm,amssymb}
\usepackage{fancyhdr}
\usepackage{lastpage}
\usepackage{setspace}
\usepackage{graphicx}
\usepackage{array}

%%%%%% Formatting Modifications %%%%%%

\usepackage[margin=2.5cm]{geometry} %% Set margins
\sectionfont{\sectionrule{0pt}{0pt}{-8pt}{0.8pt}} %% Underscore section headers
\setstretch{1.2} %% Set 1.2 spacing

%%%%%% Set Homework Variables %%%%%%

\newcommand{\hwkNum}{8}
\newcommand{\hwkAuthors}{Ben Drucker}

%%%%%% Set Header/Footer %%%%%%

\pagestyle{fancy}
\lhead{\hwkAuthors}
\rhead{Homework \#\hwkNum}
\rfoot{\textit{\footnotesize{\thepage /\pageref{LastPage}}}}
\cfoot{}
\renewcommand\headrulewidth{0.4pt}
\renewcommand\footrulewidth{0.4pt}

%%%%%% Document %%%%%%

\begin{document}

\title{Homework \#\hwkNum}
\author{\hwkAuthors}
\date{}

\maketitle

%%%%%% Begin Content %%%%%%

\section*{5.5}
	\subsection*{74}
		$\mu_X = 50*.7 = 35; \sigma_X^2 = 50*.7*.3 = 10.5\\
		\mu_Y = 50*.6 = 30; \sigma_Y^2 = 50*.6*.4 = 12 \\
		\mu_{X-Y} = 35 - 30 =5; \sigma_{X-Y}^2 = 10.5+12 = 22.5\\
		P(-5 < X < 5) \approxeq P \left ( \frac{-10}{\sqrt {22.5}} < Z < \frac{0}{\sqrt{22.5}} \right ) = .483$

\section*{5 (Supplementary)}
	\subsection*{76}
		No, only if either $\sigma$ is 0. When taking the percentile of sums, there will be a $\sqrt{\sigma_1^2 + \sigma_2^2}$ term. In order for this to equal the $\sigma_1 + \sigma_2$ term from the sum of the percentiles, at least one $\sigma$ would need to be 0. It would also hold true at $ Z=0$, the center of the distribution.
	\subsection*{88}
		\begin{align*}
			E \left [(X+Y-t)^2 \right ] &= \int_0^1 \int_0^1 (x+y-t)^2 * f(x,y)dxdy\\
			\frac{dE \left [(X+Y-t)^2 \right ]}{dt} = 0 &= -2 \int_0^1 \int_0^1 2(x+y-t)f(x,y)	\\ \\
			\int_0^1 \int_0^1 tf(x,y)dxdy &=t \\
			&= \int_0^1 \int_0^1 (x+y)f(x,y)dxdy = E(X+Y) = 1.1\overline{6}
		\end{align*}
	\subsection*{96}
		Tried, couldn't answer it.
\section*{6.1}
	\subsection*{8}
		\subsubsection*{a)}
			$\hat{p} = \frac{12}{80} = .15$
		\subsubsection*{b)}
			P(system works) = $\hat{p}^2 = \left ( \frac{80-12}{80} \right)^2 = \frac{289}{400} $
	\subsection*{10}
		\subsubsection*{a)}
			$E(\overline{X}^2 = Var \overline{X} + [E(\overline{X})]^2 = \frac{\sigma^2}{n} + \mu^2.$ The bias is $\frac{\sigma^2}{n}$.
		\subsubsection*{b)}
			$E(\overline{X}^2 -kS^2) = E(\overline{X}^2) -kE(S^2) = \frac{\sigma^2}{n} + \mu^2 -k\sigma^2.$ The estimator is unbiased where $ k = \frac{1}{n}.$
	\subsection*{16}
		\subsubsection*{a)}
			$E[\delta \overline{X} + \overline{Y}(1-\delta)] = \delta E(\overline{X} + (1-\delta)E(\overline{Y}) = \delta \mu + \mu(1-\delta) = \mu $
		\subsubsection*{b)}
			$Var[\delta \overline{X} + (1-\delta)\overline{Y}] = \delta^2 * Var(\overline{X}) + (1- \delta)^2 * Var(\overline{Y}) = \frac{\delta^2 \sigma^2}{m} + \frac{4(1-\delta)^2 \sigma^2}{n} = F \\
			\frac{dF}{d \delta} = 0 = \frac{2 \delta \sigma ^2}{m} + \frac{8(1-\delta)\sigma^2}{n} \Rightarrow \delta = \frac{4m}{4m + n} $
\section*{6.2}
	\subsection*{20}
		\subsubsection*{a)}
		$L = \ln \left [\left(\!
    \begin{array}{c}
      n \\
      x
    \end{array}
  \!\right)
 p^x(1-p)^{n-x} \right ] = \ln \left(\!
    \begin{array}{c}
      n \\
      x
    \end{array}
  \!\right) + x\ln p +\ln(1-p)(n-x) \\
\frac{dL}{dp} = 0 = \frac{x}{p} - \frac{n-x}{1-p} \Rightarrow
\hat{p} = \frac{x}{n}\\$
Given $n=20, x=3: \hat{p}  = \frac{3}{20}$.
\subsubsection*{b)}
	Yes. $E(\hat{p}) = E \left ( \frac{x}{n} \right ) = \frac{E(X)}{n} = \frac{np}{p} = p.$
\subsubsection*{c)}
	$(1-p)^5 = \left ( 1- \frac{3}{20} \right ) ^5 \approxeq .44371$
	\subsection*{22}
		\subsubsection*{a)}
			$E(X) = \int_0^1 f(x; \theta) dx= \frac{\theta + 1}{\theta +2} \\
			\overline{X} = \frac{\hat{\theta} + 1}{\hat{\theta} + 2} \Rightarrow \hat{\theta} = \frac{1}{1-\overline{X}} -2 = \frac{1}{1-.8} -2 = 3$
		\subsubsection*{b)}
			??

%%%%%% End Content %%%%%%
\end{document}

Spring 2013/STAT W1211 - Statistics/Homework/Homework 8/Homework 8.tex