\documentclass{beamer}


\usepackage{verbatim}

\usecolortheme{seagull}

\usepackage{pstricks,pst-node,pst-tree,amscd,amsfonts,verbatim,geometry,bbm}
\usepackage{fancyvrb,fancybox}
\usepackage{color}
\usepackage{xcolor}
\usepackage{colortbl}
\usepackage{graphicx}
%\RequirePackage{etex}
%\usepackage{etex}
%\usepackage{xypic}
\usepackage[all,color]{xy}
\usepackage{myxfig}

\usepackage{natbib}

\usepackage{tkz-graph}
\usepackage{tikz}
\usetikzlibrary{arrows,automata}
\usetikzlibrary{graphs,arrows.meta}
\usetikzlibrary{positioning}

\usepackage{caption}
\captionsetup[figure]{labelfont={it},textfont={color=black,it},labelformat={default},labelsep=period,name={}}


\usepackage[latin1]{inputenc}
\usepackage{undertilde}
\usepackage{bm}
\usepackage{amssymb}
\usepackage{amsmath}
%\usepackage{lastpage}
\usepackage{rotating}
\usepackage{multirow}
\usepackage{graphicx}
\usepackage{bbm}
\usepackage{bbold}

\usepackage{upgreek}

\usepackage{fancybox}
\usepackage{fancyhdr}
\usepackage{amsfonts}

\usepackage{dsfont}

%\usepackage{arydshln}

\usepackage{listings}
\usepackage{courier}
\lstloadlanguages{R}


\usepackage[scaled=.85]{DejaVuSerifCondensed}
\usepackage[T1]{fontenc}

\usefonttheme{serif}


\DeclareFontFamily{OT1}{pzc}{}
\DeclareFontShape{OT1}{pzc}{m}{it}{<-> s * [1.30] pzcmi7t}{}
\DeclareMathAlphabet{\mathpzc}{OT1}{pzc}{m}{it}

%\theoremstyle{myNote}
%\newtheorem{myNote}{Note}

\usepackage{mathtools}

\usepackage{bookmark}

\usepackage{amsthm}
\usepackage{ulem}
\usepackage{soul}

\usepackage{hanging}
\setbeamertemplate{footnote}{\hangpara{2em}{1}\makebox[2em][l]{\insertfootnotemark}\footnotesize\insertfootnotetext\par}
\addtobeamertemplate{footnote}{}{\vspace{5ex}}

\hypersetup{%
  unicode   =false,    % non-Latin characters in Acrobat’s bookmarks
  pdftoolbar=true,    % show Acrobat’s toolbar?
  pdfmenubar=true,    % show Acrobat’s menu?
  %bookmarks=false,
  bookmarksopen=false
}

\usepackage{calc}
\newsavebox\CBox
\newcommand\hcancel[2][0.25pt]{%
  \ifmmode\sbox\CBox{$#2$}\else\sbox\CBox{#2}\fi%
  \makebox[0pt][l]{\usebox\CBox}%
  \rule[0.5\ht\CBox-#1/2]{\wd\CBox}{#1}}

\newcommand{\msout}[1]{\text{\sout{\ensuremath{#1}}}}

\makeatletter
\newcommand*{\shifttext}[2]{%
  \settowidth{\@tempdima}{#2}%
  \makebox[\@tempdima]{\hspace*{#1}#2}%
}
\makeatother

\newcommand\oldmyzeta[1]{{\textcolor{red}{\protect\mathpzc{z}_{#1}} \shifttext{-10pt}{\raisebox{0.1ex}{\tiny{\sim}}}}}

\newcommand\firstmyzeta[1]{\textcolor{black}{{\protect\mathpzc{z}_{#1}}}}

\newcommand\myzeta[1]{{\textcolor{mcgillred}{{\protect\textsf{z}_{#1}}}}}
\newcommand\tildemyzeta[1]{\textcolor{mcgillred}{{\protect\widetilde{\textsf{z}}_{#1}}}}

\theoremstyle{plain}
\newtheorem{thm}{Theorem} % reset theorem numbering for each chapter

\theoremstyle{definition}
\newtheorem{defn}[thm]{Definition} % definition numbers are dependent on theorem numbers
\newtheorem{Note}{Note} % same for example numbers

\setbeamertemplate{theorems}[numbered]


\def\U{\mathcal{U}}
\def\u{\upsilon}

\def\Ind{\mathds{1}}

\def\transpose{\top}
\def\Xvec{{\skew0\bm{X}}}
\def\Xveca{{\skew0\bm{X}}_1}
\def\Xvecb{{\skew0\bm{X}}_2}

\def\Yvec{{\skew0\bm{Y}}}
\def\xvec{{\skew0\bm{x}}}
\def\xveca{{\skew0\bm{x}}_1}
\def\xvecb{{\skew0\bm{x}}_2}

\def\mvec{{\skew0\bm{m}}}
\def\muvec{{\skew0\bm{\mu}}}

\def\cvec{{\skew0\mathbf{c}}}

\def\Xbar{\overline{X}}
\def\xbar{\overline{x}}
\def\ybar{\overline{y}}
\def\yhat{\widehat{y}}
\def\betahat{\widehat{\beta}}
\def\betavec{\utilde{\beta}}
\def\betahatvec{\skew3\widehat{\utilde{\beta}}}
\def\sigmahat{\widehat{\sigma}}
\def\ehat{\widehat{e}}
\def\zhat{\widehat{z}}
\def\nhat{\widehat{n}}

\def\xbarA{\overline{x}_A}
\def\xbarB{\overline{x}_B}

\def\calR{\mathcal{R}}
\def\calS{\mathcal{S}}
\def\calE{{\mathcal{S}_{e}}}
\def\calB{\mathcal{B}}
\def\calU{\mathcal{U}}
\def\calI{\mathcal{I}}
\def\B{\mathcal{B}}

\def\Qbb{\mathbb{Q}}
\def\Pbb{\mathbb{P}}


\def\E{\mathbb{E}}
\def\Ehat{\widehat{\mathbbm{E}}}
\def\Var{\mathbb{V}ar}
\def\Cov{\mathbb{C}ov}
\def\Corr{\mathbb{C}orr}

\def\bhatint{\widehat{\beta}_0}
\def\bhatsl{\widehat{\beta}_1}

\def\d{\:\textrm{d}}

\def\ps{{\textsf{e}}}
\def\bs{{\textsf{b}}}

\def\bX{\bm{X}}
\def\Ident{\mathbf{I}}

\def\One{\mathbf{1}}
\def\Zero{\mathbf{0}}

\def\bY{\mathbf{Y}}
\def\bm{\mathbf{m}}
\def\bM{\mathbf{M}}

\newcommand\xbarBi[1]{\overline{x^{\text{\tiny{(B)}}}_{#1}}}
\newcommand\xbarib[1]{\overline{x^{\text{\tiny{(B)}}}_{#1}}}


\def\Fstat{\frac{(SSE_R - SSE_C)/(k-g)}{SSE_C/(n-k-1)}}

\def\approxsim{\sim \! \! \! : \;}
\def\hsp{\vspace{0.1 in}}
\def\fsp{\vspace{0.2 in}}

%\def\dfrac#1#2{{\displaystyle {#1 #2}}}%
\def\dint{\mathop{\displaystyle \int}}%
\def\dsum{\mathop{\displaystyle \sum}}%

\newcommand\betaZ{$\beta_{1}$}
\newcommand\betaA[1]{$\beta_{#1}^{(A)}$}
\newcommand\betaB[1]{$\beta_{#1}^{(B)}$}
\newcommand\gammaAB[1]{$\gamma_{#1}^{(AB)}$}

\def\SST{\mathit{SST}}
\def\MST{\mathit{MST}}
\def\SSE{\mathit{SSE}}
\def\MSE{\mathit{MSE}}
\def\SSB{\mathit{SSB}}
\def\MSB{\mathit{MSB}}
\def\SSI{\mathit{SSI}}
\def\MSI{\mathit{MSI}}
\def\SS{\mathit{SS}}

\def\Ztilde{{\widetilde Z}}
\def\ztilde{{\widetilde z}}

\def\bmu{\boldsymbol\mu}
\newcounter{Lecture}

\def\calA{\mathcal{A}}
\renewcommand{\thelecture}{\arabic{lecture}}

\newcommand\xbari[1]{\overline{x}_{#1}}

\newcommand\subsectnum[1]{\textbf{\arabic{section}.\arabic{subsection}} \textbf{\uppercase{#1}}}

\newcommand\textsclarge[1]{\fontshape{sc}\fontsize{14}{15} \selectfont{#1}}

\renewcommand\emph[1]{\textcolor{mcgillred}{\textit{#1}}}

\def\Exp{\mathcal{E}}
\def\Ex{\mathcal{E}}
\def\Exzero{\mathcal{E}_0}
\def\Obs{\mathcal{O}}
\def\Ob{\mathcal{O}}

\def\Ell{\mathcal{L}}

\usepackage{tikz}
\newcommand*\circled[1]{\tikz[baseline=(char.base)]{
            \node[shape=circle,draw,inner sep=1pt] (char) {#1};}}

\def\WideSpacing{\itemsep=2.0ex\topsep=0.5ex\partopsep=0.0ex\parskip=0.0ex\parsep=0.0ex}

\makeatletter
\let\orig@Enumerate =\enumerate
\newenvironment{enumerateWide}{\orig@Enumerate\WideSpacing}{\endlist}
\makeatother

\definecolor{midgray}{rgb}{0.75,0.75,0.75}
\definecolor{lightgray}{rgb}{0.85,0.85,0.85}
\definecolor{darkgray}{rgb}{0.654,0.724,0.795}
\definecolor{lightdarkgray}{rgb}{0.727,0.805,0.883}
\definecolor{purpleblue}{rgb}{0.50,0.50,1.00}
\definecolor{lightblue}{rgb}{0.90,0.90,1.00}
\definecolor{kugreen}{RGB}{50,93,61}
\definecolor{kugreenlys}{RGB}{132,158,139}
\definecolor{kugreenlyslys}{RGB}{173,190,177}
\definecolor{kugreenlyslyslys}{RGB}{214,223,216}

\definecolor{mcgillred}{rgb}{.926,0.105,0.184}
\definecolor{mcgillreddark}{rgb}{0.617,0.035,0.094}
\definecolor{mcgillredlight}{rgb}{0.926,0.153,0.241}
\definecolor{verylightred}{rgb}{1,0.95,0.95}
\definecolor{darkgreen}{rgb}{0.008, 0.294, 0.188}
\definecolor{lightgreen}{rgb}{0.75,1.0,0.75}
\definecolor{verylightgreen}{rgb}{0.90,1.0,0.90}
\definecolor{darkblue}{rgb}{0.00, 0.00, 0.444}
\definecolor{lightblue}{rgb}{0.933,0.933,1.00}
\definecolor{psyc}{rgb}{0.87, 0.0, 1.0}
\definecolor{mayablue}{rgb}{0.45, 0.76, 0.98}
\definecolor{paleblue}{rgb}{0.69, 0.93, 0.93}
\definecolor{spirodiscoball}{rgb}{0.06, 0.75, 0.99}
\definecolor{lightcyan}{rgb}{0.88, 1.0, 1.0}
\definecolor{frenchblue}{rgb}{0.0, 0.45, 0.73}
\definecolor{bubbles}{rgb}{0.91, 1.0, 1.0}
\definecolor{azurewm}{rgb}{0.94, 1.0, 1.0}
\definecolor{airforceblue}{rgb}{0.36, 0.54, 0.66}
\definecolor{darkmidnightblue}{rgb}{0.0, 0.2, 0.4}
\definecolor{darkpastelblue}{rgb}{0.47, 0.62, 0.8}
\definecolor{bleudefrance}{rgb}{0.19, 0.55, 0.91}
\definecolor{babyblue}{rgb}{0.54, 0.81, 0.94}

\setbeamercolor{background}{bg=red!15!white}

\setbeamercovered{transparent}

\setbeamercolor{title in sidebar}{fg=lightgray}

\setbeamercolor{sidebar}{bg=lightgray,fg=purpleblue}

\setbeamercolor{author in sidebar}{fg=lightgray}
\setbeamercolor{section in sidebar}{fg=white,bg=mcgillred}
\setbeamercolor{title}{fg=white,bg=mcgillred}
\setbeamercolor{author}{use=structure,fg=black,bg=darkgray}
\setbeamercolor{part name}{fg=black,bg=blue!30!white}
\setbeamercolor{institute}{use=structure,fg=black,bg=lightdarkgray}
\setbeamercolor{frametitle}{fg=white,bg=mcgillred}
\setbeamercolor{subsection in sidebar}{fg=purpleblue}
\setbeamercolor{block title}{use=structure,fg=black,bg=blue!30!white}
\setbeamercolor{block body}{use=structure,fg=black,bg=blue!20!white}


\setbeamertemplate{navigation symbols}{}


\setbeamercovered{transparent}
\mode<presentation>

\setbeamertemplate{part page}
{
  \begin{centering}
    %\begin{beamercolorbox}[sep=16pt,center]{author}
    %  \usebeamerfont{part title}\partname~\insertpartnumber \par
    %\end{beamercolorbox}
    \vskip1em\par
    \begin{beamercolorbox}[sep=16pt,center]{institute}
      \usebeamerfont{part title} \insertpart\par
    \end{beamercolorbox}
  \end{centering}
}


\makeatletter
\AtBeginPart{%
  \beamer@tocsectionnumber=0\relax
  \setcounter{section}{0}
  \numberwithin{section}{part}
    {%  start a group to keep the template change local
       \setbeamertemplate{background canvas}{%
            \color{white}\rule{\paperwidth}{\paperheight}%
        }%
        \setbeamercolor{frametitle}{fg=white,bg=white}
        \setbeamertemplate{footline}{
\leavevmode%
  \hbox{\begin{beamercolorbox}[wd=.5\paperwidth,ht=2.5ex,dp=1.125ex,leftskip=.3cm plus1fill,rightskip=.3cm]{author in head/foot}%
    \usebeamerfont{author in head/foot}
  \end{beamercolorbox}%
  \begin{beamercolorbox}[wd=.5\paperwidth,ht=2.5ex,dp=1.125ex,leftskip=.3cm,rightskip=.3cm plus1fil]{title in head/foot}%
    \usebeamerfont{title in head/foot}\hfill\insertpagenumber
  \end{beamercolorbox}}%
  \vskip0pt%
        }
        %\addtocounter{framenumber}{-1}
        \begin{frame}[noframenumbering,c]{\partpage}\end{frame}%
    }%  end group
}
\makeatother

\setbeamercolor{author in head/foot}{bg=white, fg=mcgillred}
\setbeamercolor{title in head/foot}{bg=white, fg=mcgillred}

\setbeamertemplate{footline}
{%
%\rule{\paperwidth}{0.025cm}
  \leavevmode%
  \hbox{\begin{beamercolorbox}[left, wd=.5\paperwidth,ht=2.5ex,dp=1.125ex,leftskip=.3cm]{title in head/foot}%
    \usebeamerfont{author in head/foot}\insertpartnumber.\insertsectionnumber: \insertsection
  \end{beamercolorbox}%
  \begin{beamercolorbox}[wd=.5\paperwidth,ht=2.5ex,dp=1.125ex,leftskip=.3cm,rightskip=.3cm plus1fil]{title in head/foot}%
    \usebeamerfont{title in head/foot}\hfill\insertpagenumber
  \end{beamercolorbox}}%
  \vskip0pt%
}

  %\usecolortheme[named=kugreen]{structure}
  %\useinnertheme{circles}
  %\setbeamercovered{transparent}
  %\setbeamertemplate{blocks}[rounded][shadow=true]
    \setbeamertemplate{blocks}[default]


\setbeamerfont{itemize/enumerate subbody}{size=\footnotesize}
\setbeamertemplate{itemize items}[circle]
\newenvironment<>{Ex}[1]{%
  \begin{actionenv}#2%
      \def\insertblocktitle{Example: #1}%
      \par%
      \mode<presentation>{%
       \setbeamercolor{block title}{use=structure,fg=darkmidnightblue,bg=babyblue}
       \setbeamercolor{block body}{use=structure,fg=black,bg=bubbles}
       \setbeamertemplate{itemize item}{\scriptsize\raise1.25pt\hbox{\donotcoloroutermaths$\bullet$}}
     }%
      \usebeamertemplate{block begin}\justifying}
    {\par\usebeamertemplate{block end}\end{actionenv}}

\newenvironment<>{Thm}[1]{%
  \begin{actionenv}#2%
      \def\insertblocktitle{Theorem: #1}%
      \par%
      \mode<presentation>{%
       \setbeamercolor{block title}{use=structure,fg=white,bg=darkgreen}
       \setbeamercolor{block body}{use=structure,fg=black,bg=lightgreen}
       \setbeamercolor{itemize item}{fg=orange!20!black}
       \setbeamertemplate{itemize item}[circle]
     }%
      \usebeamertemplate{block begin}\justifying}
    {\par\usebeamertemplate{block end}\end{actionenv}}


\newenvironment<>{Nt}[1]{%
  \begin{actionenv}#2%
      \def\insertblocktitle{Note}%
      \par%
      \mode<presentation>{%
       \setbeamercolor{block title}{use=structure,fg=white,bg=darkblue}
       \setbeamercolor{block body}{use=structure,fg=black,bg=azurewm}
       \setbeamercolor{itemize item}{fg=orange!20!black}
       \setbeamertemplate{itemize item}[circle]
     }%
      \usebeamertemplate{block begin}\justifying}
    {\par\usebeamertemplate{block end}\end{actionenv}}

    \newcounter{myNote}
\newcommand{\myNote}{\arabic{myNote}}

\setcounter{myNote}{1}

\renewcommand*{\thefootnote}{[\arabic{footnote}]}

\renewenvironment<>{Note}{%
  \begin{actionenv}%
      \def\insertblocktitle{Note \myNote.}%
      \par%
      \mode<presentation>{%
       \setbeamercolor{block title}{use=structure,fg=white,bg=darkblue}
       \setbeamercolor{block body}{use=structure,fg=black,bg=lightblue}
       \setbeamercolor{itemize item}{fg=orange!20!black}
       \setbeamertemplate{itemize item}[circle]
     }%
      \usebeamertemplate{block begin}\addtocounter{myNote}{1}\justifying}
    {\par\usebeamertemplate{block end}\end{actionenv}}


\date{ }
%
% The following info should normally be given in you main file:
%

\usepackage{tikz}
\newcommand{\topline}{%
  \tikz[remember picture,overlay] {%
    \draw[midgray] ([yshift=-1cm]current page.north west)
             -- ([yshift=-1cm,xshift=\paperwidth]current page.north west);}}


\setbeamertemplate{frametitle}{%
  \nointerlineskip
    \begin{beamercolorbox}[sep=0.3cm,ht=1.8em,wd=\paperwidth,rightskip=0cm]{frametitle}%
      \usebeamerfont{frametitle}\usebeamercolor[fg]{frametitle}
      \vbox{}\vskip-2ex%
        \strut\insertframetitle\strut
        \vskip-1.2ex%
    \end{beamercolorbox}%
}
\newcommand\mypart[1]{#1}


%\setbeamertemplate{frametitle continuation}[from %second][(\lowercase{\insertcontinuationcountroman})]

\setbeamertemplate{frametitle continuation}[from second][]

\setbeamertemplate{section in toc}{\insertpartnumber.\inserttocsectionnumber\hspace*{1em}\inserttocsection}

\title{MATH 559}
\author{Dr David A. Stephens}
\institute{
  Department of Mathematics \& Statistics\\
 McGill University\\
 Montreal, QC, Canada.

  \vspace{0.1 in}

  \texttt{david.stephens@mcgill.ca}\\
  \texttt{\texttt{www.math.mcgill.ca/dstephens/SISCER2020/}}
}

\titlegraphic{\includegraphics[width=1.93cm,height=2cm]{McGillLogo}}

\setbeamertemplate{itemize item}{\scriptsize\raise1.25pt\hbox{\donotcoloroutermaths$\bullet$}}
\setbeamertemplate{itemize subitem}{\tiny\raise1.25pt\hbox{\donotcoloroutermaths$\blacktriangleright$}}

\usepackage{etoolbox}
%\usepackage{setspace}
%\addtocontents{toc}{\protect\setstretch{0.9}}

\usepackage{ragged2e}
\apptocmd{\frame}{}{\justifying}{} % Allow optional arguments after frame.

%\usepackage[bookmarks=true]{hyperref}

\lstset{basicstyle=\ttfamily\tiny, numbers=left,
numberstyle=\tiny, stepnumber=1, numbersep=5pt}


\begin{document}

%\part{NHANES Example}

\setbeamercolor{author in head/foot}{bg=white, fg=mcgillred}
\setbeamercolor{title in head/foot}{bg=white, fg=mcgillred}


{
\setbeamertemplate{footline}
{%
  \leavevmode%
  \hbox{\begin{beamercolorbox}[wd=.5\paperwidth,ht=2.5ex,dp=1.125ex,leftskip=.3cm plus1fill,rightskip=.3cm]{author in head/foot}%
    \usebeamerfont{author in head/foot}
  \end{beamercolorbox}%
  \begin{beamercolorbox}[wd=.5\paperwidth,ht=2.5ex,dp=1.125ex,leftskip=.3cm,rightskip=.3cm plus1fil]{title in head/foot}%
    \usebeamerfont{title in head/foot}\hfill\insertpagenumber
  \end{beamercolorbox}}%
  \vskip0pt%
}

<<setup, cache=FALSE, echo=FALSE>>=
library(knitr)
# global chunk options
opts_chunk$set(cache=TRUE, autodep=TRUE, size = "tiny",fig.align='center')
options(scipen=5)
options(repos=c(CRAN="https://cloud.r-project.org/"))
@

%\frame{\titlepage}

\begin{frame}[fragile,allowframebreaks]\frametitle{Random effects model}

Suppose that
\[
Y_{ij} = \theta_i + \epsilon_{ij}
\]
for $i=1,\ldots,M$, $j=1,\ldots,n_i$, where
\[
\epsilon_{ij} \sim Normal(0,\sigma^2)
\]
are independent residual errors.  The unknown parameters are
\[
\theta_1,\theta_2,\ldots,\theta_M, \sigma^2
\]
where the $\theta_i$ are \emph{subgroup means}, and where
\[
Y_{ij} \sim Normal(\theta_i,\sigma^2)
\]
are conditionally independent.

\framebreak

This model is known as a \emph{one-way layout}

\begin{itemize}
  \item a form of Normal linear model
  \item it is the basis of one-way ANOVA, where a classical hypothesis test of the null hypothesis
      \[
      H_0 : \theta_1 = \theta_2 = \cdots = \theta_M
      \]
      is carried out.
  \item for a Bayesian analysis, we may use the previously derived Normal linear theory; we might assume that, given $\sigma^2$
      \[
      \theta = (\theta_1,\theta_2,\ldots,\theta_M)^\top \sim Normal_M(\bm_0,\bM_0)
      \]
      and so on.
      
\end{itemize}
\framebreak

Suppose instead that for $i=1,\ldots,M$
\[
\theta_i \sim Normal(\phi,\tau^2)
\]
are independent. We have a \emph{hierarchical model}, and might assume that
\begin{itemize}

\item $\phi|\tau^2 \sim Normal(0,\tau^2/\lambda_0)$,

\item $\tau^2 \sim InverseGamma(g_0,h_0)$

\end{itemize}
to complete the model.  The unknown parameters are now
\[
\theta_1,\theta_2,\ldots,\theta_M, \sigma^2, \phi, \tau^2
\]
and we are treating the $\theta_i$ as \emph{random effects}.

\framebreak
The values
\[
(\theta_1,\theta_2,\ldots,\theta_M)
\]
are assumed to be drawn from some second stage \emph{population}.

\medskip

This encourages the $\theta_i$ to `shrink' towards each other.

\framebreak

If $\theta = (\theta_1,\theta_2,\ldots,\theta_M)$, the posterior is
\[
\pi_n(\theta, \sigma^2, \phi, \tau^2) \propto \Ell_n(\theta, \sigma^2) \pi_0(\theta|\phi,\tau^2) \pi_0(\sigma^2) \pi_0(\phi|\tau^2) \pi_0(\tau^2)
\]
and is not analytically tractable.  

\medskip

We can instead use MCMC via the Gibbs sampler.

\framebreak

We need the \emph{full conditional distributions}

\begin{itemize}
  \item $\theta$:  we have by conditional independence
  \[
  \pi_n(\theta|\sigma^2,\phi,\tau^2) \equiv \prod_{i=1}^M \pi_{n_i}(\theta_i|\sigma^2,\phi,\tau^2)
  \]
  where
  \[
  \pi_{n_i}(\theta_i|\sigma^2,\phi,\tau^2) \propto \Ell_{n_i}(\theta_i,\sigma^2) \pi_0(\theta_i|\sigma^2,\phi,\tau^2). 
  \]
  Each of the $M$ full conditionals is univariate Normal.

\framebreak

\item $\sigma^2$: we have
\[
\pi_n(\sigma^2|\theta,\phi,\tau^2) \propto \Ell_{n}(\theta,\sigma^2) \pi_0(\sigma^2)  
\]
which is an Inverse Gamma distribution.  

\medskip

Note that the $\theta_i$ are treated as \emph{known} in this calculation.

\framebreak

\item $\phi$: we have
\[
\pi_n(\phi|\theta,\sigma^2,\tau^2) \propto \prod_{i=1}^M \pi_{0}(\theta_i|\phi,\tau^2) \pi_0(\phi|\tau^2)
\]
which is a Normal distribution.

\framebreak

\item $\phi$: we have
\[
\pi_n(\tau^2|\theta,\sigma^2,\phi) \propto \prod_{i=1}^M \pi_{0}(\theta_i|\phi,\tau^2) \pi_0(\phi|\tau^2) \pi_0(\tau^2)
\]
which is an Inverse Gamma distribution.  
\end{itemize}

\framebreak

Note that we may \emph{reparameterize} the model
\[
Y_{ij} = \phi + \delta_i + \epsilon_{ij}
\]
where
\[
\theta_i= \phi + \delta_i
\]
so that
\[
\pi_0(\delta_i|\phi,\tau^2) \equiv \pi_0(\delta_i|\tau^2) = Normal(0,\tau^2)
\]
are conditionally independent and identically distributed.

\framebreak


\emph{Which is the better parameterization for MCMC?}

\medskip

This depends on several factors:

\begin{itemize}
  \item sample sizes
  
  \item prior specification
  
  \item relative magnitudes of the \emph{true values} of the parameters, especially
  \[
  \sigma^2 \quad \text{and} \quad \tau^2.
  \]
  e.g.
  \begin{itemize}
    \item $\tau^2$ `large', infer $\theta_i$ directly as second stage model is not very informative
    \item $\tau^2$ `small', use $\delta_i$.
  \end{itemize}
\end{itemize}

\framebreak

\begin{figure}[!h]
\centering
\scalebox{0.65}{
\begin{forest}
  for tree={
    math content,
  },
  delay={
    where content={}{
      if level=0{}{
        content=\ldots,
        math content,
        no edge,
        fit=band,
      },
    }{
      rounded corners,
      outer color=blue!20,
      inner color=blue!15,
      minimum height=1cm,
      minimum width=1cm,
      draw,
      drop shadow,
    },
  },
  label levels,
  [, phantom
    [$\phi{,}\tau^2$, plain content, level label= $\pi_0(\phi{,}\tau^2)$
      [\theta_1{,}\sigma^2, level label= $\prod_{i=1}^M \pi_0(\theta_i{|}\phi{,}\tau^2)\pi_0(\sigma^2)$
        [y_{11},level label= $f(y_{ij}{;}\theta_i{,}\sigma^2)$]
        []
        [y_{1n_1}],
      ]
      [\theta_2{,}\sigma^2
        [y_{21}]
        []
        [y_{2n_2}]
      ]
      []
      [\theta_M{,}\sigma^2
        [y_{M1}]
        []
        [y_{Mn_M}]
      ]
    ]
  ]
\end{forest}}
\end{figure}

\framebreak

\begin{itemize}
  \item Stage 3:
  \[
  f(y_{ij};\theta_i,\sigma^2) = \left(\frac{1}{2 \pi \sigma^2} \right)^{1/2} \exp\left\{ - \frac{1}{2 \sigma^2} (y_{ij} - \theta_i)^2 \right\}
  \]
  
  \item Stage 2: 
  \begin{align*}
  \pi_0(\theta_1,\ldots,\theta_M,\sigma^2) & = \prod_{i=1}^M \left(\frac{1}{2 \pi \tau^2} \right)^{1/2}\exp\left\{ - \frac{1}{2 \tau^2} (\theta_i - \phi)^2 \right\} \\[6pt]
  & \times \frac{(b_0/2)^{a_0/2}}{\Gamma(a_0/2)} \left(\frac{1}{\sigma^2}\right)^{a_0/2+1} \exp\left\{ -\frac{b_0}{2 \sigma^2} \right\}
  \end{align*}
  
  \framebreak
  
  \item Stage 1:
  \begin{align*}
  \pi_0(\phi,\tau^2) & = \left(\frac{\lambda_0}{2 \pi \tau^2} \right)^{1/2}\exp\left\{ - \frac{\lambda_0}{2 \tau^2} \phi^2 \right\} \\[6pt]
  & \times \frac{(h_0/2)^{g_0/2}}{\Gamma(g_0/2)} \left(\frac{1}{\tau^2}\right)^{g_0/2+1} \exp\left\{ -\frac{h_0}{2 \tau^2} \right\}
  \end{align*}
\end{itemize}

\bigskip
Hyperparameters: $a_0,b_0,\lambda_0,g_0,h_0$.

\end{frame}

\begin{frame}[fragile,allowframebreaks]\frametitle{Random effects model: simulation}

<<fig.height=4.5>>=
set.seed(253)
M<-10
a0<-b0<-2; g0<-8;h0<-20
lam0<-1

ni<-rpois(M,4)
ni
n<-sum(ni)
tau<-sqrt(1/rgamma(1,g0/2,h0/2))
sig<-sqrt(1/rgamma(1,a0/2,b0/2))
phi<-rnorm(1,0,tau/sqrt(lam0))

c(sig^2,phi,tau^2)

th0<-rnorm(M,phi,tau)
th0

@

<<fig.height=4.5>>=
Y<-list()
for(i in 1:M){Y[[i]]<-rnorm(ni[i],th0[i],sig)}
(Ybar<-unlist(lapply(Y,mean)))
par(mar=c(4,4,2,2))
boxplot(Y)
@

<<>>=
#MCMC
nburn<-100
nthin<-10
nsamp<-2000
nits<-nburn+nthin*nsamp

#Initial values
old.th<-Ybar
old.ssq<-rep(0,M)
for(i in 1:M){
    old.ssq[i]<-sum((Y[[i]]-Ybar[i])^2)
}
old.sigsq<-sum(old.ssq)/(n-M)
old.phi<-mean(old.th)
old.tausq<-sum((old.th-old.phi)^2)/(M-1)
old.th
c(old.sigsq,old.phi,old.tausq)

@

\framebreak
<<>>=
#Gibbs sampler
ico<-0;th.samp<-matrix(0,nrow=nsamp,ncol=M)
sig.samp<-phi.samp<-tau.samp<-rep(0,nsamp)
for(iter in 1:nits){
    #Update th
    mval<-(ni*Ybar/old.sigsq+old.phi/old.tausq)/(ni/old.sigsq+1/old.tausq)
    Mval<-sqrt(1/(ni/old.sigsq+1/old.tausq))
    old.th<-rnorm(M,mval,Mval)   
    #Update phi
    mval<-(sum(old.th)/old.tausq)/(M/old.tausq+lam0/old.tausq)
    Mval<-sqrt(1/(M/old.tausq+lam0/old.tausq))
    old.phi<-rnorm(1,mval,Mval)
    #Update sigma^2
    old.ssq<-rep(0,M)
    for(i in 1:M){
        old.ssq[i]<-sum((Y[[i]]-old.th[i])^2)
    }    
    an<-a0+n; bn<-b0+sum(old.ssq)
    old.sigsq<-1/rgamma(1,an/2,bn/2)
    #Update tau^2
    gn<-g0+M+1; hn<-h0+sum((old.th-old.phi)^2)+lam0*old.phi^2
    old.tausq<-1/rgamma(1,gn/2,hn/2)
    if(iter > nburn & iter %% nthin ==0){
        ico<-ico+1
        th.samp[ico,]<-old.th
        sig.samp[ico]<-old.sigsq
        phi.samp[ico]<-old.phi
        tau.samp[ico]<-old.tausq
    }
}
@

<<fig.height=4.25>>=
par(mar=c(4,4,1,2));plot(th.samp[,1],type='l',ylab=expression(theta[1]),xlab='Iteration')
@

<<fig.height=4.25>>=
par(mar=c(4,4,1,2));acf(th.samp[,1],main='')
@

<<fig.height=6, fig.width=8,out.width = "80%", out.height = "85%">>=
par(mar=c(4,4,1,2));
plot(sig.samp,tau.samp,pch=19,cex=0.6,ylab=expression(tau^2),xlab=expression(sigma^2))
@

<<fig.height=4.25>>=
par(mar=c(4,4,1,2));plot(phi.samp,type='l',ylab=expression(theta[1]),xlab='Iteration')
@

<<fig.height=4.25>>=
par(mar=c(4,4,1,2));acf(phi.samp,main='')
@

\framebreak

<<fig.width=7, fig.height=4.5, fig.align='center',size='tiny'>>=
suppressMessages(library(fields,quietly=TRUE))
par(pty='s',mar=c(4,4,2,2))
colfunc <- colorRampPalette(c("blue","lightblue","white","yellow","orange","red"))

old.param<-cbind(phi.samp,th.samp)

post.cor<-post.cor.flip<-cor(old.param)
for(i in 1:(M+1)){
    post.cor.flip[i,]<-post.cor[M-i+2,]
}
for(j in 1:(M+1)){
    post.cor.flip[,j]<-post.cor[,M-j+2]
}
image.plot(0:(M+1),0:(M+1),post.cor.flip,col=colfunc(100),zlim=range(-1,1),
           xlab='',ylab='',cex.axis=0.8,axes=FALSE)
axis(1,at=c(0:M)+0.5,labels=c(0:M))
axis(2,at=c(0:M)+0.5,labels=rev(c(0:M)))
title(expression(paste('Posterior correlation for ',phi,',',theta)))
@

\framebreak

<<fig.width=7, fig.height=4.5, fig.align='center',size='tiny'>>=
#Posterior correlation in initial parameterization
round(post.cor,2)
@
\framebreak

New parameterization:
\[
\theta_i = \phi + \delta_i
\]
so that
\[
\begin{pmatrix}
  \phi \\
  \delta_1 \\
  \delta_2 \\
  \vdots \\
  \delta_M
\end{pmatrix} = \begin{pmatrix}
                  1 & 0 & 0 & \cdots & 0 \\
                  -1 & 1 & 0 & \cdots & 0 \\
                  -1 & 0 & 1 & \cdots & 0 \\
                  \vdots & \vdots & \vdots & \ddots & \vdots \\
                  -1 & 0 & 0 & \cdots & 1 
                \end{pmatrix}
\begin{pmatrix}
  \phi \\
  \theta_1 \\
  \theta_2 \\
  \vdots \\
  \theta_M
\end{pmatrix}\]

<<fig.width=7, fig.height=4.5, fig.align='center',size='tiny'>>=
L<-matrix(0,M+1,M+1)
L[,1]<--1
diag(L)<-1

L

new.param<-t( L %*% t(old.param))

@

<<fig.width=7, fig.height=4.5, fig.align='center',size='tiny'>>=
par(pty='s',mar=c(4,4,2,2))
colfunc <- colorRampPalette(c("blue","lightblue","white","yellow","orange","red"))
post.cor<-post.cor.flip<-cor(new.param)
for(i in 1:(M+1)){
    post.cor.flip[i,]<-post.cor[M-i+2,]
}
for(j in 1:(M+1)){
    post.cor.flip[,j]<-post.cor[,M-j+2]
}
image.plot(0:(M+1),0:(M+1),post.cor.flip,col=colfunc(100),zlim=range(-1,1),
           xlab='',ylab='',cex.axis=0.8,axes=FALSE)
axis(1,at=c(0:M)+0.5,labels=c(0:M))
axis(2,at=c(0:M)+0.5,labels=rev(c(0:M)))
title(expression(paste('Posterior correlation for ',phi,',',delta)))
@

<<fig.width=7, fig.height=4.5, fig.align='center',size='tiny'>>=
#Posterior correlation in new parameterization
round(post.cor,2)
@
\end{frame}


\end{document}
