\documentclass[12pt,t]{beamer}
\usepackage{graphicx}
\setbeameroption{hide notes}
\setbeamertemplate{note page}[plain]
\usepackage{listings}

\input{../LaTeX/header.tex}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% end of header
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\title{KnitR + \LaTeX\/ $\rightarrow$ paper}
\subtitle{Tools for Reproducible Research}
\author{\href{http://kbroman.org}{Karl Broman}}
\institute{Biostatistics \& Medical Informatics, UW{\textendash}Madison}
\date{\href{http://kbroman.org}{\tt \scriptsize \color{foreground} kbroman.org}
\\[-4pt]
\href{http://github.com/kbroman}{\tt \scriptsize \color{foreground} github.com/kbroman}
\\[-4pt]
\href{https://twitter.com/kwbroman}{\tt \scriptsize \color{foreground} @kwbroman}
\\[-4pt]
{\scriptsize Course web: \href{http://kbroman.org/Tools4RR}{\tt kbroman.org/Tools4RR}}
}

\begin{document}

{
\setbeamertemplate{footline}{} % no page number here
\frame{
  \titlepage

\note{
  This lecture is about how to create reproducible manuscripts, for
  journal articles. KnitR with R Markdown is great for informal
  reports. KnitR with AsciiDoc is great for somewhat fancier
  reports. There are a number of efforts, especially with Pandoc, to
  use R Markdown for journal articles. But if you want fine control
  over the appearance of a document, it's hard to beat \LaTeX, and so
  I'm just going to focus on that.

  I can't hope to explain \LaTeX\/ properly in just this one
  lecture. My goals are to give the general gist, indicate resources
  and options, and show how to use KnitR with \LaTeX.

  I also want to discuss some more general strategies for ensuring that
  the results described in a journal article are fully reproducible.
}
} }

\begin{frame}[c,fragile]{\LaTeX}

\begin{lstlisting}
\documentclass[12pt]{article}

\usepackage{graphicx}

\title{An example document}
\author{Karl Broman}

\begin{document}

\maketitle
\thispagestyle{empty}

\section{A section}

This is a simple example of a \LaTeX\/ document for an article.
Here's some in-line math: $y = \beta_0 + \beta_1 x + \epsilon$.

And here's a display equation:

$$ \hat{\beta} = (X'X)^{-1} X'y $$

\end{document}
\end{lstlisting}

\note{
  \LaTeX\/ is like html or Markdown: plain text with special codes to
  indicate how things are to appear.

  A \LaTeX\/ document always starts with {\tt {\textbackslash}documentclass}, then a
  bunch of overall controlling information. The actual document is
  between {\tt {\textbackslash}begin\{document\}} and {\tt {\textbackslash}end\{document\}}.

  {\tt {\textbackslash}usepackage\{\}} is like {\tt library()} in R.

  Ideally, you focus on {\nhilit semantics} rather than {\nhilit
  style}: define the {\tt {\textbackslash}title\{\}} and {\tt {\textbackslash}author\{\}} and use
  {\tt {\textbackslash}maketitle} to have them included in the document, and
  indicate sections and subsections with {\tt {\textbackslash}section\{\}} and
  {\tt {\textbackslash}subsection\{\}}.

  For some reason, {\tt {\textbackslash}thispagestyle\{empty\}} (``don't
  show page number on this page'') needs
  to be placed {\nhilit after} {\tt {\textbackslash}maketitle}.

  A key feature of \LaTeX\/ is the mathematics typesetting. There's no
  better system. And your \LaTeX\/ skills can be immediately
  transferred to your Markdown documents, with MathJax.
}
\end{frame}

\begin{frame}[c,fragile]{What I actually do}

\begin{lstlisting}
\documentclass[12pt]{article}

\setlength{\headheight}{10pt}
\setlength{\headsep}{15pt}
\setlength{\topmargin}{-25pt}
\setlength{\topskip}{0in}
\setlength{\textheight}{8.7in}
\setlength{\footskip}{0.3in}
\setlength{\oddsidemargin}{0.0in}
\setlength{\evensidemargin}{0.0in}
\setlength{\textwidth}{6.5in}

\begin{document}
\begin{center}
\textbf{\large An example document}

\vspace{10mm}
Karl Broman
\end{center}

\vspace{30mm}
\textbf{\sffamily A section}
\end{lstlisting}

\note{
  In reality, for a paper, I don't use {\tt {\textbackslash}maketitle}
  or {\tt {\textbackslash}section}, but rather just muck about,
  hard-coding the placement of things.

  But mine is not the recommended approach. If, for some reason, you
  need to change the style, it's easier if your document is defined in
  terms of {\nhilit semantics}.
}
\end{frame}

\begin{frame}{Why \LaTeX\/?}

\bbi
\item Fine control of document appearance
\item Transparency of how that was achieved
\item Version control (diff/merge)
\item Typesetting equations
\item Markdown's not quite ready, or sufficiently rich
  \bi
  \item[] (but see the R package \href{https://github.com/rstudio/rticles}{rticles})
  \ei
\ei

\note{
  It's {\nhilit a lot} of work to learn \LaTeX, so we need to be clear
  about why we'd want to devote the effort to it.

  For reproducible research, we need some sort of code-based document
  system (i.e., {\nvhilit not Word!}), and \LaTeX\/ gives you the most
  fine-grained control, if you need it. Ultimately, I hope, Markdown
  will be sufficient, but for now, we often need \LaTeX\/.

  The code-based control makes what you're trying to do
  transparent.  And you should treat \LaTeX\/ like code: write clearly
  and simply, and comment the tricky bits.

  This sort of document also has the advantage of easy treatment of
  {\tt diff} and {\tt merge} in a version control system like git.

  The real power of \LaTeX\/ is in the typesetting of mathematical
  equations. And what you learn on that aspect can be transferred to
  your Markdown documents, using MathJax. (But I already said that,
  didn't I?)
}
\end{frame}

\begin{frame}[c]{}

\vspace{10mm}

\centerline{\Large simple \quad $\longleftrightarrow$ \quad flexible}

\vspace{10mm}

\onslide<2->{\centerline{\tt \scriptsize \lolit {\textbackslash}centerline\{{\textbackslash}Large simple
{\textbackslash}quad \${\textbackslash}longleftrightarrow\$ {\textbackslash}quad flexible\}}}

\note{
  \LaTeX\/ sits at the right of the simple-to-flexible spectrum.
}
\end{frame}

\begin{frame}[c]{}

\centering
Modify your desires to match the defaults.

\vspace{36pt}

Focus your compulsive behavior on things that matter.

\note{
  I've said this before, but I like to repeat it.

  Focus on the text and the figures before worrying too much about
  fine details of how they appear on the page.

  And consider which is more important: a manuscript, web page, blog,
  grant, course slides, course handout, report to collaborator,
  scientific poster.

  You can spend a ton of time trying to get things to look just
  right. Ideally, you spend that time trying to construct a general
  solution.  Or you can modify your desires to more closely match what
  you get without any effort.
}
\end{frame}

\begin{frame}[c,fragile]{Stuff I use a lot}

\begin{lstlisting}
% other fonts
\usepackage{palatino}
\usepackage{times}

\setlength{\rightskip}{0pt plus 1fil} % makes ragged right

\newcommand{\LOD}{\text{LOD}}

\usepackage{setspace}
\setstretch{2.0}

\addtocounter{framenumber}{-1}

% make figures S1, S2, ...
\renewcommand{\thefigure}{\textbf{S\arabic{figure}}}
\renewcommand{\figurename}{\textbf{Figure}}

% bigger space between rows in tables
\renewcommand{\arraystretch}{1.5}

% paragraphs not indented but have space between
\setlength{\parskip}{6pt}
\setlength{\parindent}{0pt}
\end{lstlisting}

\note{
  These are bits of \LaTeX\/ code that I use a lot.
}
\end{frame}

\begin{frame}<handout:0>[c,fragile]{KnitR + \LaTeX $\rightarrow$ Rnw}

\begin{lstlisting}
\documentclass[12pt]{article}

\title{An example Rnw document}
\author{Karl Broman}

\begin{document}
\maketitle

<<load_library, echo=FALSE, results="hide">>=
library(broman) # used for myround()
@

<<example_chunk>>=
x <- rnorm(100)
y <- 5*x + rnorm(100)
lm.out <- lm(y ~ x)
plot(x,y)
abline(lm.out$coef)
@

The estimated slope is \Sexpr{myround(lm.out$coef[2], 1)}.
\end{document}
\end{lstlisting}
\end{frame}

\begin{frame}[c,fragile]{KnitR + \LaTeX $\rightarrow$ Rnw}
\addtocounter{framenumber}{-1}

\begin{lstlisting}
\documentclass[12pt]{article}

\title{An example Rnw document}
\author{Karl Broman}

\begin{document}
\maketitle

<<load_library, echo=FALSE, results="hide">>=
library(broman) # used for myround()
@

<<example_chunk, out.width="0.8\\textwidth">>=
x <- rnorm(100)
y <- 5*x + rnorm(100)
lm.out <- lm(y ~ x)
plot(x,y)
abline(lm.out$coef)
@

The estimated slope is \Sexpr{myround(lm.out$coef[2], 1)}.
\end{document}
\end{lstlisting}

\note{
  KnitR works well with LaTeX.

  Most of what you learned about KnitR with R Markdown transfers
  directly to working with LaTeX.

  The main difference is the way in which code chunks are
  indicated. You use {\tt <<>>=} and {\tt @} for chunks, and
  {\tt {\textbackslash}Sexpr\{\}} for in-line code.

  KnitR basically does a search-and-replace for code
  chunks. Different patterns will be easier, depending on the nature
  of the surrounding code.

  The chunk options are the same. Here, I used
  {\tt out.width="0.8{\textbackslash}textwidth"}
  to make the figure appear as 80\% of the width of the page.

  {\tt out.width} and {\tt out.height} need units as in \LaTeX\/ (built into
  {\tt {\textbackslash\textbackslash}textwidth}; otherwise {\tt "in"}
  or {\tt "cm"} or {\tt "pt"} or whatever).

  {\tt fig.width} and {\tt fig.height} are as in R, with implied units.
}
\end{frame}

\begin{frame}{LyX}

\vspace{20pt}

\figh{Figs/lyx.png}{0.7}

\vspace{20pt}

\hfill \href{http://www.lyx.org/}{lyx.org}

\note{
  I create \LaTeX\/ documents in emacs. If you want something WYSIWYG,
  consider LyX. KnitR is built in, and Yihui Xie strongly endorses
  it. (LyX is not really ``WYSIWYG'' but rather ``WYSIWYM,'' but
  that's what you want most, anyway.)
}
\end{frame}

\begin{frame}{Also}

\bbi
\item \href{http://overleaf.com}{Overleaf}
\item \href{http://sharelatex.com}{ShareLaTeX}
\item \href{http://authorea.com}{Authorea}
\item \href{http://verbosus.com}{Verbosus}
\ei

\note{
  There are a bunch of online tools for creating LaTeX documents,
  collaboratively.

  I have no experience with these, but I've heard good things about
  Overleaf (formerly WriteLaTeX).
}
\end{frame}

\begin{frame}{Flavors of \LaTeX}

\bbi
\item \href{http://www.latex-project.org/}{\LaTeX}
\item \href{http://en.wikipedia.org/wiki/PdfTeX}{pdflatex}
\item \href{http://en.wikipedia.org/wiki/XeTeX}{xelatex}
\item \href{http://www.luatex.org/}{lualatex}
\ei

\note{
  In addition to regular \LaTeX, there's pdflatex (which I mostly
  use). It has the advantage of being able to include pdf, jpg, and
  png figures, and produces a PDF file directly.

  XeLaTeX and LuaLaTeX are great for fonts and Unicode.

  I've not mentioned that behind the scenes is \TeX, which is the
  source of all of this. Believe or not, \LaTeX\/ exists because
  \TeX\/ is even harder. PdfLaTeX, XeLaTeX, and LuoLaTeX, really
  derive from PdfTeX, XeTex, and LuoTex.
}
\end{frame}

\begin{frame}{Getting help}

\bbi
\item Google
\item \href{tex.stackexchange.com}{tex.stackexchange.com}
\item Ask a friend
\item Look at others' documents
\item Resign yourself to something less-than-ideal
\ei

\note{
  There is {\nhilit a ton} of online information about \LaTeX. Start
  with google. It's highly unlikely that you have a completely unique
  question or problem.

  My last point here is basically that one way to help yourself is by
  learning to let things go.
}
\end{frame}

\begin{frame}[c,fragile]{Figure captions and floats}

\begin{lstlisting}
<<fig_with_caption, fig.cap="Scatterplot of $y$ vs $x$">>=
x <- rnorm(100)
y <- 5*x + rnorm(100)
lm.out <- lm(y ~ x)
plot(x,y)
abline(lm.out$coef)
@
\end{lstlisting}

\bigskip

\begin{lstlisting}
\begin{figure}[]
\includegraphics{figure/fig_with_caption}

\caption{Scatterplot of $y$ vs $x$\label{fig:fig_with_caption}}
\end{figure}
\end{lstlisting}

\note{
  If you use the chunk option {\tt fig.cap}, the figure will get a
  caption.

  But it will also be embedded within a {\tt figure} ``environment.''
  (That is, between {\tt {\textbackslash}begin\{figure\}} and
  {\tt {\textbackslash}end\{figure\}}.)

  This makes it a ``float.'' \LaTeX\/ decides where it's going to be
  placed. The placement of floats is {\nvhilit the biggest pain} in
  using \LaTeX.

  The figure also gets a label, from the chunk name. (The
  {\tt {\textbackslash}label\{\}} bit.) This allows you to
  cross-reference the figure, to have the figure number determined
  automatically.

  The cross reference would be with {\tt {\textbackslash}ref\{fig:fig\_with\_caption\}}.

  When you use cross references, you need to run \LaTeX\/ twice: once
  to establish where things will sit on the page and how they are
  numbered, and a second time to insert the cross references.
}
\end{frame}

\begin{frame}[fragile]{Tables in \LaTeX}

\vspace{18pt}

\begin{lstlisting}
\begin{tabular}{rrrrr} \hline
& Estimate & Std. Error & t value & Pr($>$$|$t$|$) \\  \hline
(Intercept) & 0.04 & 0.11 &  0.4 & 0.69 \\
      x     & 0.98 & 0.10 & 10.0 & 0.00 \\ \hline
\end{tabular}
\end{lstlisting}

\note{
  Tables in \LaTeX\/ are a pain, but they offer extremely fine
  control.

  But writing this sort of code ({\tt \&} indicates breaks between
  columns, {\tt {\textbackslash}{\textbackslash}} indicates the end of
  a row) {\nhilit reproducibly} is hard.
}
\end{frame}

\begin{frame}[fragile]{xtable}

\vspace{18pt}

\begin{lstlisting}
<<generate_and_fit>>=
x <- rnorm(100)
y <- x + rnorm(100)
lm.out <- lm(y ~ x)
@

<<table, results="asis">>=
library(xtable)
xtable(lm.out, digits=c(0,2,2,1,2))
@

% a non-floating version
<<table, results="asis">>=
library(xtable)
xtab <- xtable(lm.out, digits=c(0,2,2,1,2))
print(xtab, floating=FALSE)
@
\end{lstlisting}

\note{
  xtable is a superb R package for producing \LaTeX\/ tables.
  You don't have complete control, but you do have a ton of
  control. The xtableGallery vignette shows you much of what can be
  done.

  Note that a lot of the options are for {\tt print.xtable}, so look
  at the help files for both {\tt xtable} and {\tt print.xtable}.

  For example, if you {\nhilit don't} want a table to be ``floating,''
  (within a {\tt table} environment, between
  {\tt {\textbackslash}begin\{table\}} and
  {\tt {\textbackslash}end\{table\}}),
  you need to use {\tt print.table} with {\tt floating=FALSE}.
}
\end{frame}

\begin{frame}{Read proofs carefully}

\vspace{12pt}

As submitted
\bigskip

\figw{Figs/rigenome_as_submitted.png}{0.5}

\bigskip \bigskip

As printed
\bigskip

\figw{Figs/rigenome_error.png}{0.5}

\vfill
\hfill
{\lolit \scriptsize Broman (2005) Genetics 169:1133{\textendash}1146}

\note{
  Some journals re-type a bunch of your manuscript, sometimes
  introducing errors.

  So read proofs {\nhilit carefully}. (What pain!) And post a
  preprint, say to arXiv.org or bioRxiv.org.

  The above is the most important equation in the paper, and I missed
  that they'd introduced a mistake.
}
\end{frame}

\begin{frame}[c]{Re-type that!}

\vspace{18pt}

\figh{Figs/preCC_table.png}{0.65}

\vfill
\hfill
{\lolit \scriptsize Broman (2012) Genetics 190:403{\textendash}412}

\note{
  I have a few papers with {\nhilit a lot} of equations. I hope
  they're not trying to re-type these. I generated them from code.
}
\end{frame}

\begin{frame}[c,fragile]{BibTeX for bibliographies}

\begin{lstlisting}
%bibliography format
\usepackage[authoryear]{natbib}
\bibpunct{(}{)}{;}{a}{}{,}

A number of investigators have developed methods for identifying
such sample mix-ups \citep{Westra2011, Schadt2012, Lynch2012,
Ekstrom2012}, and a similar approach was applied by
\citet{Baggerly2008, Baggerly2009} in their forensic...

\bibliographystyle{genetics}
\renewcommand*{\refname}{\centerline{\normalsize\sffamily
   \textbf{Literature Cited}}}
\bibliography{samplemixups}
\end{lstlisting}

\bigskip

\begin{lstlisting}
@article{Baggerly2008,
author = {Baggerly, Keith A. and Coombes, Kevin R.},
journal = {J. Clin. Oncol.},
pages = {1186--1187},
title = {Run batch effects potentially compromise...},
volume = {26},
year = {2008} }
\end{lstlisting}

\note{
  References with \LaTeX\/ are via BibTeX, which is fabulous once you
  get used to it. Most software to track references will produce
  BibTeX files for you.

  The formatting of citations and the reference listings, to match
  what the journal wants, can be painful. But I've figured out how to
  produce what \emph{Genetics\/} wants, and I send all of my papers
  there.

  The first box is the sort of code that would appear
  in your \LaTeX\/ file: the bit at the top goes in the header (before
  {\tt {\textbackslash}begin\{document\}}). The bit in the middle
  shows how to cite papers: use {\tt {\textbackslash}citep} to get the
  whole thing in parentheses, and use {\tt {\textbackslash}citet} to
  get a reference like ``...applied by Baggerly and Coombes (2008, 2009)...''
  The last bit in the first box produces the actual list of references.

  The second box is the BibTeX format for a particular reference.

  When you use BibTeX, you tend to run {\tt pdflatex}, then {\tt
  bibtex}, and then {\tt pdflatex} a couple of more times.
}
\end{frame}

\begin{frame}{Organizing analyses}

\bbi
\item Directory for the main analysis project
  \bi
  \item[] {\tt {\textasciitilde}/Projects/Blah}
  \ei
\item Directory for a paper
  \bi
  \item[] {\tt {\textasciitilde}/Docs/Papers/Blah}
  \ei
\item Paper directory may have an analysis directory
  \bi
  \item[] {\tt {\textasciitilde}/Docs/Papers/Blah/Analysis}
  \ei
\item Symbolic links to {\tt .RData} files
  \bi
  \item[] {\tt ln -s {\textasciitilde}/Projects/Blah/DerivedData/blah.RData .}
  \ei
\item Each part well organized and fully reproducible.
\item R Markdown reports documenting different aspects.
\item Analysis with the paper may be re-done "properly."
\ei

\note{
  This is how I organize a paper related to a larger project.

  Some of the work in the main project may be re-done a bit
  differently (or cleaner) in the analysis with the paper.

  You don't want to re-do {\nhilit all} analyses for the paper, but
  it'd also be nice to have the data and code related to the paper be
  a bit more self-contained.

  And usually when you're sitting down to write the paper, you have
  better ideas about how to re-do things properly, and so it might be
  a good idea to go ahead and re-do things.

  Ideally, you'd separate out each aspect of the analysis: data
  manipulation, data cleaning, and different parts of the analysis.

  Have an R Markdown document describing each aspect, with the
  actual manuscript and its figures and tables drawing from the
  results of those R Markdown documents.
}
\end{frame}

\begin{frame}[c,fragile]{Make every number reproducible.}

\begin{lstlisting}
<<define_numbers, echo=FALSE>>=
numbers <- c("one", "two", "three", "four", "five",
             "six", "seven", "eight", "nine", "ten")
cap <- function(vec) paste0(toupper(substr(vec, 1, 1)),
                            substr(vec, 2, nchar(vec)))
Numbers <- cap(numbers)
n <- sample(1:10, 1)
@

Then if I want to talk about a number, like \Sexpr{n}, I can
refer to it by name: \Sexpr{numbers[n]}. And I can start a
sentence with it. \Sexpr{Numbers[n]} grasshoppers walked into a
bar\dots

But be careful about singular vs. plural, and so write
\Sexpr{Numbers[n]} grasshopper\Sexpr{ifelse(n>1, "s", "")}
walked\dots
\end{lstlisting}

\note{
  Every statistic, figure and table in your manuscript should be fully
  reproducible. So when you're citing statistics, use
  {\tt {\textbackslash}Sexpr\{\}} liberally.

  This should inhibit you from writing numbers as words, though the
  \LaTeX\/ code can get a bit ugly.

  There's a bit of fanciness here about capitalization and about
  ensuring that singular or plural nouns are correct. If
  {\tt {\textbackslash}Sexpr\{\}} produces a character string, it ends
  up as plain text in your document

  I'll use a lot of {\tt myround()} from my R/broman package, too.

  Long explanations or descriptions of figures can't be fully
  reproducible, but the figures themselves and any statistics you
  mention should be.
}
\end{frame}

\begin{frame}[c,fragile]{Keep the figures separate}

\begin{lstlisting}
# simple make file

mypaper.pdf: mypaper.tex Figs/fig1.pdf Figs/fig2.pdf
    pdflatex mypaper

Figs/fig1.pdf: R/fig1.R
    cd R;R CMD BATCH fig1.R fig1.Rout

Figs/fig2.pdf: R/fig2.R
    cd R;R CMD BATCH fig2.R fig2.Rout
\end{lstlisting}

\bigskip \bigskip

\begin{lstlisting}
\clearpage
\includegraphics{Figs/fig1.pdf}

\clearpage
\includegraphics{Figs/fig2.pdf}
\end{lstlisting}

\note{
  While you {\nhilit could} include all code in your {\tt .Rnw} file,
  I prefer to pull out the code for my figures as separate files, and
  then write a {\tt Makefile} for the manuscript construction and
  include them with {\tt {\textbackslash}includegraphics}.

  The advantage of this is the ability to reuse the figures in
  talks or whatever. Also, journals will generally want the figures as
  separate files. Finally, the code for my figures is often incredibly
  long and ugly, so it's best to separate it out.

  Ideally, the code for a figure would be structured as a function and
  then a function call.  Put a bit more effort into the code, so that
  you can reuse it later for a similar figure with different data.
  At the very least, you should write the repeated bits as functions.

  If your function takes arguments that define the placement of
  things (padding for text and so forth), then the fine adjustments of the
  figure appearance would be easier.
}
\end{frame}

\begin{frame}{Version Control}

\bbi
\item Your manuscript is under version control, right?
\onslide<2->{\item Local or private repository for the whole thing
  \bi
  \item including reviewers' reports and my response
  \item PDF of submitted and final manuscript
  \ei
\item Snapshot of the final version as a public repository
  \bi
  \item I don't really want to show the whole history
  \ei
}
\ei

\note{
  Git is as good for tracking manuscripts and data analyses as it is
  for tracking code. Use it!

  But I don't want to make {\nhilit everything} public, and I want to
  include private stuff in my repository.

  I've been using just a local repository, but I'm moving towards
  having a private repository hosted on BitBucket.

  I'll put a snapshot of the final version, and maybe a few final
  changes, on GitHub.
}
\end{frame}

\begin{frame}{Word}

\bbi
\item With papers led by a collaborator, I'm usually stuck with Word.
\item But my analyses and figures are fully reproducible.
\item Create an R Markdown document with the detailed results.
\ei

\note{
  Often, you'll be stuck with Word. And you can't reproducibly insert
  numbers into Word.

  So have a separate R Markdown report with the detailed results,
  including every statistic that will get inserted into Word.

  And take control of the figures and ensure that they are
  reproducible (and respectable).

  Teach your collaborators to at least have their figures be
  reproducible?
}
\end{frame}

\begin{frame}{Summary}

\bbi
\item \LaTeX\/ is brilliant for fine control and for equations
\item Floating figures and tables can be a pain
\item You use KnitR with \LaTeX\/ much the same way as you'd used it
  with Markdown.
\item Ensure that every statistic, figure, and table in your paper are
  fully reproducible.
\item Use xtable to make tables.
\item Separate out the code for the figures.
\item Use version control!
\ei

\note{
  Summaries are helpful.
}
\end{frame}

\end{document}


\documentclass[simplex.tex]{subfiles}
% NO NEED TO INPUT PREAMBLES HERE
% packages are inherited; you can compile this on its own

\onlyinsubfile{
\title{NeuroData SIMPLEX Report: Subfile}
}

\begin{document}
\onlyinsubfile{
\maketitle
\thispagestyle{empty}

The following report documents the progress made by the labs of Randal~Burns and Joshua~T.~Vogelstein at Johns Hopkins University towards goals set by the DARPA SIMPLEX grant.

%%%% Table of Contents
\tableofcontents

%%%% Publications
\bibliographystyle{IEEEtran}
\begin{spacing}{0.5}
\section*{Publications, Presentations, and Talks}
%\vspace{-20pt}
\nocite{*}
{\footnotesize	\bibliography{simplex}}
\end{spacing}
%%%% End Publications
}

\subsection{Robust Law of Large Graphs}

To estimate the mean of a collection of weighted graphs under a
low rank random graph model (e.g. Stochastic Blockmodel) when
observing contaminated graphs, we propose an estimator which not
only inherits robustness from element-wise robust estimators but
also has small variance due to application of a rank-reduction
procedure. Under appropriate conditions, we prove that our
estimator outperforms standard estimators via asymptotic relative
efficiency.  And we illustrate our theory and methods by Monte
Carlo simulation in figure~\ref{fig:rlolg}.

\begin{figure}[h!]
\begin{cframed}
\centering
\includegraphics[width=0.45\textwidth]{./figs/robQ.png}
\hspace{6pt}
\includegraphics[width=0.45\textwidth]{./figs/robEps.png}
\caption{
For the figure on the left, we vary the proportion of the contamination
represented by  and conclude: \textbf{1. MLE (red) vs ML$q$E
(blue)}: MLE outperforms a little bit when there is no
contamination, but it degrades dramatically when contamination
increases; \textbf{2. MLE (red) vs MLE\_ASE (green)}: MLE\_ASE wins
the bias-variance tradeoff;
\textbf{3. ML$q$E  (blue) vs MLE\_ASE (purple)}:
MLE\_ASE wins the bias-variance tradeoff;
\textbf{4.  ML$q$E\_ASE (purple) vs MLE\_ASE (green)}:
When contamination is large enough, ML$a$E\_ASE is better, since it
inherits the robustness from ML$q$E.  For the right panel, we vary
the parameter $q$ in the ML$q$E.  Note that when $q=1$, ML$q$E becomes
MLE so that the curves intersect. As $q$ decreases, we intend to have
more bias but still win the bias-variance trade-off by reducing the variance.
}
\label{fig:rlolg}
\end{cframed}
\end{figure}

Also, to get the convergence rate of the variance of ML$q$E, we
proved: 1. the uniform convergence $\sup_{\theta \in \Theta} \left|
E_f[g(X, \theta)] − \frac{1}{m} \sum_{i=1}^m g(X_i, \theta) \right| \to
0$ as $m \to \infty$, where $g(x, \theta)$ is the equation for
ML$q$E; 2. There exists at least one population solution of the
ML$q$E equation which is smaller than the expectation of the MLE.

In summary, MLE outperforms a little bit when there is no contamination,
but it degrades dramatically when contamination increases while ML$q$E
still does a good job. Applying ASE to either entry-wise MLE or
entry-wise ML$q$E reduces the variance by bias towards the low rank
approximation. Our estimator based on ASE of ML$q$E inherits the
robustness from ML$q$E, and it has low variance. When contamination is
large enough, our estimator performs the best among all the four.

We tested our algorithm’s performance on a synthetic dataset based on
structural connectomic data. The graphs are based on diffusion tensor MR
images collected and available at the Consortium for Reliability and
Reproducibility (CoRR). It contains 454 different brain scans, each of
which was processed to yield an undirected, weighted graph with no
self-loops, using the ndmg pipeline..  The vertices of the graphs
represent different regions in the brain defined according to an atlas.
We used the  CPAC200 atlas with 200 vertices. The weight of an edge
between two vertices represents the number of white-matter tract
connecting the corresponding two regions of the brain. In order to
evaluate the performance of the two estimators, we used a cross
validation on the 454 graphs of each size. Specifically, for a given
atlas, each Monte Carlo replicate corresponds to sampling m graphs out
of the 454 and computing the four estimates using the m selected graphs.
We then compared these estimates to the sample mean for the remaining
454-m adjacency matrices.  We ran 1000 simulations on the CPAC200
atlases for both sample size $M=2, 5$.  We also considered all possible
dimensions for adjacency spectral embedding by ranging d from 1 to n in
order to investigate the impact of the dimension selection procedures.
We plot the result in the following figure.

\begin{figure}[h!]
\begin{cframed}
\centering
\includegraphics[width=\textwidth]{./figs/robDim.png}
\caption{
{\bf Comparison of MSEhat of the four estimators for the CPAC200 atlases at two sample sizes for the CoRR data.}
For the figure on the left, we examine the four estimators at sample size m=2.
{\bf 1. MLE (horizontal solid line) vs MLqE (horizontal dotted
line):}
ML$q$E outperforms MLE since
robust estimators are always preferred in practice;
{\bf 2. MLE (horizontal solid line) vs MLE\_ASE (dashed line):} MLE\_ASE wins the bias-variance
tradeoff when embedded into a proper dimension;
{\bf 3. MLqE (horizontal
dotted line) vs ML$q$E\_ASE (dashed dotted line):}
ML$q$E\_ASE wins the
bias-variance tradeoff when embedded into a proper dimension;
{\bf 4.  ML$q$E\_ASE (dashed dotted line) vs MLE\_ASE (dashed
line):}
MLqE\_ASE is better, since it inherits the robustness from
ML$q$E. For the figure on the right, we still can see the
robustness but the lack of low-rankness
for a larger number of samples degrades the effect of ASE.
}
\label{fig:robDim}
\end{cframed}
\end{figure}

\end{document}


\documentclass[12pt]{article} % This command is used to set the type of document you are working on such as an article, book, or presenation

\usepackage[margin=1in]{geometry} % This package allows the editing of the page layout. I've set the margins to be 1inch.
\usepackage{datetime}

\usepackage{amsmath, amsfonts}  % The first package allows the use of a large range of mathematical formula, commands, and symbols.  The second gives some useful mathematical fonts.

\usepackage{graphicx}  % This package allows the importing of images

\begin{document}

\begin{center}
    \Large{
        \textbf{Reading Report:}
        Application of Catalan Numbers and the Lattice
Path Combinatorial Problem in Cryptography
    }

    \vspace{5pt}

    \normalsize{
        GEOFF YOERGER

        \usdate
        \formatdate{7}{5}{2021}
    }

    \vspace{15pt}

    \subsection*{Abstract}

    The paper analyzes the properties of Catalan numbers with respect to the Lattice Path encryption scheme in cryptography. The encryption/decryption keys are Catalan-keys, which are a subset of numbers with a property that is synonomous with a counting ability of the Catalan numbers proper.
\end{center}

\section{Introduction}

The subject of the paper covers the use of Catalan-key numbers as a form of cryptographic text encryption.  This is performed utilizing the core properties of Catalan-key numbers, in a method called the Lattice Path Problem.  The papers also covers related work and a statistical analysis according to NIST's guidelines on cryptographic soundness;  These will not be covered in this summary.

\section{Properties of Catalan Numbers}

\subsection{Catalan Numbers}

Catalan numbers are defined as

$$
C_n = \frac{(2n)!}{(n+1)!n!} = \frac{1}{n+1} {2n \choose n}
$$

Let $B = \{0, 1\}$ be a binary alphabet.

\subsection{Catalan-key numbers and Dyke words}

Catalan-key numbers are defined as numbers $c$ where

\begin{align*}
    c = (X_1 X_2 \cdots X_n)_2, & \; \; \; X_i \in B \\
    h(X_1 X_2 \cdots X_i) \geq 0, & \; \; \;  1 \leq i \leq 2n-1 \\
    h(X_1 X_2 \cdots X_n) = 0 & \\
\end{align*}

where $h: B^n \to \mathbb{N}$ is a mapping where

\begin{align*}
    h(0) &= 1 \\
    h(1) &= -1 \\
    h(X_1 X_2 \cdots X_n) &= \sum_{i=1}^{n} h(X_i) \\
\end{align*}

In other words, Catalan-key numbers are numbers whose binary representations are isomorphic to Dyke words.

Dyke words are words from the alphabet consisting of one left bracket and one right bracket, where all brackets are properly paired and nested. For example, and the 6-length Dyke words are:
\begin{enumerate}
    \item "[[[]]]"
    \item "[][[]]"
    \item "[][][]"
    \item "[[]][]"
    \item "[[][]]"
\end{enumerate}

By definition, the $n$-th Catalan number $C_n$ counts the number of total Dyke words of length $2n$, and because of the isomorphism between Catalan-keys and Dyke words, $C_n$ also counts the number of Catalan-keys with $2n$ bit long representations.  Hence, their name.

\section{Lattice Path Combinatorial Problem}

The Lattice path combinatorial problem deals with the calculations of the number of paths through a $n x n$ lattice space, from point $(0,0)$ to point $(n,n)$.

Here, we restrict movement across the diagonal line connecting the start and end points, and individual movement steps are only allowed to come from the set $\{(0,+1), (+1,0)\}$, in other words, the only possible movements are one unit right, or one unit up.

A common application of catalan numbers is showing that $C_n$ counts the total number of possible paths in such a $n x n$ lattice grid.

\subsection{Application of Catalan-key}

It follows that each $2n$-bit catalan-key uniquely represents each possible path in the lattice grid. $1$s denote movement one unit right, $0$s denote one movement up.

The restriction $ h(X_1 X_2 \cdots X_i) \geq 0$ ensures that the cummulative number of right movements is always greater than or equal to the number of up movements and any point in the path, this ensures the path never crosses the diagonal.

The restriction $h(X_1 X_2 \cdots X_n) = 0$ ensures the final endpoint of the path is $(n,n)$.

\section{The encryption scheme}

The idea presented in the paper is that these lattice paths are applicible to designate a way to encrypt a plaintext into a ciphertext by use of swapping character locations based on the bit patterns in Catalan-keys.

\subsection{The algorithm}

Using a $2n$-bit Catalan key, and an arbitrary plaintext.

\begin{enumerate}
    \item Expand the binary representation of the Catalan-key into a boolean array $A$ of length $2n$, where $A[n]$ is true if the $n$-th bit is $1$.
    \item Split the plaintext into $2n$-length segments
    \item For each segment \begin{enumerate}
            \item Make a LIFO Stack
            \item For i = 0..2n \begin{enumerate}
                    \item If $A[i]$, Pop the front character of the plaintext into the stack, this is analogous to a "right movement"
                    \item Else, Pop the top of the stack onto the end of the ciphertext, analogous to a "up movement"
            \end{enumerate}
        \item Output the encrypted segment
    \end{enumerate}
\end{enumerate}

My description of the algorithm does not match specifically the algorithm described in the paper, which uses fixed length arrays for the plaintext and ciphertext, while manually tracking the indexes into both.  Using a stack works to simplify understanding.

The properties of Catalan-keys ensure that the same number of characters will be pushed onto the stack as popped off, and that whenever a pop occurs, the stack will be not empty.

The execution of this process is completely deterministic, so decryption simply works backwards given a cipertext and key to recover the plaintext.

The algorithm can be performed on arbitrary alphabets, for example, in the encrytion of english characters, the plaintext can be first converted to its binary representation, and the binary string manipluated as above to achieve an encryption scheme whose result is far less recognizable.

\pagebreak

\subsection{An example}

Taken from the paper.

\includegraphics[width=\textwidth]{path}

\includegraphics[width=\textwidth]{chart}

\section{Conclusion}

This paper showed how Catalan-key numbers can be used in encryption schemes.  The core properties of Catalan-key numbers ensured the algorithms possible operation.  The parameters in the algorithm are also variable to ensure a wide execution space (key size, input representation)

However, crytographic viability was not tested, so this appeared to be mostly a proof of concept for inspiring further work.

\section{Source}

Saračević, Muzafer, Saša Adamović, and Enver Biševac. "Application of Catalan numbers and the lattice path combinatorial problem in cryptography." Acta Polytechnica Hungarica 15.7 (2018): 91-110.

\end{document}


% Chapter 1

\chapter{Introduction} % Main chapter title

\label{Chapter1} % For referencing the chapter elsewhere, use \ref{Chapter1}

%----------------------------------------------------------------------------------------

% Define some commands to keep the formatting separated from the content
\newcommand{\keyword}[1]{\textbf{#1}}
\newcommand{\tabhead}[1]{\textbf{#1}}
\newcommand{\code}[1]{\texttt{#1}}
\newcommand{\file}[1]{\texttt{\bfseries#1}}
\newcommand{\option}[1]{\texttt{\itshape#1}}

%----------------------------------------------------------------------------------------

Spanning trees have been a central object of study in graph theory for a long time. \citet{doi:10.1002/andp.18471481202} established a linear algebraic relationship between spanning trees of graphs and determinants while studying electric networks. We are interested in the following problem.

\begin{IP}[Uniform random spanning tree]
 Given an undirected connected graph $G = (V, E)$, sample a spanning tree $T$ with probability $\frac{1}{|\mathcal{T}|}$ where $\mathcal{T}$ denotes the set of all spanning trees of $G$.
\end{IP}

Sampling spanning trees happens to be a primitive used in various problems such as

\begin{itemize}
\item Constructing expanders (\cite{10.5555/1496770.1496834}, \cite{doi:10.1137/120890971})
\item Approximation algorithms for the travelling salesman problem(\cite{6108216}, \cite{doi:10.1287/opre.2017.1603})
\item Graph Sparcification (\cite{DBLP:journals/corr/abs-1005-0265}, \cite{dolev2016random})
\item Analysis of network reliability (\cite{10.5555/535891},\cite{doi:10.1002/net.3230200303}, \cite{colbourn1988estimating})
\item Sequence shuffling problem in Bioinformatics (\cite{KANDEL1996171})

\end{itemize}

\citet{10.1007/3-540-51687-5_27} proposed a distributed algorithm for this problem. Recently \citet{a11040053} implemented some of the random walk algorithms and have compared their efficiencies.

\subsection{Algorithms for sampling random spanning trees}
There has been a lot of progress in this problem for the past 40 years. These algorithms can be broadly classified into 3 categories.

\subsubsection{Matrix Based }
These algorithms are based on Kirchoff Matrix Tree theorem and involve computing determinants of the laplacian matrix of the graph  to sample spanning trees. These notions would be made clear in later part of the thesis.

\begin{itemize}
\item Random Spanning Tree, \cite{GUENOCHE1983214}
\item Unranking and ranking spanning trees of a graph, \cite{COLBOURN1989271}
\item Generating random combinatorial objects, \cite{KULKARNI1990185}
\item Two Algorithms for Unranking Arborescences, \cite{COLBOURN1996268}
\item Generating random spanning trees via fast matrix multiplication, \cite{harvey2016generating}
\end{itemize}

\subsubsection{Random Walk Based}
These algorithms simulate variants of random walk on the input graph and consutructs a spanning tree from this simulation.
\begin{itemize}
\item Generating random spanning trees, \cite{63516}
\item The random walk construction of uniform spanning trees and uniform labelled trees, \cite{aldous1990random}
\item Generating random spanning trees more quickly than the cover time, \cite{10.1145/237814.237880}
\item How to Get a Perfectly Random Sample from a Generic Markov Chain and Generate a Random Spanning Tree of a Directed Graph, \cite{Propp1998HowTG}

\end{itemize}

\subsubsection{Approximation Algorithms}
These are more recent algorithms which sample a uniform spanning tree with a high probability. The main theme here is to employ tools from approximation algorithms.
\begin{itemize}
\item Faster generation of random spanning trees, \cite{10.5555/1747597.1748019}
\item Fast Generation of Random Spanning Trees and the Effective Resistance Metric, \cite{10.5555/2722129.2722263}
\item Sampling Random Spanning Trees Faster than Matrix Multiplication, \cite{10.1145/3055399.3055499}
\item An Almost-Linear Time Algorithm for Uniform Random Spanning Tree Generation, \cite{10.1145/3188745.3188852}
\end{itemize}

\subsection{Motivation}

The main motivation with which we started exploring this problem was to extend sampling random spanning trees to a dynamic setting. We explored some ideas on how this could be done faster than computing it from scratch. This is explained in the \textbf{Conclusion}.

\subsection{Structure of the thesis}

First we define the basic ideas which would be used later. Then we give a brief summary of the algorithms of some of the papers listed above. Then we explain the \citet{harvey2016generating} algorithm in detail.


\documentclass[12pt]{article}

\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{tabularx}
\usepackage{multicol}
\usepackage{algpseudocode}
\usepackage{algorithm}

% Geometry
\usepackage{geometry}
\geometry{letterpaper, left=15mm, top=20mm, right=15mm, bottom=20mm}

% Fancy Header
\usepackage{fancyhdr}
\renewcommand{\footrulewidth}{0.4pt}
\pagestyle{fancy}
\fancyhf{}
\chead{CSC 360 - Analysis of Algorithms}
\lfoot{CALU Fall 2021}
\rfoot{RDK}

% Add vertical spacing to tables
\renewcommand{\arraystretch}{1.4}

% Macros
\newcommand{\definition}[1]{\underline{\textbf{#1}}}

\newenvironment{rcases}
  {\left.\begin{aligned}}
  {\end{aligned}\right\rbrace}

% Begin Document
\begin{document}

\section*{Notes Week 4}

\begin{itemize}

    \item Exam in Week 5 - Last Names A-M 6:00pm, N-Y 6:45pm

    \item Read Chapter 4 for Week 6 - after exam

\end{itemize}

\section*{Quiz 1 Review - Proof by Induction}

Prove $n < 2n$ for all $n \geq 1$.

\begin{enumerate}

    \item Base Case: $n=1$ \\ \\
    \begin{tabular}{l}
        $1 < 2\times(1)$ \\
        $1 < 2$
    \end{tabular}

    \item Assume this is true for $1, \ldots, k$.

    \item If true for $k$, then it is true for $k+1$ \\ \\
    \begin{tabular}{l l}
        $k < 2k$ & Independent Hypothesis \\
        $k + 1 < 2k + 1$ & Add 1 to both sides \\
        $k + 1 < 2k + 1 + 1$ & As this is an equality, can add $1$ to the larger side and hold true \\
        $k + 1 < 2k + 2$ & Simplify \\
        $k + 1 < 2(k + 1)$ & Factor out the two \\
    \end{tabular}

\end{enumerate}

\pagebreak

\section*{Example - Proof by Induction}

Prove that path of length $n$ has $n-1$ edges.

\begin{enumerate}

    \item Base Case: $n=2$ \\ \\
    \begin{tabular}{l}

    \end{tabular}

    \item Assume this is true for $1, \ldots, k$.

    \item If true for $k$, then it is true for $k+1$ \\ \\
    \begin{tabular}{l l}

    \end{tabular}

\end{enumerate}

\pagebreak

\section*{Proof By Contradiction}

\begin{itemize}

    \item Prove something by contradicting the negated hypothesis

    \item ``Not everyone that is exactly six feet tall has red hair.''

    \item The Steps:
    \begin{enumerate}

        \item Assume that the hypothesis is false

        \item Show the assumption leads to a contradiction

        \item Recognize that assuming step 1 is false leads to a contradiction, implying the hypothesis is true

    \end{enumerate}

\end{itemize}

\section*{Example - Proof by Contradiction}

Prove if $n$ is an integer and $n^2$ is even, then $n$ is even.

Suppose by way of contradiction that:
\begin{itemize}
    \item $n$ is an integer
    \item $n^2$ is even
    \item $n$ is odd
    \begin{itemize}
        \item[$\rightarrow$] $n = 2k+1$ for some integer $k$ (the definition of an odd number)
    \end{itemize}
    \item $n^2 = (2k+1)^2 = 4k^2 + 4k + 1$
    \item $2(2k^2+2k) + 1$ is odd
    \item $n^2$ is odd
\end{itemize}

Contradiction: $n^2$ cannot be both even and odd.

\section*{Example - Proof by Contradiction}

Prove: for every $n$, if $n > 2$ and $n$ is prime, then $n$ is odd.

Suppose by way of contradiction that:
\begin{itemize}
    \item $n>2$
    \item $n$ is prime
    \item $n$ is even
    \item $n = 2k$ for some integer $k$ (definition of an even integer)
    \item $k != 1$
    \item $n = 2(k)$, $k>1$
    \item $n \& (whole number > 1)$ is composite
\end{itemize}

Contradiction: $n$ cannot be both composite and prime

\section*{Example - Proof by Contradiction}

Prove: No integers $a$ \& $b$ exist for which $24a + 12b = 1$.

Suppose by way of contradiction:
\begin{itemize}
    \item $a$ is an integer
    \item $b$ is an integer
    \item $24a + 12b = 1$
    \item Divide by 12, $2a + b = \frac{1}{12}$
\end{itemize}

Contradiction: A whole number multiplied by $2$ summed with another whole number cannnot be a fraction.

\pagebreak

\section*{Notation notes}

\begin{itemize}
    \item $B = O(A) \rightarrow$ B is upper bounded by A
    \item $T(n) = O(f(n))$ if there are positive constants $c$ \& $n_0$ such that $T(n) \leq cf(n)$ when $n \geq n_0$
    \item $A = \Omega(B) \rightarrow$ A is lower bounded by B
    \item $T(n) = \Omega(f(n))$ if there are positive constants $c$ \& $n_0$ such that $T(n) \geq cf(n)$ when $n \geq n_0$
    \item $\omega(n)$ instead of $\Omega(n)$ if not possible to be equal
    \item $T(n) = \mu(f(n))$ if there are positive constants $c$ \& $n_0$ such that $T(n) > cf(n)$ when $n \geq n_0$
    \item Use the lower case versions when bounded but not able to equal. Use upper case when bounded and can be equal, based on definitions above.
    \item $T(n) = \Theta(f(n))$ if and only if $T(n) = O(f(n))$ and $T(n) = \Omega(f(n))$
\end{itemize}

Given $f(n) = 3n^2$ and $g(n) = 5n^2$, give all true statements.
\begin{itemize}
    \item $f(n) = O(g(n))$
    \item $g(g) = \Omega(f(n))$
    \item etc.
\end{itemize}

\end{document}


\include{../common/start}
\title[Intro to CP]{Introduction to Competitive Programming}
\subtitle[Get started with CP 2]{Get started with competitive programming - part 2}

\include{../common/init}

\section{Structure of a problem statement}
\begin{frame}
    \frametitle{Statement}
    \href{http://codeforces.com/problemset/problem/796/A}{http://codeforces.com/problemset/problem/796/A}
    \screenshot{screenshots/statement.png}
\end{frame}

\begin{frame}
    \frametitle{Statement - Story}
    \screenshot{screenshots/statement_story.png}
\end{frame}

\begin{frame}
    \frametitle{Statement - Task}
    \screenshot{screenshots/statement_task.png}
\end{frame}

\begin{frame}
    \frametitle{Statement - Input format}
    \screenshot{screenshots/statement_input.png}
\end{frame}

\begin{frame}
    \frametitle{Statement - Output format}
    \screenshot{screenshots/statement_output.png}
\end{frame}

\begin{frame}
    \frametitle{Statement - Examples}
    \screenshot{screenshots/statement_examples.png}
\end{frame}

\begin{frame}
    \frametitle{Statement - Time limit}
    \screenshot{screenshots/statement_tl.png}
\end{frame}

\begin{frame}[fragile]
    \frametitle{Statement - solution}
    \begin{cppcode}
#include<bits/stdc++.h>
using namespace std;

int main() {
    int n, m, k, a, ans = 100000;
    cin >> n >> m >> k;
    for(int i = 1; i <= n; i++) {
        cin >> a;
        if(a != 0 && a <= k) ans = min(ans, 10 * abs(m - i));
    }
    cout << ans << endl;

    return 0;
}
    \end{cppcode}
\end{frame}

\section{Verdicts}
\begin{frame}
    \frametitle{How programs are evaluated}
    \begin{itemize}
        \item Problem setter uploads inputs and expected correct output \\ \pause
        \item Programs are run against the inputs and compared to the expected output \\ \pause
        \item Some program have multiple correct output - they are handled by a custom checker \\
    \end{itemize}
\end{frame}

\begin{frame}
    \frametitle{Types of verdicts}
    \begin{itemize}
        \item Accepted (AC) \\ \pause
        \item Wrong Answer (WA) \\ \pause
        \item Time Limit Exceeded (TLE) \\ \pause
        \item Runtime Error (RTE) \\ \pause
        \item Memory Limit Exceeded (TLE) \\ \pause
        \item Compile Error (CE) \\ \pause
        \item Presentation Error (PE) \\
    \end{itemize}
\end{frame}

\section{Common contest formats}
\begin{frame}
    \frametitle{Contest phases}
    \begin{itemize}
        \item SRM - coding phase, challenge phase, system test \\ \pause
        \item Codeforces rounds - pretests, hacks, system tests \\ \pause
        \item Codechef - Immediate feedback \\
    \end{itemize}
\end{frame}

\begin{frame}
    \frametitle{Problem types}
    \begin{itemize}
        \item Binary/classical - either correct or wrong \\ \pause
        \item Partial - subtasks with relaxed constraints \\ \pause
        \item Challenge/approximate - No one correct answer, have a scoring formula \\
    \end{itemize}
\end{frame}

\section{Common mistakes}
\begin{frame}[fragile]
    \frametitle{Common mistakes - printing message}
    \begin{cppcode}
int main() {
    int t;
    cout << "Enter number of test cases"; // DO NOT DO THIS
    cin >> t;
    // ...
}
    \end{cppcode}
\end{frame}

\begin{frame}[fragile]
    \frametitle{Common mistakes - not returning 0}
    \begin{cppcode}
int main() {
    //...

    return 0; // DO THIS
}
    \end{cppcode}
\end{frame}

\begin{frame}
    \frametitle{Common mistakes - wrong I/O format}
    \begin{itemize}
        \item \# of test cases \\ \pause
        \item Outputting doubles, newlines etc. \\ \pause
        \item Input whole lines, strings etc. \\
    \end{itemize}
\end{frame}

\section{Beginner tips}
\begin{frame}
    \frametitle{Beginner tips}
    \begin{itemize}
        \item Take your time \\ \pause
        \item Solve LOTS of problems \\ \pause
        \item Learn from others' code \\ \pause
        \item Learn your programming language well \\ \pause
        \item Make a list of your coding errors \\
    \end{itemize}
\end{frame}

\section{Conclusion}
\begin{frame}
    \frametitle{Thank you}
    \href{https://code-drills.com/bfscp/modules/intro}{https://code-drills.com/bfscp/modules/intro}
\end{frame}

\end{document}


\documentclass[PHIL101-Textbook.tex]{subfiles}
\begin{document}

\part{PL Truth Trees}\label{part:pl.trees}

\chapter{Reintroducing Truth Trees}
%\section{Why we need Truth Trees}

%In Part \ref{part.PL.models} we saw that the more structured models of PL make reasoning about all possible models rather complex.
In TFL a model was just an assignment of truth values to atomic formulas, so reasoning about all models was relatively straightforward: we could simply list them all in a complete truth table. In PL there isn't a simple method like complete truth tables for reasoning about consistency and validity. So we must use other methods, such as truth trees.

In this Part, we will extend our TFL truth tree method to allow for the extra complexity and symbols in PL. The tree method still tests whether a set of formulas is consistent, and we can still use it to test for properties like consistency and argument validity. If the root formulas are consistent, we will still generate a valuation from the truth tree; it will merely be a valuation for a model containing objects and predicates.

%You might want to refresh your knowledge of propositional truth trees before starting this section, as we'll be using all the methodology, rules, and strategies from that section, then adding some further complexity and subtlety.

\notation{We having been representing predicates as $P(a)$ or $R(x,y)$. But trees require us to write formulas repeatedly, and brackets can be confusing. It's fine to drop predicate brackets now and just write $Pa$ or $Rxy$.}

\section{Unquantified Trees}
PL without quantifiers behaves a lot like TFL. We have the same set of connectives, and atomic formulas such as $Pa$ and $Rbc$ behave exactly like atomic formulas such as $p$ and $q$ in TFL. It doesn't matter whether they are one-place predicates like $Pa$ or many-place like $Rbc$ or even $Skdq$. These atoms are true or false, and that's all the tree method cares about. So, if the root of our PL truth tree has no quantifiers, we can use exactly the same techniques as we did with TFL truth trees.

\subsection{Closed Trees}

Compare the truth trees that test if the TFL formula $(p \eand q) \eiff (p \eif \enot q)$ and the PL formula $(Pa \eand Qb) \eiff ( Pa \eif \enot Qb)$ are logical falsehoods:

%\begin{tabular}{c|c}
\begin{prooftree}
{close with=\ensuremath{\times}}
[(p \eand q) \eiff (p \eif \enot q), checked%, name=p1
	[p \eand q, checked%, just={\eiff}:p1, name=p2
	 [p \eif \enot q, checked%, just={\eiff}:p1, name=p3
	  [p%,  just={\eand}:p2
	   [q%,  just={\eand}:p2
	   [\enot p, close ]%, just={\eif}:p3]
	   [\enot q, close ]%, just={\eif}:p3]
	]]]]
	[\enot(p \eand q), checked
	 [\enot(p \eif \enot q), checked%, just={\eiff}:p1
	  [\enot\enot p
	   [\enot\enot q
	    [\enot p, close]
	    [\enot q, close]
	]]]]
]
\end{prooftree}
%&
\begin{prooftree}
{close with=\ensuremath{\times}, not line numbering}
[(Pa \eand Qb) \eiff (Pa \eif \enot Qb), checked
	[Pa \eand Qb, checked
	 [Pa \eif \enot Qb, checked
	  [Pa
	   [Qb
	   [\enot Pa, close ]
	   [\enot Qb, close ]
	]]]]
	[\enot(Pa \eand Qb), checked
	 [\enot(Pa \eif \enot Qb), checked
	  [\enot\enot Pa
	   [\enot\enot Qb
	    [\enot Pa, close]
	    [\enot Qb, close]
	]]]]
]
\end{prooftree}
%\end{tabular}

These trees have parallel structures. The decomposition rules for conjunction, disjunction, conditional, biconditional, double negation, and the rules for creating a root, branching, and closing a branch, are identical.

\subsection{Open Trees}

Similarly, compare the truth trees that test if the TFL formulas $p \eor q$, $\enot p$, $\enot q \eor r$ and the PL formulas $Pa \eor Qb$, $\enot Pa$, $\enot Qb \eor Rba$ are mutually consistent:

\begin{prooftree}
{close with=\ensuremath{\times}}
[p \eor q, checked
 [\enot p, checked
  [\enot q \eor r, checked
	[p, close]
	[q
	 [\enot q, close]
	 [r, open]
	]
]]]
\end{prooftree}\hspace{50pt}
\begin{prooftree}
{close with=\ensuremath{\times}, not line numbering}
[Pa \eor Qb, checked
 [\enot Pa, checked
  [\enot Qb \eor Rba, checked
	[Pa, close]
	[Qb
	 [\enot Qb, close]
	 [Rba, open]
	]
]]]
\end{prooftree}

Again, the trees have parallel structures. When we read off the valuation which makes all the formulas true, we use the same process, but the valuations will look different.

The valuation for the TFL tree is $p=\vF, q=\vT, r=\vT$.

The valuation for the PL tree is: \\

 \begin{tabular}{r l l l }
	  Domain = $\{a, b\}$
	  %\[\domain \, = \, \{\dom a, \dom b\}\]
	\\

	& \begin{tabular}{l|ll}
	           & $P$ & $Q$ \\ \hline
		a & \vF & \vU\\
		b & \vU & \vT\\
		\end{tabular}
	& \hspace{30pt}
	& \begin{tabular}{l|ll} $Rxy$        & a & b \\ \hline
		a & \vU          & \vU  \\
		b & \vT          & \vU
		\end{tabular}
\end{tabular}

We can use tables to check that the valuations make all formulas true. In \tfl:

\[
  \begin{array}{ccc|ccc|cc|cccc}
    p & q & r & p & \lor & q & \neg & p & \neg & q & \lor & r \\\hline
   \vF & \vT & \vT & \gF & \cellcolor{green!15} \vT & \gT & \cellcolor{green!15} \vT & \gF & \gF & \gT & \cellcolor{green!15} \vT & \gF
            \end{array}
  \]

  \noindent In \pl:

  \[
  \begin{array}{ccc|cc|cccc}
 Pa & \lor & Qb & \neg & Pa & \neg & Qb & \lor & Rba \\\hline
\gF & \cellcolor{green!15} \vT & \gT & \cellcolor{green!15} \vT & \gF & \gF & \gT & \cellcolor{green!15} \vT & \gF
            \end{array}
  \]
\section{Quantified Trees}
\label{sec.fixedrules}

If we can remove all the quantifiers from a PL tree, we can simply use the existing TFL tree rules, as we  have seen. This will be our goal. The problem is that we don't know which names (or objects) each variable should stand for in our valuations.

We will play it safe by assuming that an existential quantifier \emph{might} be referring to a new object, and so we will always use a new name. (Remember that an object can have more than one name, so if the new name needs to apply to an object we've already named, that's fine). This means that our existential quantifier rule will add new information to our tree, unlike every other rule.

A universal quantifier will always be referring to all existing objects. But we don't know which objects exist, so we will confine ourselves to using old names; names that we know refer to existing objects. As a universal quantifier applies to all existing objects, it might be used several times. This means that our universal quantifier rule will be reusable, unlike every other rule.

We will also need to decompose negated quantifiers, in the same way that we decomposed negated conjunctions and so forth. Here, we will take a short-cut, to simplify our PL trees.

\subsection{Negated Quantifiers}

Negated existential claims are quite similar to universals. They say that no instance is true, which is another way of saying that every instance is false. And in fact: \[\enot\qe \script{x} \ \meta{A} \eiff \qa \script{x}\ \enot\meta{A}\]
\noindent Similarly, a negated universal is similar to an existential. It says that not all instances are true, so at least one instance is false:
\[\enot\qa \script{x}\ \meta{A} \eiff \qe \script{x}\ \enot\meta{A}\]

We will take advantage of these two equivalences to transform all negated quantified formulas into non-negated quantified formulas.

\factoidbox{
\begin{center}
\begin{prooftree}
{not line numbering}
[\enot\qe\script{x}\ \meta{A}
 [\qa\script{x}\ \enot\meta{A} , just={$i$ \enot\esome}]
]
\end{prooftree}\hspace{40pt}
\begin{prooftree}
{not line numbering}
[\enot\qa\script{x}\ \meta{A}
 [\qe\script{x}\ \enot\meta{A} , just={$i$ \enot\eall}]
]
\end{prooftree}
\end{center}
}

For example, if $\enot\qeb x {Fx}$ is in the tree, we can decompose it to $\qab x {\enot Fx}$. And likewise we can decompose $\enot \qab z {Raz \eif Pz}$ to $\qen z {\enot (Raz \eif Pz)}$.

\subsection{Existential Quantifiers}

Our tree rule for decomposing existential quantifiers replaces all instances of the existential variable in the formula with our new object name:

\factoidbox{
	\begin{center}\begin{prooftree}
	{not line numbering}
	[\qe\script{x}\meta{A}, checked={\script{a}}
	 [\meta{A}\substitution{x}{a}, just={$i$ \esome \script{a}}
 	  [ , just={(where \script{a} is new})]
	 ]
	]
\end{prooftree}\end{center}
}

Just as \meta{A} stands in for any formula of PL, the \script{x} stands in for any variable, and \script{a} stands in for any name. The requirement that the name be \emph{new} means that the name chosen for the substitution instance must be a name that has not appeared \emph{anywhere} in the tree so far.

For example, consider this tree:

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[Fa, just={Root}
 [\qeb x {\enot Fx}, name=p2, checked=b, just={Root}
  [\enot Fb, just=$\exists b$:p2]
]]
\end{prooftree}\end{center}

On line (2), we replace $x$ with $b$ (rather than $a$), because $a$ is a name that is already in use. We want to say that \emph{something} is $F$, not necessarily that $a$ is $F$. Of course, $Fa$ could also be true: there could be more than one object that is $F$; and it is also possible for $a$ and $b$ to be names for the same object ($a = b$).

There is also a $b$ next to the check mark in line (2). When we mark the existential quantifier as decomposed, we add the name that we've used to replace the quantified variable, so we can trace our work more easily.

Consider this more complex example:

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
 [\qeb x {\qeb y { Rxy} \eif Rbx}, name=p1, checked=a, just={Root}
  [\qeb y {Ray} \eif Rba, grouped, name=p2, checked, just=$\exists a$:p1
   [\enot \qeb y {Ray} , name=p3, checked, just=$\eif$:p2
    [\qab y {\enot Ray} , just=$\enot\exists$:p3]
   ]
   [Rba, just=$\eif$:p2]
 ]]
\end{prooftree}\end{center}

On line (2), we decompose line (1) and can replace $x$ with any letter except $b$, which is already used on line (1). On line (2), the main connective is not $\qe$ but $\eif$, so we can't decompose it using our existential tree rule. When we finally have a quantifier as the main connective on line (4), it's now a universal quantifier. We need another rule to decompose this formula.

\subsection{Universal Quantifiers}

Our tree rule for decomposing universal quantifiers replaces all instances of the existential variable in the formula with an old object name:

\factoidbox{
	\begin{center}\begin{prooftree}
	{not line numbering}
	[\qa\script{x}\meta{A}, subs={\script{a}}
	 [\meta{A}\substitution{x}{a}, just={$i$ \eall \script{a}}
 	  [ , just={(where \script{a} is old})]
	 ]
	]
\end{prooftree}\end{center}
}

For a name to be `old' means that it has appeared \emph{somewhere} in the tree.

Unlike all the other tree rules, we don't decompose a universally quantified formula and then check it off, never to use it again. Because more than one name can appear in a tree, each universal formula can be used more than once.  We mark this by writing a $\backslash$ instead of a \checkmark next to the universal formula.\\

Here is an example illustrating the importance of decomposing a universally quantified formula multiple times:

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qab x {Fx \eand Gx}, name=p1, subs={a,b}, just={Root}
 [\enot Fa \eor \enot Gb, grouped, name=p2, checked, just={Root}
  [Fa \eand Ga, name=p3, checked, just=$\forall a$:p1
	[Fa, just=$\eand$:p3
	 [Ga, just=$\eand$:p3
		[\enot Fa, just=\eor:p2, close]
		[\enot Gb
		 [Fb \eand Gb, just=$\forall b$:p1, checked, name=p7
			[Fb, just=\eand:p7
			 [Gb, just=\eand:p7, close
			]]
		]]
	]]
]]]
\end{prooftree}\end{center}

On line (3) we replace the universally quantified variable with $a$ at line (1), and this helps to close one branch. But the other branch won't close until we take the $b$ instance as well on line (7).
Of course, we might have foreseen that we would need both a formula containing $a$ and one containing $b$ to close the tree, and replaced the quantified variable with $b$ on line (4); the tree would have worked just as well. But in general, we want to delay acting on universal quantifiers for as long as possible, for reasons we'll explain shortly.

\section{Completing your Tree}

%Our branch closure rules also remain unchanged. A branch closes if and only if it contains some formula \meta{A} along with its negation, \enot\meta{A}. We mark closed branches with an `\ensuremath\times'.

Although the connective, branching, and branch closing rules are identical to those in TFL, we will need to change our completion rule slightly.

%From TFL Trees
%\factoidbox{
%An open branch is \define{complete} iff all its complex formulas have been decomposed, as indicated by a check mark.
%
%A tree is \define{complete} iff all its branches are closed or complete.}

The TFL tree completion rule, given in \S\ref{sec.TFL.tree.completion}, said that a branch was complete if every complex formula has been decomposed, as indicated by a check mark. But universally quantified formulas may need to be decomposed several times -- once for each name in the tree. We need our completion condition to ensure that we've taken \emph{enough} instances.

For example, this should not count as a completed tree:

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qab x {Fx \eif Ga}, name=p1, subs=a, just={Root}
 [\enot Ga, just={Root}
  [Fb, just={Root}
	[Fa \eif Ga, checked, name=p4, just={$\eall a$:p1}
	 [\enot Fa, just={\eif}:p4]
	 [Ga, close]
	]
]]]
\end{prooftree}\end{center}

The universal quantifier on line (1) can be decomposed using $a$ and using $b$. If we did this, the tree would close:

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qab x {Fx \eif Ga}, name=p1, subs={a,b}, just={Root}
 [\enot Ga, just={Root}
  [Fb, just={Root}
   [Fa \eif Ga, checked, name=p4, just={$\eall a$:p1}
	[\enot Fa, just={\eif}:p4
	  [Fb \eif Ga, checked, name=p6, just={$\eall b$:p1}
	   [\enot Fb, close, just={\eif}:p6]
	   [Ga, close]
	  ]
	]
	[Ga, close]
]]]]
\end{prooftree}\end{center}

We don't want this tree to count as complete until it has decomposed line (1) using both $a$ and $b$. A true universal formula is true of \emph{every} object; we can't test that formula properly if we've only checked \emph{some} objects.

For an open branch to be complete, every universally quantified formula in that branch must be decomposed using \emph{every} name in the branch.

%\factoidbox{
%A branch is \define{complete} if and only if either (i) it is closed, or (ii) every resolvable formula in the branch has been resolved, and for every universal formula and every name \script{a} in the branch, the \script{a} instance of that universal formula has been taken.

%\pagebreak

\section{More PL Tree Examples}

A tautology can never be false. A tree can test if a formula can be false.\\
Is $(\enot \qeb x {Ax \eand  \enot Bx} \eif  \qab y {Ay \eif  By})$ a tautology?

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\enot(\enot \qeb x {Ax \eand \enot Bx} \eif \qab y {Ay \eif  By}), name=p1, checked, just={Root}
 [\enot \qeb x {Ax \eand \enot Bx}, name=p2, checked, just={$\enot\eif$:p1}
  [\enot \qab y {Ay \eif  By}, name=p3, checked, just={$\enot\eif$:p1}
   [\qen y {\enot (Ay \eif  By)}, name=p4, checked=a, just={$\enot\forall$:p3}
    [\enot (Aa \eif  Ba), name=p5, checked, just={$\exists a$:p4}
     [Aa , name=p6, just={$\enot \eif$:p5}
      [\enot Ba, name=p7, just={$\enot \eif$:p5}
       [\qan x {\enot ( Ax \eand \enot Bx)}, name=p8, subs={a}, just={$\enot\exists$:p2}
        [\enot ( Aa \eand \enot Ba), name=p9, just={$\forall a$:p8}
         [\enot Aa, close, name=p10, just={$\enot\eand$:p9}]
         [\enot\enot Ba, close, name=p11, just={$\enot\eand$:p9}]
       ]]
    ]]]
]]]]
\end{prooftree}\end{center}

The tree shows that the negated formula can never be true. This means that
the formula can never be false -- it is a tautology.\\

\noindent Is the argument `No flasks are not made of glass so all flasks are made of glass' valid?

%Using an intuitive symbolisation key, we symbolise this argument as:

$$\enot \qeb {x} {Fx \eand \enot Gx} \ \therefore  \ \qab{y} {Fy \eif Gy}$$

\noindent We check if the premises can be true while the conclusion is false:

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\enot \qeb x {Fx \eand \enot Gx}, name=p1, checked, just={Premise}
 [\enot \qab y {Fy \eif Gy}, name=p2, checked, just={Neg Conc}
  [\qab x {\enot (Fx \eand \enot Gx)}, name=p3, subs={a}, just={$\enot\exists$:p1}
   [\qeb y {\enot (Fy \eif Gy)}, name=p4, checked=a, just={$\enot\forall$:p2}
	[\enot (Fa \eif Ga), name=p5, checked, just={$\exists a$:p4}
	 [Fa , name=p6, just={$\enot\eif$:p5}
	  [\enot Ga , name=p7, just={$\enot\eif$:p5}
		[\enot (Fa \eand \enot Ga), name=p8, checked, just={$\forall a $:p3}
		 [\enot       Fa, name=p9a, close, just={$\enot\eand$:p8}]
		 [\enot \enot Ga, name=p9b, close, just={$\enot\eand$:p8}]
		]
	]]]
]]]]
\end{prooftree}\end{center}

\noindent It is impossible for the premises to be true and the conclusion false, so there is no counter-example, and the argument is valid.

%\pagebreak

\noindent Proof that $\qa y {\qe x {(Ryy \eif  Rxy)}}$ is a tautology:
\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\enot \qan y {\qeb x {Ryy \eif  Rxy}}, name=p1, checked, just={Root}
 [\qen y {\enot \qeb x {Ryy \eif  Rxy}}, name=p2, checked=a, just={$\enot\forall$:p1}
  [\enot \qeb x {Raa \eif  Rxa}, name=p3, checked, just={$\forall a$:p2}
   [\qab x {\enot (Raa \eif  Rxa)}, name=p4, checked=a, just={$\enot\exists$:p3}
	[\enot(Raa \eif  Raa)), name=p5, checked, just={$\exists a$:p4}
	 [Raa, just={$\enot\eif$:p5}
	  [\enot Raa, close, just={$\enot\eif$:p5}
	 ]]
  ]]]
]]
\end{prooftree}\end{center}

%The negated formula can never be true, so the formula is a tautology.\\

\newpage
\noindent Proof that $\qa{x}{\qa{y}{\qab{z}{(Rxy \eand  Ryz) \eif  Rxz}}}, \qab{x}{\enot Rxx} \ \therefore	\ \qa{x}{\qab{y}{Rxy \eif  \enot Ryx}}$ is valid:

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qan x {\qan y {\qab z {(Rxy \eand  Ryz) \eif  Rxz}}}, subs={a}, name=p1, just={Premise}
 [\qab x {\enot Rxx}, name=p2, subs={a}, just={Premise}
  [\enot \qan x {\qab y {Rxy \eif  \enot Ryx}}, name=p3, checked, just={Neg Conc}
	[\qen x {\enot \qab y {Rxy \eif  \enot Ryx}}, name=p4, checked=a, just={$\enot\forall$:p3}
	 [\enot \qab y {Ray \eif  \enot Rya}, name=p5, just={$\exists$a :p4}
	  [\qeb y {\enot (Ray \eif  \enot Rya)}, name=p6, checked=b, just={$\enot\forall$ :p5}
	   [\enot (Rab \eif  \enot Rba), name=p7, just={$\exists$b :p6}
		[Rab, just={$\enot\eif$:p7}
		 [\enot\enot Rba, name=p9, just={$\enot\eif$:p7}
		  [Rba, name=p10, just={$\enot\enot$:p9}
			[\qan y {\qab z {(Ray \eand  Ryz) \eif  Raz}}, subs={b}, name=p11, just={$\forall a$:p1}
			 [\qab z {(Rab \eand  Rbz) \eif  Raz}, subs={a}, name=p12, just={$\forall b$:p11}
			  [(Rab \eand  Rba) \eif  Raa, checked, name=p13, just={$\forall a$:p12}
			   [\enot Raa, name=p14, just={$\forall a$:p2}
				[\enot(Rab \eand  Rba), checked, name=p15, just={$\eif$:p13}
				 [\enot Rab, close, just={$\enot\eand$:p15}]
				 [\enot Rba, close, just={$\enot\eand$:p15}]
				]
				[Raa, close, just={$\eif$:p13}]
				]
			]]]]
		]]]
	]]]]
]]]
\end{prooftree}\end{center}

%It is impossible for the premises to be true and the conclusion false, so there is no counter-example, and the argument is valid.

\mathematics{The above argument is a proof from mathematics. It says that any relation that is transitive and anti-reflexive (e.g., the greater-than `$>$' and strict subset `$\subset$' relations) must also be anti-symmetric. %For example,  is transitive (if $A>B$ and $B>C$ then $A>C$), and anti-reflexive ($A\ngtr A$), so must also be anti-symmetric (if $A > B$ then $B \ngtr A$). %One of the big changes in mathematics at the moment is the increased emphasis on the formalisation of mathematical proofs into pure logic that can be checked by computers.
}
\pagebreak
The following argument is invalid:\\

\indent\indent\indent\indent\indent
$\qab{x}{\enot (\qeb{y}{Syx} \eand  \enot Ax)}$

\indent\indent\indent\indent\indent
$\qab{x}{\qeb{y}{Sxy} \eif  \enot Bx}$

\indent\indent\indent\indent\indent
$\therefore \ \qab{x}{Sxx \eif  (Ax \eand  Bx)}$

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qab x {\enot (\qeb y {Syx} \eand  \enot Ax)}, subs={a}, name=p1, just={Premise}
 [\qab x {\qeb y {Sxy} \eif \enot Bx}, name=p2, subs={a}, just={Premise}
  [\enot \qab x {Sxx \eif  (Ax \eand  Bx)}, name=p3, checked, just={Neg Conc}
   [\qeb x {\enot (Sxx \eif  (Ax \eand  Bx))}, name=p4, checked=a, just={$\enot\forall$:p3}
    [\enot (Saa \eif  (Aa \eand  Ba)), name=p5, checked, just={$\exists a$:p4}
     [Saa, name=p6, just={$\enot\eif$:p5}
	  [\enot (Aa \eand  Ba), name=p7, just={$\enot\eif$:p5}
		[\enot (\qeb y {Sya} \eand  \enot Aa), name=p8, checked, just={$\forall a$:p1}
		 [\enot \qeb y {Sya}, checked, name=p9, just={$\enot\eand$:p8}%, move by=4
		  [\qab y {\enot Sya}, subs={a}, name=p10, just={$\enot\exists$:p9}
		   [\enot Saa, close, just={$\forall a$:p10}]
		 ]]
		 [\enot \enot Aa, name=p9a, just={$\enot\eand$:p8}
		  [Aa, just={$\enot\enot$:p9a}, move by=1
		   [\enot Aa, close, just={$\enot\eand$:p7}]
		   [\enot Ba, just={$\enot\eand$:p7}
			[\qeb y {Say} \eif \enot Ba, checked=a, name=p11, just={$\forall a$:p2}
			 [\enot \qeb y {Say}, checked, name=p12, just={$\eif$:p11}
			  [\qab y {\enot Say}, subs={a}, name=p13, just={$\enot\exists$:p12}
			   [\enot Saa, close, just={$\forall a$:p13}]
			 ]]
			 [\enot Ba, open, just={$\eif$:p11}]
			]
		]]]]
    ]]]
]]]]
\end{prooftree}\end{center}

\noindent Fortunately the tree has produced a one-item counter-example. This will lead to a short counter-example and proof:\\

\noindent
\begin{tabular}{l ll lcc}
 Domain = $\{a\}$
& & \begin{tabular}{c|l}
	 $Sxy$     & a\\ \hline
	a & \vT
	\end{tabular}
& &  \begin{tabular}{l|ll}
				& $A$	& $B$ \\ \hline
	a	& \vT	& \vF \\
	\end{tabular}
\end{tabular}

$ $\\

\begin{tabular}{c c | ceeeeec }
$x$ & $y$ & $\qa x$ & $[\enot$ & $(\qe y$ & $[Syx]$ & $\eand$ & $\enot$ & $Ax)]$\\
\hline
$a$ & $a$ & \vT & \vT & \vT & \vT & \vF & \vF & \vT\\
\end{tabular}
$ $
\begin{tabular}{c c | ceeeec }
$x$ & $y$ & $\qa x$ & $[\qe y$ & $[Sxy]$ & $\eif$ & $\enot$ & $Bx]$\\
\hline
$a$ & $a$ & \vT & \vT & \vT & \vT & \vT & \vF
\end{tabular}

$ $\\

\begin{tabular}{c c | ceeeeec }
$x$ & $y$ & $\enot$ & $\qa x$ & $[Sxx$ & $\eif$ & $(Ax$ & $\eand$ & $Bx)]$\\
\hline
$a$ & $a$ & \vT & \vF & \vT & \vF & \vT & \vF & \vF
\end{tabular}

\pagebreak

\noindent $\qab {x} {\qeb{y}{Rxy} \eif  Fx}, 	\qab{x}{Fx \eif \enot Rxx} \ \therefore	\ \qa{x}{\qab{y}{Rxx \eor \enot Rxy}}$ is invalid:

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qab x {\qeb y {Rxy} \eif  Fx}, subs={a,b}, name=p1, just={Premise}
 [\qab x {Fx \eif \enot Rxx}, name=p2, subs={a}, just={Premise}
  [\enot \qan x {\qab y {Rxx \eor \enot Rxy}}, name=p3, checked, just={Neg Conc}
   [\qeb x {\enot (\qab y {Rxx \eor \enot Rxy})}, name=p4, checked=a, just={$\enot\forall$:p3}
	[\enot (\qab y {Raa \eor \enot Ray}), name=p5, checked, just={$\exists a$:p4}
	 [\qeb y {\enot (Raa \eor \enot Ray)}, name=p6, checked=b, just={$\enot\forall$:p5}
	  [\enot (Raa \eor \enot Rab), name=p7, checked, just={$\exists b$:p6}
		[\enot Raa, name=p8, just={$\enot \eor$:p7}
		 [\enot \enot Rab, name=p9, just={$\enot \eor$:p7}
		  [Rab, name=p10, just={$\enot \enot$:p9}
	[\qeb y {Ray} \eif  Fa, name=p11, checked, just={$\forall a$:p1}
	 [\enot \qeb y {Ray} , name=p12a, checked, just={$\eif$:p11}
	  [\qab y {\enot Ray} , name=p13a, subs={b}, just={$\enot\exists$:p12a}
	   [\enot Rab, close, just={$\forall b$:p13a}]
	 ]]
	 [Fa, name=p12b, just={$\eif$:p11}
	  [Fa \eif \enot Raa, name=p13b, checked, just={$\forall a$:p2}, move by=2
	   [\enot Fa, close, just={$\eif$:p13b}]
	   [\enot Raa, just={$\eif$:p13b}
		[\qeb y {Rby} \eif  Fa, name=q11, checked, just={$\forall b$:p1}
		 [\enot \qeb y {Rby} , name=q12a, checked, just={$\eif$:q11}
		  [\qab y {\enot Rby} , name=q13a, subs={a,b}, just={$\enot\exists$:q12a}
		   [\enot Rba, just={$\forall a$:q13a}
		    [\enot Rbb, open, just={$\forall b$:q13a}]
		 ]]]
	    [Fb, name=q12b, just={$\eif$:q11}
	     [\vdots]
	    ]
	   ]]
	  ]
	 ]
	]
		]]]
   ]]]]
]]]
\end{prooftree}\end{center}

\noindent While the branch under $Fb$ might continue, it can't affect our open branch. Our counter-example and proof is:\\

\noindent
\begin{tabular}{l ll ll}
Domain = $\{a, b\}$
& & \begin{tabular}{c|ll}
	 $Rxy$     & a & b \\ \hline
	a & \vF        & \vT  \\
	b & \vF        & \vF
	\end{tabular}
& &  \begin{tabular}{l|l}
	 & $F$  \\ \hline
	a & \vT          \\
	b & \vU
	\end{tabular}
\end{tabular}

$ $\\

\begin{tabular}{c c | ceeec | ceeec | ceeeeec }
$x$ &$y$&	$\qa x $ & $[\qe y$ & $ [Rxy] $ & $\eif$ & $Fx]$
		&	$\qa x $ & $[Fx$ & $\eif$ & $\enot$ & $Rxx]$
		& 	$\enot$ & $ \qa x $ & $\qa y $ & $[Rxx $ & $\eor $ & $\enot$ & $ Rxy]$
    \\
\hline
$a$ & $a$&	\brax{4}{\vT} & \brax{2}{\vT} & \vF & \braz{2}{\vT} & \mrow{2}{\vT}
		&	\brax{4}{\vT} & \mrow{2}{\vT} & \mrow{2}{\vT} & \mrow{2}{\vT} & \mrow{2}{\vF}
		& 	\mrow{4}{\vT} & \brax{4}{\vF} & \brax{2}{\vF} & \vF & \vT & \vT & \vF\\

$a$ & $b$&	$ $ & $ $ & \vT & $ $ & $ $
		&	$ $ & $ $ & $ $ & $ $ & $ $
		& 	$ $ & $ $ & $ $ & \vF & \vF & \vF & \vT\\

\cline{5-5}\cline{16-19}

$b$ & $a$&	$ $ & \brax{2}{\vF} & \vF & \braz{2}{\vT} & \mrow{2}{\vU}
		&	$ $ & \mrow{2}{\vU} & \mrow{2}{\vT} & \mrow{2}{\vT} & \mrow{2}{\vF}
		& 	$ $ & $ $ & \brax{2}{\vT} & \vF & \vT & \vT & \vF\\

$b$ & $b$&	$ $ & $ $ & \vF & $ $ & $ $
		&	$ $ & $ $ & $ $ & $ $ & $ $
		& 	$ $ & $ $ & $ $ & \vF & \vT & \vT & \vF\\
\end{tabular}

\pagebreak

\chapter{Tree Strategies}\label{ch:pl.tree.strategies}
\section{Order of Decomposition}

You can always decompose the complex formulas of a truth tree in any order you want. The resulting trees will all eventually give the same (or equivalent) results. But some trees are shorter, or easier to find good strategies to complete, or easier to complete without making mistakes. Here's the advice we gave for TFL trees:

\begin{earg}
\item Non-branching rules before branching.
\item Close branches quickly.
\item Simple formulas before complex.
\item Biconditionals last.
\end{earg}

All this still holds. However, we also have some quantifier-specific advice.

\begin{earg}
\item Negated Quantifiers are simple non-branching rules; do them early.
\item Existential Quantifiers after other non-branching rules.
\item Universal Quantifiers only when you have a clear plan for them.
\item Otherwise, delay Universal Quantifiers if there are many names.
\end{earg}

This advice isn't perfect, but it will generally serve you well.

Existential quantifiers generate new information and new possibilities. Every existential quantifier will add a new name. Negated quantifiers will either become existential quantifiers, to be decomposed immediately, or universal quantifiers, to be planned for and used wisely (or often).

 Because universal quantifiers can generate so many new formulas, you should either use them only when you have a clear plan, or when you are out of plans; at which point, use all the names, and see if anything useful appears!

\pagebreak
Let's test if $\qa x {Rax}, \qa x {\qa y {(Rxy \eif Ryx)}} \ \therefore \ \qa y {Rya}$ is valid. %The root will contain the premises, and the negation of the conclusion:

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qab x {Rax}, name=p1, just={Premise}
 [\qan x {\qab y {Rxy \eif Ryx}}, grouped, name=p2, just={Premise}
  [\enot \qab y {Rya}, grouped, name=p3, just={Neg Conc}
]]]
\end{prooftree}\end{center}

If we ignored (3) and decomposed our universals first, we'd get

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qab x {Rax}, subs={a}, name=p1, just={Premise}
 [\qan x {\qab y {Rxy \eif Ryx}}, subs={a}, name=p2, just={Premise}
  [\enot \qab y {Rya}, checked, name=p3, just={Neg Conc}
	[Raa, just={$\eall a$:p1}
	 [\qab y {Ray \eif Rya}, subs={a}, name=p5, just={$\eall a$:p2}
	  [Raa \eif Raa, name=p6, just={$\eall a$:p5}
		[\enot Raa, close, name=p7, just=$\eif$:{p6}]
		[Raa, just=$\eif$:{p6}
		 [\qeb y {\enot Rya}, checked=b, name=p8, just={$\enot \eall$: p3}
		  [\enot Rba, just={$\exists b$: p8}
		 ]]
		]
	]]]
]]]
\end{prooftree}\end{center}

The tree hasn't closed yet, and the new name $b$ on line (8) means we need to rethink our use of lines (1), (2) and (5). If we instead delayed our universals until we had a plan, we might get:

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qab x {Rax}, subs={b}, name=p1, just={Premise}
 [\qan x {\qab y {Rxy \eif Ryx}}, subs={a}, name=p2, just={Premise}
  [\enot \qab y {Rya}, checked, name=p3, just={Neg Conc}
	[\qeb y {\enot Rya}, checked=b, name=p4, just={$\enot \eall$: p3}
	 [\enot Rba, just={$\exists b$: p4}
		[Rab, just={$\eall b$:p1}
		 [\qab y {Ray \eif Rya}, subs={b}, name=p7, just={$\eall a$:p2}
		  [Rab \eif Rba, name=p8, just={$\eall b$:p7}
			[\enot Rab, close, just=$\eif$:{p8}]
			[Rba, close, just=$\eif$:{p8}]
		]]]
	]]
]]]
\end{prooftree}\end{center}

With line (5) giving us $\enot Rba$, we could see that line (2), which switches the order of the names, could cause a contradiction with $(Rab \eif Rba)$ if we also had $Rab$. And line (1) could give us $Rab$. So we had a plan for which names to substitute into lines (1) and (2) -- and with a little luck, our plan worked.
%The good news is that even if our plan didn't work, we could just try the next idea, but we've also increased our chances of a short, simple tree, and so fewer errors.

%Planning ahead can help make your trees more efficient. The general principle you should keep in mind is, if you have a choice for what resolvable formula to resolve, or what instance of a general formula to take, make a choice that will allow you to close branches more quickly.

\section{Truth Tree Complexities}

\subsection{Strategically Selecting Names}
In our last example, we had a plan for substituting our universal quantifiers by trying to create contradictions. This sort of strategy is important, particularly when you realise how long your tree could get if you just listed all possible substitutions. Lets try a more complex argument:
%Everyone is related to someone, if you are related to someone, they re related to you, If you are related to someone, and they are related to someone, you are related to that last person. \therefore you are related to yourself.
$$\qa x {\qe y {Rxy}},
\qa x {\qa y {Rxy \eif Ryx}} ,
\qa x {\qa y {\qa z {(Rxy \eand Ryz) \eif Rxz}}} \
\therefore \ \qa x {Rxx}$$

We'll start by decomposing all the existentials as quickly as we can:

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qan x {\qeb y {Rxy}}, subs={a}, name=p1, just={Premise}
 [\qan x  {\qab y {Rxy \eif Ryx}}, name=p2, just={Premise}
  [\qan x  {\qan y  {\qab z {(Rxy \eand Ryz) \eif Rxz}}}, name=p3, just={Premise}
   [\enot\qab x  {Rxx}, checked, name=p4, just={Neg Conc}
	[\qeb x {\enot Rxx}, checked=a, name=p5, just={$\enot\eall$:p4}
	 [\enot Raa, name=p6, just={$\exists a$:p6}
	  [\qeb y {Ray}, checked=b, name=p7, just={$\eall a$:p1}
	   [Rab, name=p8, just={$\exists b$:p7}
	]]]]
]]]]
\end{prooftree}\end{center}

Now we ask how we can get a contradiction with these formulas. $\enot Raa$ is our only negative formula, so we need to get $Raa$ from lines (2) or (3). If $Raa$ was the consequent of line (2), the full formula would be $Raa \eif Raa$, which doesn't seem useful? If $Raa$ was the consequent of line (3), the full formula would be $(Rab \eand Rba) \eif Raa$. So we'd need $Rab \eand Rba$. And we already have $Rab$! How can we get $Rba$? Well, line (2) can give us $Rab \eif Rba$, and we already have $Rab$. We have a plan!!

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}, line no shift=8}
[ \qab y {Ray \eif Rya}, subs={b}, name=p9, just={2\ $\eall a$}
 [Rab \eif Rba, name=p10, just={$\eall b$:p9}
  [\enot Rab, close, just={$\eif$:p10}]
  [Rba, name=p11, just={$\eif$:p10}
	[\qan y {\qab z {(Ray \eand Ryz) \eif Raz}}, checked=b, name=p12, just={3\ $\eall a$}
	 [\qab z {(Rab \eand Rbz) \eif Raz}, name=p13, checked=a, just={$\eall b$:p12}
	  [(Rab \eand Rba) \eif Raa, name=p14, just={$\eall a$:p13}
		[\enot(Rab \eand Rba), checked, name=p15, just={$\eif$:p14}
	     [\enot Rab, close, just={$\enot\eand$:p15}]
	     [\enot Rba, close, just={$\enot\eand$:p15}
		]]
		[Raa, close, just={$\eif$}:p14]
	]]]
]]]
\end{prooftree}\end{center}

%\aw{possibly a little more discussion, or a simpler example.}

\subsection{Infinite Trees}

Every decomposition of a TFL tree takes us closer to a completed tree, because we check of formulas as decomposed, and replace them with either one or two simpler formulas. TFL trees are guaranteed to be completed in a finite number of steps --- they will either close, or every formula will be decomposed into an atomic or negated atomic formula.

However, the universal quantifier rule can be applied to the same formula once for every name in the tree, and so if we keep generating new names, it is possible for trees to continue indefinitely without closing.

Consider a tree with two formulas in its root: $Raa, \qa{x}{\qeb{y}{Rxy}}$. We will have to decompose the universal, using the existing name `$a$'. And that will give us $\qeb{y}{Ray}$, which in turn will give us a new name `$b$', which we'll use to decompose the universal quantifier...

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[Raa, just={Root}
[\qan x {\qeb y {Rxy}}, name=p1, subs={a,b,c}, just={Root}
	[\qeb y {Ray}, just=1 $\forall a$, checked=b
	[Rab, just=2 $\exists b$
		[\qeb y {Rby}, just=1 $\forall b$, checked=c
		[Rbc, just=4 $\exists c$
			[\qeb y {Rcy}, just=1 $\forall c$, checked=d
			[Rcd, just=5 $\exists d$
				[\vdots]
			]]
		]]
	]]
]]
\end{prooftree}\end{center}

As the pattern makes clear, this tree will never close, but it will also never be complete. It will just keep decomposing instances of an existential with new names, then decomposing those instances of the universal, which in turn require a new existential, and so on.

The tree will never close, and its open branch is describing a model where all the formulas are true, but it is an infinite model. There's nothing illogical about that, but we certainly can't use truth tables to check formulas in that model. The good news is that in PL whenever there is an infinite model that makes a finite list of formulas true, there is also a finite model that does the same. The bad news is that we can't tell you how to find this finite model.

\logic{Congratulations, you've run into a limit of logic. PL is \emph{semi-decidable}. We can always tell if a set of formulas is inconsistent, but we can't always tell if a set of formulas is consistent -- any algorithm will sometimes go into an infinite loop rather than stopping with an answer.}

So, what should you do if your tree starts looping? First, check your tree decompositions, in case you've made a mistake. Then, once you are sure your tree is looping, stop extending the tree, draw a table with all the information you have \emph{before the loop starts}, and manually, creatively, add more information to the table until you can make all the formulas true. We can't give you precise instructions on how to do this, because there is no algorithm that will always work.

However, usually (particularly with exercises in this course) you can produce a counter-example which is a model with one or two names. For example, with the tree above, a one-name model where $Raa=1$ makes both $Raa$ and $\qa{x}{\qeb {y}{Rxy}}$ true. So would any two-name model with $Raa=1$ and $Rba=1$, or $Raa=1$ and $Rbb=1$. You can then check your counter-example using the techniques we discussed in Part \ref{part:models}.

Here is one counter-example, taken from the first 4 lines of the tree:\\

\noindent
\begin{tabular}{l l }
Domain = $\{a, b\}$
	\\

	& \begin{tabular}{l|ll} $Rxy$        & a & b \\ \hline
		a & \vT          & \vT  \\
		b & \vT          & \vU
		\end{tabular}
\end{tabular}
\ \ \  \begin{tabular}{c c | c | c c c }
$x$ & $y$ &  $Raa$ & $\qa x $ & $\qe y$ & $[Rxy]$ \\
\hline
$a$ & $a$ &\mrow{4}{\vT}&\brax{4}{\vT}&\brax{2}{\vT}& \vT\\
$a$ & $b$ & 		    &             &				& \vT\\
\cline{6-6}
$b$ & $a$ & 		    & 			  &\brax{2}{\vT}& \vT\\
$b$ & $b$ & 		    &             &				& \vU\\
\end{tabular} \\

\logic{In theory, to determine whether a set of formulas is consistent, or an argument valid, you don't need to produce a finite model. If a tree continues infinitely, there will always be an open branch. But in this course you must always produce a finite model.}

\subsection{An Old New Name}
There is one case where you can use a \emph{new} name when decomposing a universal quantifier. Suppose that you have no existential quantifiers, and no names already mentioned. Then there are no old names, and you can't decompose any of your universal quantifiers. In this one case, you can (after double-checking), use a new name to decompose a universal quantifier. Why? Because we can assume that the model we are reasoning about is not empty. Empty models aren't interesting. Consider the seemingly valid argument that `everything is made out of atoms, so something is made of atoms'. If there's nothing at all, then the premise could be true and the conclusion false. But truth trees assume there is always at least one object:

$$\qab{x}{Ax} \ \therefore \ \qeb{x}{Ax}$$

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qab x {Ax}, name=p1, just={Premise}
[\enot \qeb x {Ax}, name=p2, subs=b, just={Neg Conc}
	[\qab x {\enot Ax}, name=p3, just=$\enot\exists $:p2, checked=b
	 [\enot Ab, just=$\forall b$:p3
	  [Ab, close, just=$\forall b$: p1
	]]]
]]
\end{prooftree}\end{center}

%On line (4) we used a new letter `$b$', as there was not, and could not be, any old letters in the tree. We couldn't decompose our formulas unless we assumed there was at least one named object in our domain.

Is $\qe x {\qab y {Ryy \eif  Rxy}}$ a tautology?
\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\enot \qen x {\qab y {Ryy \eif  Rxy}}, name=p1, checked, just={Root}
 [\qab x {\enot \qab y {Ryy \eif  Rxy}}, name=p2, subs={a}, just={$\enot\exists$:p1}
  [\enot \qab y {Ryy \eif  Ray}, name=p3, checked, just={$\forall a$:p2}
   [\qeb y {\enot Ryy \eif  Ray}, name=p4, checked=b, just={$\enot\forall$:p3}
	[\enot( Rbb \eif  Rab), name=p5, checked, just={$\exists b$:p4}
	 [Rbb, just={$\enot\eif$:p5}
	  [\enot Rab, open, just={$\enot\eif$:p5}
	 ]]
  ]]]
]]
\end{prooftree}\end{center}

Is this valid: `All Unicorns have horns, so some Unicorns have horns'?

$$\qab{x}{Ux \eif Hx} \ \therefore\ \enot \qe{y}{Uy \eand Hy}$$

\begin{center}\begin{prooftree}
{close with=\ensuremath{\times}}
[\qab x {Ux \eif Hx}, subs={a}, name=p1, just={Premise}
[\enot \qeb y {Uy \eand Hy}, name=p2, checked, just={Neg Conc}
 [\qab y {\enot (Uy \eand Hy)}, name=p3, subs={a}, just={$\enot\exists$:p2}
  [Ua \eif Ha, checked, name=p4, just={$\forall a$:p1}
   [\enot (Ua \eand Ha), checked, name=p5, just={$\forall a$:p3}
	[\enot Ua, just={$\eif$:p4}
	 [\enot Ua, open, just={$\enot\eand$:p5}]
	 [\enot Ha]
	]
    [Ha
	 [\enot Ua]
	 [\enot Ha, close]
    ]
 ]]]
]]
\end{prooftree}\end{center}

A counter-example is: \ \ Domain = $\{a\}$. \ \
 \begin{tabular}{l|cc} & $Hx$ & $Ux$ \\ \hline
			a & \vU  & \vF  \\
 \end{tabular} $ $\\

 You can use new letters for your universals in other situations, but they will only make your tree longer, and never help it close or generate a counter-example. So don't. Just don't.

\section{Common Student Errors}

\subsection{Using Old Names}

The most frequent errors for trees in PL involve ignoring the restrictions on names when taking instances. Particular formulas (existentials and negated universals) require a \emph{new} name --- if the name appears anywhere in the branch at the time the existential is taken (including below it), it is not suitable for substitution via these rules.

For example, this tree contains a mistake in a quantifier rule. See if you can spot it:

\begin{prooftree}
{close with=\ensuremath{\times}}
[\qan x {\qeb y {\enot Rxy}}, subs={a}
 [Rab, grouped
	[\qeb y {\enot Ray}, just=1 $\forall$, checked=b
	 [\enot Rab, just=3 $\exists$, close%={2, 4}
	]]
]]
\end{prooftree}

Line (3) here is fine; but at line (4), this tree uses the name `$b$' to decompose the existential on line (3), even though `$b$' had already appeared in line (2). The existential rule requires a new name. The correct version of this tree would remain open. (It will extend infinitely.)

\subsection{Main Connectives}

You can only ever decompose the main connective of a formula. If you have a formula like $\qa x \qe y (\enot Ryx) \eand (Fa \eif Fb)$ you can't decompose the universal quantifier. This formula is a conjunction, so the only decomposition rule possible is that for conjunction.

It's often tempting to decompose a quantifier that's not the main connective. First, you can't. The rules don't work that way. Second, there are several ways that this can cause trouble. For instance, an existential quantifier within the scope of either a negation or the antecedent of a conditional will become a universal quantifier by the time the formula is decomposed. Second, if a quantifier is inside the scope of another quantifier, decomposing the inner quantifier first is effectively moving the inner quantifier outside the other quantifier. This quantifier scope shift is particularly problematic for an existential quantifier inside a universal quantifier.

It may help you to remember this by remembering our earlier example that `Every day someone is struck by lightning' is true, but `Someone is struck by lightning every day' is false, as different people are struck each day.

\subsection{Decomposing Universals Only Once}

It's very easy to forget that a universal quantifier can be decomposed multiple times in a tree. And often a single use will close some or all branches. But if there's an open branch, you'll need to identify every name used in that branch, and make sure that every universal quantifier in that branch is decomposed for every name. This is important for populating the counter-example, and also because occasionally it will close a seemingly open branch.

\subsection{Negating Formulas in the Root}
When testing consistency, we want to check if all the formulas can be true together. So no formula is negated. When testing validity, we want to check if all the premises can be true and the conclusion false (a counter-example). So we negate the conclusion only. When testing if a formula is a logical truth, we want to check if it can be false, so we negate the formula. It is very easy to tangle these up - particularly to forget to negate the conclusion of an argument. Then the information in the root of your tree is rotten. And a tree with a rotten root won't turn out well.

\subsection{Reading off Counter-examples incorrectly}

When you read off a counter-example from an open branch, make sure that you only trace up the tree towards the root. Do not use any atomic formulas that are on other branches, even if they are also open. If a name doesn't appear on your chosen open branch, its not needed in the counter-example. All the predicates in the root are needed, however.

Once you have your list of names from the open branch, and predicates from the root, draw up your tables -- one for all the one-place predicates, and one for each two-place predicate. Then fill in the values for each atom in your open branch. Any cell in the tables that isn't filled with a \vT\ or \vF\ is then filled with a \vU.

When you complete your partial predicate truth table, you should be able to fill in all the cells even with the missing truth values. If you need a truth value to calculate a row, check if you didn't decompose all names in one of the universal quantified formulas, as that's the most likely way to skip generating a needed atomic formula.

%\subsection{Final Tips}
%\begin{itemize}
%\item Negate your conclusion.
%
%\item Know your decomposition rules.
%
%\item Branch rules before column rules.
%
%\item Re-use your universal quantifiers.
%\end{itemize}

\pagebreak
\practiceproblems

\noindent\solutions
\problempart
\label{pr.PL.trees.tautology}
Use a tree to test whether the following formulas are tautologies. If they are not tautologies, describe a model on which they are false.
\begin{earg}
\item $\qa{x}{\qab{y}{Gxy \eif \qeb{z}{Gxz}}}$
\item $\qab{x}{Fx} \eor \qab{x}{Fx \eif Gx}$
\item $\qab{x}{Fx \eif (\enot Fx \eif \qab{y}{Gy}}$
\item $\qeb{x}{Jx} \eiff \enot \qab{x}{\enot Jx}$
\item $\qeb{x}{Fx \eor \enot Fx}$
\item $\qab{x}{Fx \eor Gx} \eif (\qab{y}{Fy} \eor \qeb{x}{Gx})$
\end{earg}

\noindent\solutions
\problempart
\label{pr.PL.trees.validity}
Use a tree to test whether the following arguments are valid. If they are not, give a model as a counterexample.
\begin{earg}
\item $Fa$, $Ga$ \therefore\ $\qab{x}{Fx \eif Gx}$
\item $Fa$, $Ga$ \therefore\ $\qeb{x}{Fx \eand Gx}$
\item $\qa{x}{\qeb{y}{Lxy}}$ \therefore\ $\qe{x}{\qab{y}{Lxy}}$
\item $\qeb{x}{Fx \eand Gx}$, $Fb \eiff Fa$, $Fc \eif Fa$ \therefore\ $Fa$
\item $\qa{x}{\qeb{y}{Gyx}}$ \therefore\ $\qa{x}{\qeb{y}{Gxy \eor Gyx}}$
\end{earg}

\noindent\problempart
\label{pr.PL.trees.translation.and.validity}
Translate each argument into PL, then use a tree to evaluate for validity. If they are invalid give a model as a counterexample.
\begin{earg}
\item Every logic student is studying. Patrick is not studying. Therefore, Patrick is not a logic student.
\item Kane Williamson is a New Zealand male athlete. Therefore, some athletes are New Zealand.
\item The All Blacks are going to win the game. Every team who wins the game will be celebrated. Therefore, the All Blacks will be celebrated.
\item The All Blacks are going to win the game. Therefore, the Springboks are not going to win the game.
\item All cats make Deborah sneeze, unless they are hairless. Some hairless cats are cuddly. Therefore, some cuddly things make Deborah sneeze.
\end{earg}

\end{document}