<!DOCTYPE book [
<!ENTITY  version        "4.0-beta10"         >

<!ENTITY  source.file    "&version;.tar.gz"         >
<!ENTITY  linux64.file   "bali-phy-&version;-linux64.tar.gz"         >
<!ENTITY  win32.file     "bali-phy-&version;-win32.tar.gz"         >
<!ENTITY  win64.file     "bali-phy-&version;-win64.tar.gz"         >
<!ENTITY  mac64.file     "bali-phy-&version;-mac64.tar.gz"         >

<!ENTITY  repo.url       "https://github.com/bredelings/BAli-Phy" >
<!ENTITY  source.url     "&repo.url;/archive/refs/tags/&source.file;" >
<!ENTITY  linux64.url    "&repo.url;/releases/download/&version;/&linux64.file;" >
<!ENTITY  win64.url      "&repo.url;/releases/download/&version;/&win64.file;" >
<!ENTITY  mac64.url      "&repo.url;/releases/download/&version;/&mac64.file;" >

<!ENTITY  install.prefix   "~/Applications"         >
<!ENTITY  install.path     "&install.prefix;/bali-phy-&version;"         >
<!ENTITY  exe.path         "&install.path;/bin/bali-phy"         >
<!ENTITY % sgml.features "IGNORE">
<!ENTITY % xml.features "INCLUDE">

<!ENTITY % dbcent 
	 PUBLIC "-//OASIS//ENTITIES DocBook Character Entities V4.5//EN"
	 "/usr/share/xml/docbook/schema/dtd/4.5/dbcentx.mod">
%dbcent;

<!ENTITY % ent-mmlalias
      PUBLIC "-//W3C//ENTITIES Aiases for MathML 2.0//EN"
             "/usr/share/xml/schema/w3c/mathml/dtd/mmlalias.ent" >
%ent-mmlalias;
]>
<article xmlns="http://docbook.org/ns/docbook" version="5.0" 
         xmlns:mml="http://www.w3.org/1998/Math/MathML"
	 xml:lang="en">
  <info><title><application>BAli-Phy</application> User's Guide v&version;</title>
    
    <author><personname><firstname>Benjamin</firstname><surname>Redelings</surname></personname></author>
  </info>

  <section xml:id="intro"><info><title>Introduction</title></info>
    <para><application>BAli-Phy</application> is a Unix command line program that is developed primarily on Linux.  <application>BAli-Phy</application> also runs on Windows and Mac OS X, but it is not a GUI program and so you must run it in a terminal.  Therefore, you might want to keep a <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.ee.surrey.ac.uk/Teaching/Unix">Unix tutorial</link> or <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.rain.org/~mkummel/unix.html">Unix cheat sheet</link> handy while you work.
    </para>

    <para>In addition to the main <command>bali-phy</command> executable, <application>BAli-Phy</application> comes with a collection of small command-line utilities such as <command>alignment-cat</command>, <command>trees-consensus</command>, etc.  These utilities can be used to process alignments, assemble data sets, and summarize the results of MCMC.
    </para>
  </section>

  <section xml:id="installation"><info><title>Installation</title></info>

  <section xml:id="pre-requisites"><info><title>Hardware requirements</title></info>
    
    <para>
      We typically run <application>BAli-Phy</application> on workstations with at least 8Gb of RAM and 2 cores.  More cores will allow you to run more MCMC chains at once, and more RAM will allow you to run larger data sets.  However, it is often easier and faster to run BAli-Phy on a (Linux) computing cluster, if you have one available.
    </para>

    <para>
    </para>
  </section>

  <section xml:id="upgrades"><info><title>Upgrades</title></info>
  <para>If you have previously installed bali-phy, you do not have to remove the old version before installing the new version.  Simply follow the installation instructions for the new version.  If you are manually adding the new version of bali-phy to your PATH, just make sure that the new version comes before the old version in the PATH, or remove the old version from the PATH.</para>

  <para>In order to remove an older version, simply delete the directory <filename>bali-phy-<replaceable>oldversion</replaceable></filename>.  This will completely uninstall the old version from the system. BAli-Phy does not create hidden files that will remain after you remove its directory.</para>
  </section>

  <section><info><title>Install on MS Windows</title></info>
    <para>First check that you have a 64-bit version of the Windows operation system installed. The executables for download will only run on a 64-bit installation of Windows.  </para>
    <section><info><title>Install a Unix command line: Cygwin (recommended)</title></info>
    <para>
       Before you can use <application>BAli-Phy</application> on Windows, you need to install a Unix command-line environment.  
       We recommend installing <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.cygwin.com/install.html">Cygwin</link>:
<itemizedlist>
<listitem>Run the Cygwin installer <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.cygwin.com/setup-x86_64.exe"><filename>setup-x86_64.exe</filename></link>. </listitem>
<listitem>In the installer, add the following extra packages: <userinput>R</userinput>, <userinput>gnuplot</userinput>, <userinput>perl</userinput>, <userinput>python3</userinput>, <userinput>wget</userinput>, and <userinput>nano</userinput>.</listitem>
</itemizedlist>
       Its easiest to find extra packages if you set the View to "Full" and enter each package name in the Search box.  
       After you run the installer, you can access the Unix command line environment by running the Cygwin shell (not the normal windows command line).  
       You can run the installer again to add more packages.
    </para>

    <para>BAli-Phy uses Windows-style filenames (such as <filename>C:\</filename>) because it is compiled as a native windows executable.  However, the Cygwin shell uses UNIX-style filenames.
<informaltable>
<tgroup cols="2">
<colspec colnum="1" colname="col1" colwidth="1*"/>
<colspec colnum="2" colname="col2" colwidth="1*"/>
<thead><row>
<entry>UNIX-style</entry>
<entry>Windows-style</entry>
</row></thead>
<tbody>
<row><entry>/home/<emphasis>username</emphasis></entry><entry>C:\cygwin64\home\<emphasis>username</emphasis></entry></row>
<row><entry>~/file</entry><entry>C:\cygwin64\home\<emphasis>username</emphasis>\file</entry></row>
<row><entry>/cygdrive/c/file</entry><entry>C:\file</entry></row>
</tbody>
</tgroup>
</informaltable>
You can use the <userinput>cygpath</userinput> program to convert between UNIX and Windows filenames:
<screen><prompt>%</prompt> cygpath -w ~/Applications
C:\cygwin64\home\<emphasis>username</emphasis>\Applications\
</screen>
</para>
    <note>If you supply UNIX-style filenames to BAli-Phy, then it will complain "<emphasis role="strong">file does not exist!</emphasis>".</note>

  </section>
</section>

    <section><info><title>Install on Mac OS X</title></info>
    <section><info><title>Install BAli-Phy using homebrew (recommended) </title></info>
    <para>First install the <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://developer.apple.com/xcode/">XCode</link> (version 11 or higher) command line tools:
    <screen><prompt>%</prompt> <userinput>xcode-select --install</userinput></screen>

    Then install <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://brew.sh/">homebrew</link> and use homebrew to compile and install <command>bali-phy</command>:
<screen><prompt>%</prompt> <userinput>brew tap brewsci/bio</userinput>
<prompt>%</prompt> <userinput>brew install bali-phy</userinput></screen>
Check that the executable runs:
<screen><prompt>%</prompt> <userinput>bali-phy --version</userinput></screen>
If you install with homebrew, you don't need to do anything extra to put bali-phy in your PATH.
    </para>
    </section>

    <section><info><title>Install BAli-Phy using executables from website (alternative)</title></info>
    <para>
      Open a windows in the Terminal app to access the UNIX command line.  Then download and extract the executables:
      <screen><prompt>%</prompt> <userinput>mkdir -p &install.prefix;</userinput>
<prompt>%</prompt> <userinput>cd &install.prefix;</userinput>
<prompt>%</prompt> <userinput>curl -LO &mac64.url;</userinput>
<prompt>%</prompt> <userinput>tar -zxf &mac64.file;</userinput></screen>
      Check that the executable runs:
      <screen><prompt>%</prompt> <userinput>~/Applications/bali-phy-&version;/bin/bali-phy --version</userinput></screen>
      You still need to add it to your PATH as described in <xref linkend="path"/>.
    </para>

    </section>

    <section><info><title>Install programs used by <command>bp-analyze</command> using homebrew</title></info>
    <para>
      You can install <application>gnuplot</application> via homebrew:
<screen><prompt>%</prompt> <userinput> brew install gnuplot</userinput></screen> 
You can install <application>R</application> via homebrew:
<screen><prompt>%</prompt> <userinput> brew tap caskroom/cask</userinput>
<prompt>%</prompt> <userinput> brew cask install xquartz</userinput>
<prompt>%</prompt> <userinput> brew install r</userinput></screen>
However, note that this might conflict with R installed from other places, such as <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://mran.microsoft.com/open/">MRAN</link>.
</para>
    </section>
    <section><info><title>Install some of the programs used for viewing the results using homebrew</title></info>
      <para>
	<!-- This might be a better formula https://github.com/tseemann/homebrew-bioinformatics-linux/blob/master/figtree.rb
	     I could copy it to bredelings/bioinformatics ...
	-->
	You can install Figtree with homebrew:
	<screen><prompt>%</prompt> <userinput>brew tap caskroom/cask</userinput>
<prompt>%</prompt> <userinput>brew cask install figtree</userinput></screen>
	However, Seaview and Tracer don't have homebrew packages at the moment.
      </para>
    </section>
    </section>

    <section><info><title>Install on Linux</title></info>

    <section><info><title>Install BAli-Phy using <command>apt-get</command></title></info>
    BAli-Phy is available on Ubuntu <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://launchpad.net/ubuntu/+source/bali-phy/">("Cosmic Cuttlefish" or later)</link>, and Debian (<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://packages.debian.org/search?keywords=bali-phy&amp;searchon=names&amp;section=all">testing and unstable</link>).
    <screen><prompt>%</prompt> <userinput>sudo apt-get install bali-phy</userinput></screen>
    Check that the executable runs:
    <screen><prompt>%</prompt> <userinput>bali-phy --version</userinput></screen>
    If you install with <command>apt-get</command>, you don't need to do anything extra to put bali-phy in your PATH.
    </section>

    <section><info><title>Install BAli-Phy using executables from website (alternative)</title></info>

    <para>First install <command>wget</command>.  If you have Debian or Ubuntu Linux, type:
    <screen><prompt>%</prompt> <userinput>sudo apt-get install wget</userinput></screen>
    </para>
    <para>
      Then download and extract the executables:
      <screen><prompt>%</prompt> <userinput>mkdir -p &install.prefix;</userinput>
<prompt>%</prompt> <userinput>cd &install.prefix;</userinput>
<prompt>%</prompt> <userinput>wget &linux64.url;</userinput>
<prompt>%</prompt> <userinput>tar -zxf &linux64.file;</userinput></screen>
      Second, check that the executable runs:
      <screen><prompt>%</prompt> <userinput>~/Applications/bali-phy-&version;/bin/bali-phy --version</userinput></screen>
      You still need to add it to your PATH as described in <xref linkend="path"/>.
    </para>
    </section>
    <section><info><title>Install programs used by <command>bp-analyze</command></title></info>
    <para>If you have Debian or Ubuntu Linux, you can install other recommended programs by typing:
    <screen><prompt>%</prompt> <userinput>sudo apt-get install gnuplot</userinput>
<prompt>%</prompt> <userinput>sudo apt-get install r-base</userinput></screen>
    </para>
    </section>
    <section><info><title>Install programs used to view the results</title></info>
    <para>
<screen><prompt>%</prompt> <userinput>sudo apt-get install seaview</userinput>
<prompt>%</prompt> <userinput>sudo apt-get install figtree</userinput></screen>
    However, there isn't a Debian or Ubuntu package for Tracer at the moment.
</para>
    </section>
    </section>

    <section xml:id="path"><info><title>Add BAli-Phy to your <envar>PATH</envar></title></info>

    <section><title>Is bali-phy in your PATH already?</title>
<para> First check if the executable is in your PATH.
<screen><prompt>%</prompt> <userinput>bali-phy --version</userinput></screen>
If this shows version info, then <command>bali-phy</command> is already in your PATH and you can skip this section.  This should be true if you installed <command>bali-phy</command> using a package manager such as homebrew or apt, or if you've already added it to your PATH.</para>
<para>If bali-phy is not in your path, then you should see:
<screen><prompt>%</prompt> <userinput>bali-phy --version</userinput>
bali-phy: command not found.</screen>
If bali-phy is not in your PATH, then continue with this section.
</para>
    </section>
    <section><title>Quick version</title>
<para>Add <command>bali-phy</command> to your PATH, so that the shell knows where to find it.  This command only affects the terminal in which it is typed, and will not affect new terminals:
<screen><prompt>%</prompt> <userinput>export PATH=~/Applications/bali-phy-&version;/bin:&#36;PATH</userinput></screen>
To set the PATH automatically for new terminals, type:
<screen><prompt>%</prompt> <userinput>test -r ~/.bash_profile &#38;&#38; echo 'export PATH=~/Applications/bali-phy-&version;/bin:&#36;PATH' &#62;&#62; ~/.bash_profile</userinput>
<prompt>%</prompt> <userinput>echo 'export PATH=~/Applications/bali-phy-&version;/bin:&#36;PATH' &#62;&#62; ~/.profile</userinput></screen>
This will affect new terminals only after you log out and log back in though.</para>
<para>
Now check that the executable runs:
<screen><prompt>%</prompt> <userinput>bali-phy --version</userinput></screen>
If it does, then your PATH is set up correctly, and you can probably skip the rest of this section. 
</para>
    
    </section>
      <section><title>I have a path?</title>
      <para>
	If you installed <application>BAli-Phy</application> to the directory
	<filename>&install.prefix;</filename>, then you can run
	bali-phy by typing <command>&exe.path;</command>.
	However, it would be much nicer to simply type
	<command>bali-phy</command> and let the computer find the
	executable for you.  This can be achieved by putting the directory
	that contains the <application>BAli-Phy</application> executables into
	your "path".  	The "path" is a colon-separated list of directories that is
	searched to find program names that you type.  It is stored in an
	environment variable called <envar>PATH</envar>.
	</para>
      <para>
	Setting your <envar>PATH</envar> is also a pre-requisite for running
	the <command>bp-analyze</command> script to summarize your
	MCMC runs.
      </para>
      </section>

      <section><title>Examining your <envar>PATH</envar></title>
      <para>
	You can examine the current value of
	this environment variable by typing:
	<screen><prompt>%</prompt> <userinput>echo &#36;PATH</userinput></screen>
	We will assume that you extracted the bali-phy archive in
	<filename>&install.prefix;</filename> and so you want to add
	<filename>&#36;HOME/Applications/bali-phy-&version;/bin</filename>
	to your <envar>PATH</envar>.  (If you installed to another directory,
	replace <filename>&#36;HOME/Applications/bali-phy-&version;/</filename> with that directory.)
      </para>
      </section>

      <section><title>Adding BAli-Phy to your <envar>PATH</envar></title>
      <para>The commands
	for doing this depend on what "shell" you are using.  Type
	<command>echo &#36;SHELL</command> to find out. If your
	shell is <command>sh</command> or 
	<command>bash</command> then the command looks like this: 
	<screen><prompt>%</prompt> <userinput>PATH=&#36;HOME/Applications/bali-phy-&version;/bin:&#36;PATH</userinput></screen>
	If your shell is <command>csh</command> or
	<command>tcsh</command>, then the command looks like this:
	<screen><prompt>%</prompt> <userinput>setenv PATH &#36;HOME/Applications/bali-phy-&version;/bin:&#36;PATH</userinput></screen>
	Note that these commands will only affect the window you are typing
	in, and will vanish when you reboot.   
      </para>
      </section>

      <section><title>Making the change stick</title>
	<para>
	  To make this change survives when you logout or reboot, open
	  your shell configuration file in a text editor, and add the
	  command on a line by itself.  This will ensure that it is
	  run every time you log in.
	</para>

	<para>To find the right configuration file, look in your &#36;HOME directory
	  for <filename>.profile</filename> (for the Bourne shell <command>sh</command>), 
	  <filename>.bash_profile</filename> (for BASH), or
	  <filename>.login</filename> (for tcsh).  You may have to
	  create the file if it is not present.  On Cygwin, you should
	  put the change in the file <filename>.bashrc</filename>.
	</para>

	<para>If you do not know which directory is your home
	directory, you can find its full name by typing:
	<screen><prompt>%</prompt> <userinput>echo &#36;HOME</userinput></screen>
	</para>
      </section>
    </section>

    <section xml:id="tests"><info><title>Test the installed software</title></info>
    <para>In order to determine that the software has been correctly installed, and the <envar>PATH</envar> has been correctly set, run the following commands:
    <screen><prompt>%</prompt> <userinput>cp &install.path;/share/doc/bali-phy/examples/sequences/5S-rRNA/25.fasta .</userinput>
<prompt>%</prompt> <userinput>bali-phy 25.fasta --iter=150</userinput>
<prompt>%</prompt> <userinput>bali-phy 25.fasta --iter=150</userinput>
<prompt>%</prompt> <userinput>bp-analyze 25-1 25-2</userinput></screen>
    </para>
    <para>Furthermore, the directories <filename>25-1</filename> and <filename>25-2</filename> should contain a file called <filename>C1.log</filename>.  You should be able to load these files in Tracer, although the chain will not really have converged yet.</para>
    </section>


    <section xml:id="software_req"><info><title>Install programs used for viewing the results</title></info>

    <para>
      <itemizedlist>
	<listitem>
	  <para>
	    <link xmlns:xlink="http://www.w3.org/1999/xlink"
		  xlink:href="http://tree.bio.ed.ac.uk/software/tracer/">
	      Tracer
	    </link>
	    :  MCMC parameter/diagnostic viewer.
	  </para>
	</listitem> 

	<listitem>
	  <para>
	    <link xmlns:xlink="http://www.w3.org/1999/xlink"
		  xlink:href="http://tree.bio.ed.ac.uk/software/figtree/">
	      FigTree
	    </link>
	    : Phylogeny Viewer
	  </para>
	</listitem>
      
	<listitem>
	  <para>
	    <link xmlns:xlink="http://www.w3.org/1999/xlink"
		  xlink:href="http://pbil.univ-lyon1.fr/software/seaview.html">
	      SeaView
	    </link>
	    : Alignment viewer.
	  </para>
	</listitem>

    </itemizedlist>
    </para>

    </section>
    </section>


  <section xml:id="running"><info><title>Running the program</title></info>
    

    <para>Here are some examples and explanations of how to run <command>bali-phy</command>.  You can get an overview of command line options by running <command> bali-phy --help</command>.</para>
<para>We recommend running multiple chains in parallel for each command, because 
<orderedlist>
  <listitem>You can combine the samples, leading to faster run times.</listitem>
  <listitem>You can compare the runs to determine if the chains have converged.</listitem>
</orderedlist>
 
This can be done simply by starting several instances of the program, and does not require using MPI or special command-line options.
</para>

    <section><info><title>Quick Start</title></info>
      
      <para>The simplest way to run <command>BAli-Phy</command> is
      to type all the arguments on the command line:
      <screen><prompt>%</prompt> <userinput>bali-phy sequences.fasta</userinput></screen>
      You can run a traditional fixed-alignment Bayesian tree inference by adding <userinput>-I none</userinput>:
      <screen><prompt>%</prompt> <userinput>bali-phy sequences.fasta -I none</userinput></screen>
      You can also specify a character set for analysis:
      <screen><prompt>%</prompt> <userinput>bali-phy sequences.fasta:1-30,90-100</userinput></screen>
      </para>
    </section>

    <section>
      <info><title>Input</title></info>
      <para>Sequence files can be in FastA or PHYLIP format.  FASTA format prefixes sequence names with "&gt;":
    </para>
      <programlisting>>human       this is a comment and is not part of the sequence name
CTGACTCCTGAGGAGAAGTCTGCCGTTACTGCCCTGTGGGGCAAGGTGAACGTGGATGAA
GTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTGGTCTACCCTTGGACCCAGAGGTTCTTT
>tarsier     this is also a comment
CTGACTGCTGAAGAGAAGGCCGCCGTCACTGCCCTGTGGGGCAAGGTAGACGTGGAAGAT
GTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTCGTCTACCCATGGACCCAGAGGTTCTTT
>bushbaby
CTGACTCCTGATGAGAAGAATGCCGTTTGTGCCCTGTGGGGCAAGGTGAATGTGGAAGAA
GTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTTGTCTACCCATGGACCCAGAGGTTCTTT
>hare
CTGTCCGGTGAGGAGAAGTCTGCGGTCACTGCCCTGTGGGGCAAGGTGAATGTGGAAGAA
GTTGGTGGTGAGACCCTGGGCAGGCTGCTGGTTGTCTACCCATGGACCCAGAGGTTCTTC
</programlisting>
<para>If the sequence-name line contains a space, BAli-Phy treats everything after the space as a comment.</para>
<para>The sequences in the file do not need to be aligned unless you fix the alignment with <userinput>-I none</userinput>.</para>
<para></para>

      
    </section>

    <section><info><title>Command line options</title></info>
      
    <para>Sensible defaults are supplied for command line options that are not specified.  For example, if <filename>sequences.fasta</filename> contains DNA sequences, then
    <screen><prompt>%</prompt> <userinput>bali-phy sequences.fasta</userinput></screen>
    is equivalent to
    <screen><prompt>%</prompt> <userinput>bali-phy sequences.fasta -A DNA -S tn93 -I rs07</userinput></screen>
    Default values that are used will always be displayed on the screen and in the output files so that you do not have to guess.  You can specify a more complex substitution model using the <userinput>-S</userinput> option.  You will generally need to write the substitution model inside single quotes unless it is just a single word.

    <screen><prompt>%</prompt> <userinput>bali-phy sequences.fasta -S 'lg08&nbsp;+>&nbsp;Rates.gamma&nbsp;+>&nbsp;inv'</userinput></screen>
    Every short option like <userinput>-S</userinput> has an equivalent long option like <userinput>--smodel</userinput>.
    To see the most frequently-used command-line options, you can run
    <screen><prompt>%</prompt> <userinput>bali-phy help</userinput></screen>
    </para>

    </section>

   <section><info><title>Option files (Scripts)</title></info>
      
      <para>
	In addition to using the command line, you may also specify
	options in a file. Option files also use the long form of command line options.
	Each option is given on its own line using the syntax "<userinput>option =
	value</userinput>" instead of the syntax "<userinput>--option
	value</userinput>".  The value can be blank if the option does not take
	an argument. The <userinput>align</userinput> option indicates sequence files.
	Lines that begin with # are comments, and blank lines are ignored.
      </para>

	<para>
	  For example, consider the following
	  option file:
	  <programlisting># sequence data for 3 genes/partitions
align = ITS1.fasta
align = 5.8S.fasta
align = ITS2.fasta

# linked substitution model for 1st and 3rd partition
smodel = 1,3:tn93&nbsp;+>&nbsp;Rates.free(n=3)

# substitution model for 2nd partition
smodel = 2:tn93

# indel model for second partition
imodel = 2:none

# linked scale for 1st and 3rd partition
scale = 1,3:

# choose a name for output directories
name = ITS-analysis1
</programlisting>
Options files are specified with the <userinput>-c <replaceable>option_file</replaceable></userinput> option:
	<screen><prompt>%</prompt> <userinput>bali-phy -c analysis1.txt</userinput>                           # run the analysis
<prompt>%</prompt> <userinput>bali-phy -c analysis1.txt --name ITS-analysis1b</userinput>     # override the name</screen>
        Options given on the command line will override values given in the option file.
	</para>
	<!-- para>
	  The file <filename>~/.bali-phy</filename> is a special
	  option file called the <emphasis>configuration
	    file.</emphasis>  If it exists, it is always loaded.
	  Options given on the command line or an option file 
	  override values given in <filename>~/.bali-phy</filename>. 
	</para -->
    </section>

    <section xml:id="cluster"><info><title>Running on computing clusters</title></info>
    <para>
      Running <command>bali-phy</command> on a computing cluster is
      not necessary, but can speed up the analysis dramatically.
      This is because a cluster allows you to run several
      <emphasis>independent</emphasis> MCMC chains simultaneously and
      pool the resulting samples.  You can run multiple chains
      simultaneously simply by starting several different instances of
      <command>bali-phy</command>.  Each instance of bali-phy runs
      only one chain and does not require using MPI or special
    command-line options.</para>   

      <para>This approach to parallel computation is sometimes more
      efficient than MCMCMC-based parallelism involving heated chains.
      It is equivalent to running MCMCMC with no temperature
      difference between chains, with the exception that it allows
      results from <emphasis>all</emphasis> chains to be used, instead
      of just results from the single "cold" chain.  Thus, if you run
      10 independent chains in parallel, then you may gather samples
      10 times faster that a single chain. 
      </para>
    </section>

  </section>

  <section xml:id="input"><info><title>Input</title></info>
    

    <section><info><title>Sequence formats</title></info>
      
      <para><application>BAli-Phy</application> can read in sequences
	and alignments in both FastA and PHYLIP formats.  Filenames for
	FastA files should end in <userinput>.fasta</userinput>,
	<userinput>.mpfa</userinput>, <userinput>.fna</userinput>,
	<userinput>.fas</userinput>, <userinput>.fsa</userinput>, or
	<userinput>.fa</userinput>.  Filenames for PHYLIP files should
	end in <userinput>.phy</userinput>.  If one of these extensions
	is not used, then <application>BAli-Phy</application> will
	attempt to guess which format is being used.
      </para>

    </section>

    <section><info><title>Is my data set too large?</title></info>
      

      <para>Large data sets run more slowly than small data
	sets. We recommend a conservative starting point with few taxa
	and short sequence lengths.  You can then increase the size of
	your data set until a balance between speed and size is
	reached.  The tool <application>alignment-thin</application> described
        in <xref linkend="alignment-utilities"/> can be used to construct a smaller
        data set.</para> 

      <para>The number of MCMC samples that you need depends on whether you
	are primarily interested in obtaining a point estimate or in
	obtaining detailed measures of confidence and uncertainty.  For
	detailed measures of confidence and uncertainty you should
	obtain a minimum of 10,000 samples after the Markov chain
	converges.  For an estimate, you don't need very many samples
	after convergence.  (But you may need many samples to be sure
	that you've converged!)
      </para>

      <para>See also <xref linkend="cluster"/>.</para>

      <section><info><title>Too many taxa?</title></info>
	

	<para><application>BAli-Phy</application> is quite CPU
	  intensive, and so we recommend using 150 or fewer taxa in order
	  to limit the time required to accumulate enough MCMC
	  samples.
	</para>
	<para>When designing an MCMC analysis, I recommend performing an initial analysis
	with a much smaller number of sequences.  This smaller analysis will run much faster, and
	allow discovering mistakes much more quickly.  Then, after you are sure that you
	are running the program correctly and have chosen the best model, you can ramp
	up the number of sequences towards your desired number.
	</para> 

      </section>

      <section><info><title>Sequences too long?</title></info>
	

	<para>Aligning just a pair of sequences takes $O(L^2)$ time
	  and memory, where $L$ represents the sequence length.  Therefore
	  sequences longer than (say) 1000 letters become increasingly
	  impractical.  However, you might try to see how long you can make your
	  sequences before you run out of memory, or the program
	  becomes too slow.</para>

	<para>For multi-gene analyses, two separate data partitions
	  (i.e. genes) of 500 letters will be twice as fast
	  to align as one data partition of 1000 letters. So, it may be possible
	  to analyze several genes as long as each gene individually
	  is not too long.</para> 

	<!-- para>You can speed up alignment for long genes by specifying
	  alignment constraints (See <xref linkend="alignment_constraints"/>).
	  Ideally, 10 evenly spaced constraints should reduce the cost of
	  re-aligning a sequence by a factor of 10.
	</para -->

	<para>Also, note that you can sometimes speed up the analysis
	  of protein sequences by coding them as amino acids or codons, rather 
	  than nucleotides. This is because it decreases the sequence
	  length.
	</para> 
      </section>

    </section>

  </section>

  <section xml:id="output"><info><title>Output</title></info>
    

    <section><info><title>Output directory</title></info>
      
      <para><application>BAli-Phy</application> creates a new
	directory to store its output files each time it is run.  By default, the
	directory name is the name of the sequence file, with a number
	added on the end to make it unique. <application>BAli-Phy</application>
	first checks  if there is already a directory called
	<filename><replaceable>file</replaceable>-1/</filename>, and then moves on to
	<filename><replaceable>file</replaceable>-2/</filename>, etc. until it finds an
	unused directory name.</para> 
      
      <para>You can specify a different name to use instead of the
	sequence-file name by using the <userinput>--name</userinput> option.</para>
    </section>

    <section><info><title>Output files</title></info>
      
      <para><application>BAli-Phy</application> writes the following output
	files inside the directory that it creates:</para>
      
      <variablelist>
	<varlistentry>
	  <term>C1.out</term>
	  <listitem>
	    <para>Iteration numbers, probabilities, success probabilities for transition kernels, etc..</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>C1.P$n$.fastas</term>
	  <listitem>
	    <para>Sampled alignments for partition $n$ including ancestral sequences.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>C1.err</term>
	  <listitem>
	    <para>Log file for hopefully irrelevant error messages.</para>
	  </listitem>
	</varlistentry>
	
	<varlistentry>
	  <term>C1.MAP</term>
	  <listitem>
	    <para>Successive estimates of the MAP alignment, tree and parameters.</para>
	  </listitem>
	</varlistentry>
	
	<varlistentry>
	  <term>C1.log</term>
	  <listitem>
	    <para>Numeric parameters: indel and substitution rates, etc. </para>
	    <para>(<emphasis>One sample per line.</emphasis>)</para>
	  </listitem>
	</varlistentry>
	
	<varlistentry>
	  <term>C1.trees</term>
	  <listitem>
	    <para>Tree samples in Newick format.</para>
	    <para>(<emphasis>One sample per line.</emphasis>)</para>
	  </listitem>
	</varlistentry>
	
	<varlistentry>
	  <term>C1.run.json</term>
	  <listitem>
	    <para>JSON file containing information about the command line, models, hostname, start time, etc.</para>
	  </listitem>
	</varlistentry>

      </variablelist>
      
      <section><title>Field names in <filename>C1.log</filename></title>

      <para>This section explains the meaning of the various field names in the file <filename>C1.log</filename>.</para>


      <variablelist>
	<varlistentry>
	  <term>prior</term>
	  <listitem>
	    <para>The log prior probability. </para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>likelihood</term>
	  <listitem>
	    <para>The log likelihood.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>posterior</term>
	  <listitem>
	    <para>The log of the posterior probability.</para>
	    <para>(<emphasis>The posterior probability is the product of the prior and the likelihood</emphasis>).</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>prior_A</term>
	  <listitem>
	    <para>The log-probability of the alignments in all partitions.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>|A|</term>
	  <listitem>
	    <para>The total number of alignment columns across all partitions.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>#indels</term>
	  <listitem>
	    <para>The total number of indel events across all partitions.</para>
	    <para>(<emphasis>Adjacent indels that occur on the same branch are merged</emphasis>).</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>|indels|</term>
	  <listitem>
	    <para>The total length of indel events across all partitions.</para>
	    <para>(<emphasis>Adjacent indels that occur on the same branch are merged</emphasis>).</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>#substs</term>
	  <listitem>
	    <para>The total unweighted parsimony score for substitutions across all partitions.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>P$n$/likelihood</term>
	  <listitem>
	    <para>The substitution log-likelihood for partition $n$. </para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>P$n$/prior_A</term>
	  <listitem>
	    <para>The log-probability of the alignment for partition $n$.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>P$n$/|A|</term>
	  <listitem>
	    <para>The length of the alignment in the $n$th partition.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>P$n$/#indels</term>
	  <listitem>
	    <para>The number of indel events in partition $n$, if we group adjacent indels that occur on the same branch.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>P$n$/|indels|</term>
	  <listitem>
	    <para>The length of indel events in partition $n$, if we group adjacent indels that occur on the same branch.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>P$n$/#substs</term>
	  <listitem>
	    <para>The unweighted parsimony score for substitutions in partition $n$.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>Scale[$m$]&nbsp;*&nbsp;|T|</term>
	  <listitem>
	    <para>The <emphasis>scaled</emphasis> branch lengths for partition group $m$.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>|T|</term>
	  <listitem>
	    <para>The <emphasis>unscaled</emphasis> tree length.  (This will probably be around 1.0).</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>Scale[$m$]</term>
	  <listitem>
	    <para>The average number of substitutions per site on the entire tree for partitions in the $m$th scale group.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>S$n$/<replaceable>name</replaceable></term>
	  <listitem>
	    <para>Parameter <replaceable>name</replaceable> in the $n$th substitution model.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>I$n$/<replaceable>name</replaceable></term>
	  <listitem>
	    <para>Parameter <replaceable>name</replaceable> in the $n$th insertion/deletion model.</para>
	  </listitem>
	</varlistentry>

      </variablelist>
      <para>The "prior" field includes the probability of the alignment, since the alignment is not observed.</para>
      <para>The likelihood is the probabilistic analogue to summed mismatch penalties.</para>
      <para>The prior_A is the probabilistic analogue to summed gap penalties.</para>
      <para>The prefixes "S$n$/" and "I$n$/" will be dropped if not necessary to disambiguate parameters with the same name in different sub-models.</para>

      </section>
    </section>

    <section><info><title>Summarizing the output</title></info>
      

      <para>This section is primarily about extracting estimates from output files.  See <xref linkend="mixing_and_convergence"/> for methods of determining effective sample sizes, and for checking mixing and convergence.</para>

      <section><info><title>Finding the majority consensus tree</title></info>
	
	<para>
To compute the majority consensus tree, do the following.  (The
program <link xmlns:xlink="http://www.w3.org/1999/xlink"
xlink:href="http://tree.bio.ed.ac.uk/software/figtree/">FigTree</link>
allows you to view the resulting tree file graphically.)
<screen><prompt>%</prompt> trees-consensus <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees &gt; <filename>c50.PP.tree</filename></screen>
</para>

<para>By default, the first 10% of tree samples are skipped as burn-in (<userinput>--skip=10%</userinput> or <userinput>-s 10%</userinput>) and every generation is analyzed (<userinput>--subsample=1</userinput> or <userinput>-x 1</userinput>).  To discard the first 1000 tree samples and analyze every 10th sample:
<screen><prompt>%</prompt> trees-consensus -s 1000 -x 10 <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees &gt; <filename>c50.PP.tree</filename></screen>
By default, splits are included in the consensus tree if they have a
PP greater than 0.5.  You can specify a more stringent level
(e.g. 0.66) by adding the option
<userinput>--consensus-PP=0.66</userinput> as follows:
<screen><prompt>%</prompt> trees-consensus -s20% -x10 --consensus-PP=0.66 <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees &gt; <filename>c66.PP.tree</filename></screen>
You may also make the program write directly to the output file
(e.g. <filename>c66.PP.tree</filename>) by using the more general form
<userinput>--consensus-PP=0.66:c66.PP.tree</userinput>.  Leaving off 
the "<userinput>:c66.PP.tree</userinput>" part (as we did above) or specifying
"<userinput>:-</userinput>" sends the output to the standard output
(e.g. the terminal, if not redirected). 
<screen><prompt>%</prompt> trees-consensus -s20% -x10 <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees --consensus-PP=0.66:<filename>c66.PP.tree</filename></screen>
You can supply multiple levels and filenames separated by commas.
This is faster than running the program multiple times with different
consensus levels.
<screen><prompt>%</prompt> trees-consensus -s20% -x10 <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees --consensus-PP=0.5:<filename>c50.PP.tree</filename>,0.66:<filename>c66.PP.tree</filename></screen>
Finally, you may use the option <userinput>--consensus=</userinput>
instead of the option <userinput>--consensus-PP=</userinput> if you do
not wish the resulting tree to contain embedded posterior
probabilities on branches, as well as branch lengths.
<screen><prompt>%</prompt> trees-consensus -s20% -x10 <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees --consensus=0.5:<filename>c50.PP.tree</filename>,0.66:<filename>c66.PP.tree</filename></screen>
Both the <userinput>--consensus=</userinput> and 
<userinput>--consensus-PP=</userinput> options may be given simultaneously.
</para>

<para>
  See <userinput>trees-consensus --help</userinput> for a complete list of options.
</para>

      </section>

      <section><info><title>Finding the greedy consensus tree</title></info>
	
	<para>
	  The greedy consensus tree may be used instead of a majority-consensus tree when a fully resolved (e.g. bifurcating) tree is required.  When the topology has many tips and each topology may be sampled only once, the greedy consensus should be higher quality than the estimate of the MAP topology.  To obtained a fully resolved tree, the  greedy consensus strategy starts with the majority consensus and then adds the highest-supported split that does not conflict.</para>
	
	<para>To compute the <emphasis>greedy consensus</emphasis> tree do:
<screen><prompt>%</prompt> trees-consensus --skip=<replaceable>burnin</replaceable> <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees --greedy-consensus=<filename>greedy.tree</filename></screen>	
</para>

      </section>

      <section><info><title>Finding the M.A.P. tree</title></info>
	
	<para>
To compute the <emphasis>maximum a posteriori</emphasis> tree do:
<screen><prompt>%</prompt> trees-consensus --skip=<replaceable>burnin</replaceable> <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees --map-tree=<filename>MAP.tree</filename></screen>	
When the tree has many tips, each topology may be sampled only once, leading to low quality estimates of the MAP topology.  As a result, when you need a bifurcating tree you should probably use the greedy consensus instead.
</para>
      </section>

      <section><info><title>Checking topology convergence</title></info>
	
<para>
<screen><prompt>%</prompt> trees-bootstrap <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees</screen>	
This command computes the effective sample size for the posterior probability of each split.  It also computes the Average Standard Deviation of Split Frequencies (ASDSF) between two or more independent runs.</para>

<para>See <xref linkend="mixing_and_convergence"/> for more information.
</para>  
      </section>

      <section><info><title>Summarizing numerical parameters</title></info>
	
<para>
This command gives a median and confidence interval, ESS, and a stabilization time:
<screen><prompt>%</prompt> statreport <replaceable>dir-1</replaceable>/C1.log <replaceable>dir-2</replaceable>/C1.log &gt; Report </screen>	
When multiple runs are analyzed, this command gives PSRF and joint ESS values. The program <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://tree.bio.ed.ac.uk/software/tracer/">Tracer</link> allows you to view the same summaries graphically.</para>

<para>See <xref linkend="mixing_and_convergence"/> for more information.
</para>
      </section>

      <section><info><title>Computing an alignment using Posterior Decoding</title></info>
      <para>To construct an alignment estimate via posterior decoding, select any tree file <replaceable>tree</replaceable> that corresponds to your alignment.  It does not need to be fully resolved.
      </para>
      
      <screen><prompt>%</prompt> cut-range <replaceable>dir</replaceable>-1/C1.P<replaceable>p</replaceable>.fastas <replaceable>dir</replaceable>-2/C1.P<replaceable>p</replaceable>.fastas --skip=<replaceable>burn-in</replaceable> | alignment-chop-internal --tree <replaceable>tree</replaceable> | alignment-max &gt; P<replaceable>p</replaceable>-max.fasta</screen>

      <para>You can optionally replace <userinput>--tree <replaceable>tree</replaceable></userinput> with <userinput>-N <replaceable>n_sequences</replaceable></userinput>, where <replaceable>n_sequences</replaceable> is the number of non-ancestral sequences in your alignment.</para>

      <para>You can use the program <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://pbil.univ-lyon1.fr/software/seaview.html">SeaView</link> to view the alignment graphically.</para>

      </section>      

      <!-- section><info><title>Find the alignment from the maximum a posterior (MAP) point (<filename>C1.MAP</filename>)</title></info>
	
<screen><prompt>%</prompt> alignment-find &lt; C1.MAP &gt; P1-MAP.fasta</screen>

      This only works correctly on single-partition analyses.
      </section -->      

      <section><info><title>Create an Au (Alignment Uncertainty) plot</title></info>
	
<para>To annotate a specific alignment <replaceable>alignment</replaceable>.fasta, choose a fully resolved tree estimate <replaceable>tree</replaceable>:
<screen><prompt>%</prompt> cut-range <replaceable>dir</replaceable>-1/C1.P<replaceable>p</replaceable>.fastas <replaceable>dir</replaceable>-2/C1.P<replaceable>p</replaceable>.fastas --skip=<replaceable>burn-in</replaceable> | alignment-chop-internal --tree <replaceable>tree</replaceable>  | alignment-gild <replaceable>alignment</replaceable>.fasta <replaceable>tree</replaceable>  &gt; <replaceable>alignment</replaceable>-AU.prob
<prompt>%</prompt> alignment-draw <replaceable>alignment</replaceable>.fasta --AU <replaceable>alignment</replaceable>-AU.prob &gt; <replaceable>alignment</replaceable>-AU.html</screen>
The majority consensus tree is usually not fully resolved, so we recommend using the greedy consensus instead.
</para>
      </section>


    </section>


  <section xml:id="analysis"><info><title>Summarizing the output - scripted</title></info>
    
    
    <para>
      Instead of manually running each of the steps to analyze the
      output files, you may instead run the PERL script
      <command>bp-analyze</command> to execute these commands.  The
      script will create an HTML page
      <filename>Results/index.html</filename> that summarizes the
      posterior distribution.
    </para>

  <para>You may run <command>bp-analyze</command> inside the output directory, like this:
<screen><prompt>%</prompt> bp-analyze --skip=<replaceable>iterations</replaceable></screen>
      You may also run it with one or more output directories as
      arguments, like this:
<screen><prompt>%</prompt> bp-analyze --skip=<replaceable>iterations</replaceable> <replaceable>directory</replaceable>-1/ <replaceable>directory</replaceable>-2/</screen>
      In this case, output from multiple runs will be used to assess convergence and mixing, as well as to increase the precision of the estimates.
    </para>

<para> All the commands that are executed by <command>bp-analyze</command> will be logged to
      <filename>Results/commands.log</filename>. You can also see these
      commands as they are executed by supplying the <command>--verbose</command> option:
<screen><prompt>%</prompt> bp-analyze --skip=<replaceable>iterations</replaceable> --verbose</screen>
    </para>

    <section><info><title>Meaning of generated files</title></info>
      
    <para>The <filename>Results/</filename> directory will contain
    the following useful files:</para>

      <variablelist>

	<varlistentry><term>Report</term><listitem>
	    <para>A summary of numerical parameters: credible
	    intervals and mixing.</para>
	</listitem></varlistentry>

	<varlistentry><term>consensus</term><listitem>
	    <para>A summary of supported splits (clades). </para>
	</listitem></varlistentry>

	<varlistentry><term>c-levels.plot</term><listitem>
	    <para>The number of splits (clades) supported at each LOD level.</para>
	</listitem></varlistentry>

	<varlistentry><term>c50.tree</term><listitem>	<para>The majority consensus topology + branch lengths (Newick format)</para> 
	</listitem></varlistentry>

	<varlistentry><term>c50.PP.tree</term><listitem>
	<para>The majority consensus topology + branch lengths +
	Posterior Probabilities (Newick format)</para> 
	</listitem></varlistentry>

	<varlistentry><term>MAP.tree</term><listitem>
	    <para>An estimate of the MAP topology + branch lengths (Newick format)</para>
	</listitem></varlistentry>

      </variablelist>
      <para> 
	The following files will be generated to summarize alignment uncertainty, unless the analysis uses a fixed alignment.

      </para>

      <variablelist>
	<varlistentry><term>P<replaceable>p</replaceable>-max.fasta</term><listitem>
	    <para>An estimate of the alignment for partition
	    <replaceable>p</replaceable> using maximum posterior decoding.</para>
	</listitem></varlistentry>

	<varlistentry><term>P<replaceable>p</replaceable>-max-AU.html</term><listitem>
	    <para>An AU plot of the maximum posterior decoding alignment for partition
	    <replaceable>p</replaceable>  (AA/DNA color-scheme).</para>
	</listitem></varlistentry>

	<!-- varlistentry><term>consensus.fasta</term><listitem>
	    <para>A consensus alignment, representing information shared by most alignment samples.
	</para></listitem></varlistentry>

	<varlistentry><term>consensus-AU.html</term><listitem><para>An AU plot of the consensus alignment (rainbow color-scheme).
	</para></listitem></varlistentry>

	<varlistentry><term>consensus-AU2.html</term><listitem><para>An AU plot of the MAP alignment (AA/DNA color-scheme).
	</para></listitem></varlistentry>

	<varlistentry><term>consensus-AU.prob</term><listitem><para>The probabilities for each letter in the consensus alignment AU plot.
	</para></listitem></varlistentry -->
	
      </variablelist>


      <para>The following files describe convergence and mixing:</para>


      <variablelist>

	<varlistentry><term>partitions.bs</term><listitem>
	    <para>Confidence intervals on the support for partitions, generated
	      using a block bootstrap.</para>
	</listitem></varlistentry>

	<varlistentry><term>partitions.SRQ</term><listitem><para>A collection of
	      SRQ plots for the supported partitions.
	</para></listitem></varlistentry>

	<varlistentry><term>c50.SRQ</term><listitem><para>An
	      SRQ plot for the majority consensus tree.
	</para></listitem></varlistentry>


      </variablelist>

      <para>The SRQ plots can be viewed by typing "<userinput>plot
	  '<replaceable>file</replaceable>' with lines</userinput>" in
	<application>gnuplot</application>.</para>

    </section>
      <section><info><title><filename>Mixing/partitions.bs</filename>: partition mixing</title></info>
	
	<para>
	  This file reports the quality of estimates of support for each
	  partition in terms of the posterior probability (PP) and
	  log-10 odds (LOD).  It also reports the auto-correlation time (ACT),
	  the effective sample size (Ne), the number of samples
	  that support (1) or do not support (0) the partition, and
	  the number of regenerations. 

	  Only partitions with PP &gt; 0.1 are shown by default.
	</para>
      </section>


  </section>
  </section>


  <section xml:id="subst_models">
    <info><title>Substitution models</title></info>
      
    <section xml:id="dna_models">
      <info><title>DNA and RNA models</title></info>
	
      <para>The default substitution model for DNA and RNA is tn93.</para>
      <section>
	<info><title>Substitution rates</title></info>
      <para>All the DNA models are special cases of the GTR model.  </para>
      <informaltable>
	<tgroup cols="3">
	  <colspec colnum="1" colname="col1" colwidth="1*"/>
	  <colspec colnum="2" colname="col2" colwidth="1*"/>
	  <colspec colnum="3" colname="col3" colwidth="1*"/>
	  <thead><row>
	    <entry>Model</entry>
	    <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	    <entry>Summary</entry>
	  </row></thead>

	  <tbody>
	    <row>
	      <entry><userinput>jc69</userinput></entry>
	      <entry>0</entry>
	      <entry><para>Equal rates and equal base frequencies.</para>
	      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1016/B978-1-4832-3211-9.50009-7">(Jukes and Cantor, 1969)</link>
	      </entry>
	    </row>

	    <row>
	      <entry><userinput>k80</userinput></entry>
	      <entry>1</entry>
	      <entry><para>Unequal transition &amp; transversion rates, equal base frequencies.</para>
	      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1007%2FBF01731581">(Kimura, 1980)</link>
	      </entry>
	    </row>

	    <row>
	      <entry><userinput>f81</userinput></entry>
	      <entry>3</entry>
	      <entry><para>Equal exchangeabilities, unequal frequencies.</para>
	      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1007%2FBF01734359">
		(Felsenstein, 1981)
	      </link>
	      </entry>
	    </row>

	    <row>
	      <entry><userinput>hky85</userinput></entry>
	      <entry>4</entry>
	      <entry><para>Unequal Transition &amp; transversion rates, unequal base frequencies.</para>
	      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1007/BF02101694">
		(Hasegawa, Kishino, and Yano, 1985)
	      </link>
	      </entry>
	    </row>

	    <row>
	      <entry><userinput>tn93</userinput></entry>
	      <entry>5</entry>
	      <entry>
		<para>Unequal rates for transitions (purines), transitions (pyrimidines) and transversions, unequal base frequencies.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a040023">
		  (Tamura and Nei, 1993)
		</link>
	      </entry>
	    </row>

	    <row>
	      <entry><userinput>gtr</userinput></entry>
	      <entry>8</entry>
	      <entry><para>Unequal exchangeabilities, unequal frequencies.</para>
	      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.damtp.cam.ac.uk/user/st321/CV_&amp;_Publications_files/STpapers-pdf/T86.pdf">
		(Tavare, 1986)
	      </link>
	      </entry>
	    </row>
	  
	  </tbody>
	</tgroup>
      </informaltable>
      </section>
    <section xml:id="nucleotide-frequencies">
      <info><title>Frequencies</title></info>
      <para>Frequencies are estimated by default.  Frequencies can be fixed by setting the <userinput>pi</userinput> parameter to a constant value, if the model allows unequal frequencies.</para>
      <para>Constant frequencies are specified as a list of pairs that associates each letter with its frequency:</para>
      <programlisting language="java">gtr(pi={"A":0.1, "C":0.2, "T":0.3, "G":0.4})</programlisting>
      <para>Frequencies can also be specified using functions:</para>

      <para>
	<programlisting language="java">gtr(pi=Frequencies.uniform)</programlisting>
      </para>

      <informaltable>
	<tgroup cols="3">
	  <colspec colnum="1" colname="col1" colwidth="1*"/>
	  <colspec colnum="2" colname="col2" colwidth="1*"/>
	  <colspec colnum="3" colname="col3" colwidth="1*"/>
	  <thead><row>
	    <entry>Model</entry>
	    <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	    <entry>Summary</entry>
	  </row></thead>

	  <tbody>
	    <row>
	      <entry><userinput>Frequencies.uniform</userinput></entry>
	      <entry>0</entry>
	      <entry>Equal frequencies</entry>
	    </row>

	  </tbody>
	</tgroup>
      </informaltable>
    </section>


    </section>

    <section xml:id="protein_models">
      <info><title>Protein models</title></info>

      <para>The default substitution model for proteins is lg08.</para>

      <section>
	<info><title>Substitution rates</title></info>
      <informaltable>
	  
	<tgroup cols="3">
	  <colspec colnum="1" colname="col1" colwidth="1*"/>
	  <colspec colnum="2" colname="col2" colwidth="1*"/>
	  <colspec colnum="3" colname="col3" colwidth="1*"/>
	  <thead><row>
	    <entry>Model</entry>
	    <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	    <entry>Summary</entry>
	  </row></thead>
	  
	  <tbody>
	    <row>
	      <entry><userinput>jc69</userinput></entry>
	      <entry>0</entry>
	      <entry><para>Equal rates and equal frequencies.</para>
	      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1016/B978-1-4832-3211-9.50009-7">(Jukes and Cantor, 1969)</link></entry>
	    </row>

	    <row>
	      <entry><userinput>f81</userinput></entry>
	      <entry>19</entry>
	      <entry><para>Equal exchangeabilities, unequal frequencies.</para>
	      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1007%2FBF01734359">
		(Felsenstein, 1981)
	      </link>
	      </entry>
	    </row>

	    <row>
	      <entry>
		<para><userinput>jtt&nbsp;+>&nbsp;f</userinput></para>
	      </entry>
	      <entry>19</entry>
	      <entry>
		<para>Empirical exchange rates, all proteins.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/bioinformatics/8.3.275">
		  (Jones, Taylor, and Thornton, 1992)
		</link>
	      </entry>
	    </row>

	    <row>
	      <entry>
		<para><userinput>wag&nbsp;+>&nbsp;f</userinput></para>
	      </entry>
	      <entry>19</entry>
	      <entry>
		<para>Empirical exchange rates, all proteins.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a003851">
		  (Whelan and Goldman, 2001)
		</link>
	      </entry>
	    </row>

	    <row>
	      <entry>
		<para><userinput>lg08&nbsp;+>&nbsp;f</userinput></para>
	      </entry>
	      <entry>19</entry>
	      <entry>
		<para>Empirical exchange rates, all proteins.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/molbev/msn067">
		  (Le and Gascuel, 2008)
		</link>
	      </entry>
	    </row>

	    <row>
	      <entry>
		<para><userinput>empirical(<replaceable>file</replaceable>)&nbsp;+>&nbsp;f</userinput></para>
	      </entry>
	      <entry>19</entry>
	      <entry>
	      </entry>
	    </row>

	    <row>
	      <entry><userinput>gtr</userinput></entry>
	      <entry>208</entry>
	      <entry><para>Unequal exchangeabilities, unequal frequencies.</para>
	      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.damtp.cam.ac.uk/user/st321/CV_&amp;_Publications_files/STpapers-pdf/T86.pdf">
		(Tavare, 1986)
	      </link>
	      </entry>
	    </row>
	  </tbody>
	</tgroup>
      </informaltable>
      </section>
    <section xml:id="amino-acid-frequencies">
      <info><title>Frequencies</title></info>
      <para>Frequencies are estimated by default.  Frequencies can be fixed by setting the <userinput>pi</userinput> parameter to a constant value, if the model allows unequal frequencies.</para>
      <para>Constant frequencies are specified as a list of pairs that associates each letter with its frequency:</para>
      <programlisting language="java">wag +> f({"A":0.047, "R":0.19,...})</programlisting>
      <para>Frequencies can also be specified using functions:</para>
      <para>
	<programlisting language="java">wag +> f(pi=Frequencies.uniform)</programlisting>
      </para>

      <informaltable>
	<tgroup cols="3">
	  <colspec colnum="1" colname="col1" colwidth="1*"/>
	  <colspec colnum="2" colname="col2" colwidth="1*"/>
	  <colspec colnum="3" colname="col3" colwidth="1*"/>
	  <thead><row>
	    <entry>Model</entry>
	    <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	    <entry>Summary</entry>
	  </row></thead>

	  <tbody>
	    <row>
	      <entry><userinput>Frequencies.uniform</userinput></entry>
	      <entry>0</entry>
	      <entry>Equal frequencies</entry>
	    </row>

	    <row>
	      <entry><userinput>wag_freq</userinput></entry>
	      <entry>0</entry>
	      <entry>The constant amino-acid frequencies from the WAG paper.</entry>
	    </row>

	    <row>
	      <entry><userinput>lg08_freq</userinput></entry>
	      <entry>0</entry>
	      <entry>The constant amino-acid frequencies from the LG08 paper.</entry>
	    </row>
	  </tbody>
	</tgroup>
      </informaltable>
	  
      <para>The <userinput>+> fe</userinput> model is shorthand for <userinput>+> f(pi=Frequencies.uniform)</userinput>:</para>
      <para>
	<programlisting language="java">wag +> fe</programlisting>
      </para>
    </section>


    </section>
      
    <section xml:id="doublet_models">
      <info><title>Doublet models (RNA stems)</title></info>
      <para>The doublets alphabet consists of 16 RNA dinucleotides.  It is used to model RNA stems, where two nucleotides matched in the RNA secondary structure are highly correlated.</para>
      <para>The default substitution model for doublets is <userinput>tn93_sym&nbsp;+>&nbsp;x2_sym&nbsp;+>&nbsp;f</userinput>.</para>
      <section xml:id="doublet-data">
	<info><title>Doublet data</title></info>
	<para>As of version 3.4, BAli-Phy does not yet allow specifying which nucleotides are paired either with a string like <userinput>((.))</userinput> or with a "pairs" file.  Instead you must manually extract the paired nucleotides and put them in their own partition (for stems), and then manually extract each loop and put it in its own partition.</para>
	<para>The stems should be arranged so that paired nucleotides are adjacent. For example, suppose the sequence <userinput>AGGCT</userinput> was paired according to <userinput>((.))</userinput>.  Then the input file for the stems should contain a sequence of doublets that looks like <userinput>ATGC</userinput>, where <userinput>AT</userinput> is the first pair, and <userinput>GC</userinput> is the second pair.  Later versions of the software should allow extracting stems and loops from nucleotide sequences using parenthesis notation or a "pairs" file.
	</para>
      </section>
      <section>
	<info><title>Substitution rates</title></info>
      <informaltable>

	<tgroup cols="3">
	  <colspec colnum="1" colname="col1" colwidth="1*"/>
	  <colspec colnum="2" colname="col2" colwidth="1*"/>
	  <colspec colnum="3" colname="col3" colwidth="1*"/>
	  <thead><row>
	    <entry>Model</entry>
	    <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	    <entry>Summary</entry>
	  </row></thead>
	  
	  <tbody>
	    <row>
	      <entry><userinput><replaceable>nuc_model</replaceable>&nbsp;+>&nbsp;x2</userinput></entry>
	      <entry>df(nuc_model)</entry>
	      <entry>
		<para>The the same as <replaceable>nuc_model</replaceable>, but on dinucleotides instead of nucleotides.</para>
		<para>Simultaneous changes of both letters are <emphasis>not</emphasis> allowed.</para>
		<para>Dinucleotide frequencies are the product of independent nucleotide frequencies.</para>
	      </entry>
	    </row>

	    <row>
	      <entry><userinput><replaceable>nuc_model</replaceable>&nbsp;+>&nbsp;x2&nbsp;+>&nbsp;mut_sel</userinput></entry>
	      <entry>df(nuc_model)+15</entry>
	      <entry>
		<para>Mutation-selection model: neutral mutation follows <replaceable>nuc_model</replaceable> and scaled selection coefficients 2Ns on dinucleotides.</para>
		<para>Simultaneous changes of both letters are <emphasis>not</emphasis> allowed.</para>
	      </entry>
	    </row>

	    <row>
	      <entry><userinput><replaceable>nuc_model</replaceable>&nbsp;+>&nbsp;x2_sym&nbsp;+>&nbsp;f</userinput></entry>
	      <entry>df(nuc_model)+15</entry>
	      <entry><para>This model has separate frequencies for each dinucleotide.</para>
	      <para>Simultaneous changes of both letters are <emphasis>not</emphasis> allowed.</para>
	      </entry>
	    </row>

	    <row>
	      <entry><userinput><replaceable>RNA.m16a</replaceable></userinput></entry>
	      <entry>19</entry>
	      <entry>
		<para>This model has separate frequencies for each dinucleotide, and distinguishes between transitions and transversion between match states (including GU/UG).</para>
		<para>Simultaneous changes of both letters <emphasis>are</emphasis> allowed, but only between match states.</para>
	      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/genetics/157.1.399">
		(Savill et al., 2001)
	      </link>
	      </entry>
	    </row>

	    <!-- row> This is too advanced
	      <entry><userinput>x2x2[q1,q2]</userinput></entry>
	      <entry>df(q1)+df(q2)</entry>
	      <entry><para>Doublet rate matrix constructed from a nucleotide rate matrix for each doublet position.</para>
	      </entry>
	    </row -->

	    <row>
	      <entry><userinput>gtr</userinput></entry>
	      <entry>134</entry>
	      <entry><para>Unequal exchangeabilities, unequal frequencies.</para>
	      <para>It is unlikely that you would want to use this model, since it has so many parameters.</para>
	      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.damtp.cam.ac.uk/user/st321/CV_&amp;_Publications_files/STpapers-pdf/T86.pdf">
		(Tavare, 1986)
	      </link>
	      </entry>
	    </row>

	  </tbody>
	</tgroup>
      </informaltable>
      </section>
    <section xml:id="doublet-frequencies">
      <info><title>Frequencies</title></info>
      <para>Frequencies are estimated by default.  Frequencies can be fixed by setting the <userinput>pi</userinput> parameter to a constant value, if the model allows unequal frequencies.</para>
      <para>Constant frequencies are specified as a list of pairs that associates each letter with its frequency.</para>
      <programlisting language="java">hky85(pi={"A":0.1, "C":0.2, "T":0.3, "G":0.4}) +> x2

hky85_sym +> x2_sym +> f({"AA":0.01, "AC":0.01, "AG":0.01, "AU":0.22, "CA":0.01, "CC":0.01, "CG":0.22, "CU":0.01, "GA":0.01, "GC":0.22, "GG":0.01, "GU":0.01, "UA":0.22, "UC":0.01, "UG":0.01, "UU":0.01})</programlisting>

      <para>Frequencies can also be specified using functions:</para>
      <!-- para>
	<programlisting language="java">hky85_sym +> x2_sym +> f(pi=f1x4)            // nucleotide frequencies are estimated</programlisting>
      </para -->


      <informaltable>
	<tgroup cols="3">
	  <colspec colnum="1" colname="col1" colwidth="1*"/>
	  <colspec colnum="2" colname="col2" colwidth="1*"/>
	  <colspec colnum="3" colname="col3" colwidth="1*"/>
	  <thead><row>
	    <entry>Model</entry>
	    <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	    <entry>Summary</entry>
	  </row></thead>

	  <tbody>
	    <row>
	      <entry><userinput>Frequencies.uniform</userinput></entry>
	      <entry>0</entry>
	      <entry>Equal frequencies on dinucleotides</entry>
	    </row>

	    <!-- row>  Maybe this should take (i) one set of nuc frequencies, and (ii) one set of fitness parameters?
	      <entry><userinput>f1x4</userinput></entry>
	      <entry>3</entry>
	      <entry>Constructs doublet frequencies from independent nucleotide frequencies.</entry>
	    </row -->

	    <!-- row>
	      <entry><userinput>f2x4</userinput></entry>
	      <entry>6</entry>
	      <entry>Constructs doublet frequencies from independent nucleotide frequencies for each doublet position.</entry>
	    </row -->
	    
	  </tbody>
	</tgroup>
      </informaltable>
    </section>

    <section xml:id="doublet-branch-lengths">
      <info><title>Branch lengths</title></info>
      <para>BAli-Phy interprets branch lengths for doublet models as 1/2 the number of substitutions per doublet.  Thus, they should be comparable to branch lengths under DNA/RNA nucleotide models.</para>
    </section>
      

  </section>

    <section xml:id="triplet_models">
      <info><title>Triplet models</title></info>
      <para>The triplets alphabet is similar to the codons alphabet, except that stop codons are included. Unlike the codons alphabet, the triplets alphabet has no knowledge of the genetic code.</para>
      <para>The default substitution model for triplets is tn93 +> x3.</para>
      <section>
	<info><title>Substitution rates</title></info>
      <informaltable>

	<tgroup cols="3">
	  <colspec colnum="1" colname="col1" colwidth="1*"/>
	  <colspec colnum="2" colname="col2" colwidth="1*"/>
	  <colspec colnum="3" colname="col3" colwidth="1*"/>
	  <thead><row>
	    <entry>Model</entry>
	    <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	    <entry>Summary</entry>
	  </row></thead>
	  
	  <tbody>
	    <row>
	      <entry><userinput><replaceable>nuc_model</replaceable>&nbsp;+>&nbsp;x3_sym&nbsp;+>&nbsp;f</userinput></entry>
	      <entry>df(<replaceable>nuc_model</replaceable>)+63</entry>
	      <entry><para>GY94-style rate matrix constructed from nucleotide exchangeability matrix.</para>
	      </entry>
	    </row>

	    <row>
	      <entry><userinput><replaceable>nuc_model</replaceable>&nbsp;+>&nbsp;x3</userinput></entry>
	      <entry>df(<replaceable>nuc_model</replaceable>)</entry>
	      <entry><para>MG94-style rate matrix constructed from nucleotide rate matrix.</para>
	             <para>This model should give the same likelihood as <replaceable>nuc_model</replaceable> on triplets, but not on codons.</para>
	      </entry>
	    </row>

	    <!-- row> This is too advanced
	      <entry><userinput>x3x3(q1,q2,q3)</userinput></entry>
	      <entry>df(q1)+df(q2)+df(q3)</entry>
	      <entry><para>Triplet rate matrix constructed from a nucleotide rate matrix for each codon position.</para>
	      </entry>
	    </row -->

	      <row>
		<entry><userinput><replaceable>nuc_model</replaceable>&nbsp;+>&nbsp;x3&nbsp;+>&nbsp;mut_sel</userinput></entry>
		<entry>df(<replaceable>nuc_model</replaceable>)+63</entry>
		<entry><para>Mutation-selection model with neutral mutation following <replaceable>nuc_model</replaceable> and scaled selection coefficients 2Ns <emphasis>for each codon</emphasis>.</para>
		</entry>
	      </row>

	  </tbody>
	</tgroup>
      </informaltable>
      </section>
    <section xml:id="triplet-frequencies">
      <info><title>Frequencies</title></info>
      <para>Frequencies are estimated by default.  Frequencies can be fixed by setting the <userinput>pi</userinput> parameter to a constant value, if the model allows unequal frequencies.</para>
      <para>Constant frequencies are specified as a list of pairs that associates each letter with its frequency.</para>
      <programlisting language="java">hky85(pi={"A":0.1, "C":0.2, "T":0.3, "G":0.4}) +> x3</programlisting>
      <para>Frequencies can also be specified using functions:</para>
      <para>
	<programlisting language="java">hky85_sym +> x3_sym +> f(pi=f1x4)            // nucleotide frequencies are estimated</programlisting>
      </para>


      <informaltable>
	<tgroup cols="3">
	  <colspec colnum="1" colname="col1" colwidth="1*"/>
	  <colspec colnum="2" colname="col2" colwidth="1*"/>
	  <colspec colnum="3" colname="col3" colwidth="1*"/>
	  <thead><row>
	    <entry>Model</entry>
	    <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	    <entry>Summary</entry>
	  </row></thead>

	  <tbody>
	    <row>
	      <entry><userinput>Frequencies.uniform</userinput></entry>
	      <entry>0</entry>
	      <entry>Equal frequencies</entry>
	    </row>

	    <row>
	      <entry><userinput>f1x4</userinput></entry>
	      <entry>3</entry>
	      <entry>Constructs triplet frequencies from independent nucleotide frequencies.</entry>
	    </row>

	    <row>
	      <entry><userinput>f3x4</userinput></entry>
	      <entry>9</entry>
	      <entry>Constructs triplet frequencies from independent nucleotide frequencies for each codon position.</entry>
	    </row>
	    
	  </tbody>
	</tgroup>
      </informaltable>
	<para>The <userinput>+> fe</userinput> model is shorthand for <userinput>+> f(pi=Frequencies.uniform)</userinput>:</para>
	<para>
	  <programlisting language="java">hky85_sym +> x3_sym +> fe</programlisting>
	</para>
    </section>

      <para>BAli-Phy interprets branch lengths for codon models as 1/3 the number of substitutions per triplet.  Thus, they should be comparable to branch lengths under DNA/RNA nucleotide models.</para>
      

    </section>

    <section xml:id="codon_models">
      <info><title>Codon models</title></info>

      <para>The default substitution model for codons is gy94.</para>

      <section>
	<info><title>Substitution rates</title></info>
	
	<informaltable>
	  
	  <tgroup cols="3">
	    <colspec colnum="1" colname="col1" colwidth="1*"/>
	    <colspec colnum="2" colname="col2" colwidth="1*"/>
	    <colspec colnum="3" colname="col3" colwidth="1*"/>
	    <thead><row>
	      <entry>Model</entry>
	      <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	      <entry>Summary</entry>
	    </row></thead>

	    <tbody>
	      <row>
		<entry><userinput>gy94</userinput></entry>
		<entry>62</entry>
		<entry><para>Model of dN/dS with a separate frequency for each codon.</para>
		<para>Rate for changing a nucleotide depends on neighboring nucleotides.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a040153">
		  (Goldman and Yang, 1994)
		</link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>gy94(pi=f1x4)</userinput></entry>
		<entry>5</entry>
		<entry><para>The GY94 model with codon frequencies constructed from nucleotide frequencies.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a040153">
		  (Goldman and Yang, 1994)
		</link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>gy94(pi=f3x4)</userinput></entry>
		<entry>11</entry>
		<entry><para>The GY94 model with codon frequencies constructed from nucleotide frequencies for each codon position.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a040153">
		  (Goldman and Yang, 1994)
		</link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>gy94_ext(<replaceable>nuc_model</replaceable>)</userinput></entry>
		<entry>df(<replaceable>nuc_model</replaceable>)+61</entry>
		<entry><para>GY94 model extended with a generic nucleotide exchangeability matrix.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a040153">
		  (Goldman and Yang, 1994)
		</link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>mg94</userinput></entry>
		<entry>4</entry>
		<entry>
		  <para>Model of dN/dS with f81 as the neutral model.</para>
		  <para>Rate for changing a nucleotide depends only on that nucleotide.</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a040152">
		    (Muse and Gaut, 1994)
		  </link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>mg94k</userinput></entry>
		<entry>5</entry>
		<entry><para>Model of dN/dS with hky85 as the neutral model.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a040152">
		  (Muse and Gaut, 1994)
		</link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>mg94_ext(<replaceable>nuc_model</replaceable>)</userinput></entry>
		<entry>df(<replaceable>nuc_model</replaceable>)+1</entry>
		<entry><para>Model of dN/dS with <replaceable>nuc_model</replaceable> as the neutral model.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a040152">
		  (Muse and Gaut, 1994)
		</link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>fMutSel</userinput></entry>
		<entry>65</entry>
		<entry><para>MG94-like model with fitnesses for each codon.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/molbev/msm284">
		  (Yang and Nielsen, 2008)
		</link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>fMutSel0</userinput></entry>
		<entry>24</entry>
		<entry><para>MG94-like model with fitnesses for each amino-acid.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/molbev/msm284">
		  (Yang and Nielsen, 2008)
		</link>
		</entry>
	      </row>
	      
	      <row>
		<entry><userinput><replaceable>nuc_model</replaceable>&nbsp;+>&nbsp;x3_sym&nbsp;+>&nbsp;f</userinput></entry>
		<entry>df(nuc_model)+60</entry>
		<entry><para>GY94-style rate matrix constructed from nucleotide exchangeability matrix (dN/dS = 1).</para>
	               <para>This model should give the same likelihood as <replaceable>nuc_model</replaceable> on codons only if the frequency of stop codons is zero.</para>
		</entry>
	      </row>

	      <row>
		<entry><userinput><replaceable>nuc_model</replaceable>&nbsp;+>&nbsp;x3</userinput></entry>
		<entry>df(nuc_model)</entry>
		<entry><para>MG94-style rate matrix constructed from nucleotide rate matrix (dN/dS = 1).</para>
		</entry>
	      </row>

	      <!-- row>
		<entry><userinput>x3x3(q1,q2,q3)</userinput></entry>
		<entry>df(q1)+df(q2)+df(q3)</entry>
		<entry><para>Triplet rate matrix constructed from a nucleotide rate matrix for each codon position (dN/dS = 1).</para>
		</entry>
	      </row -->

	      <row>
		<entry><userinput><replaceable>codon_model</replaceable> +> dNdS(omega)</userinput></entry>
		<entry>df(<replaceable>codon_model</replaceable>)+1</entry>
		<entry><para>Scales non-synonymous rates by <replaceable>omega</replaceable>.</para>
		</entry>
	      </row>

	      <row>
		<entry><userinput><replaceable>codon_model</replaceable> +> mut_sel</userinput></entry>
		<entry>df(<replaceable>codon_model</replaceable>)+60</entry>
		<entry><para>Mutation-selection model with neutral mutation following <replaceable>codon_model</replaceable> and scaled selection coefficients 2Ns <emphasis>for each codon</emphasis>.</para>
		</entry>
	      </row>

	      <row>
		<entry><userinput><replaceable>nuc_model</replaceable>&nbsp;+>&nbsp;x3&nbsp;+>&nbsp;mut_sel_aa</userinput></entry>
		<entry>df(<replaceable>nuc_model</replaceable>)+19</entry>
		<entry><para>Mutation-selection model with neutral mutation following <replaceable>nuc_model</replaceable> and scaled selection coefficients 2Ns <emphasis>for each amino acid</emphasis>.</para>
		</entry>
	      </row>
	      
	    </tbody>
	  </tgroup>
	</informaltable>


	<para>BAli-Phy interprets branch lengths for codon models as 1/3 of the number of substitutions per codon.  Thus, they should be comparable to branch lengths under DNA/RNA models.</para>
	<para>The <userinput>x3</userinput>, <userinput>x3_sym</userinput>, <userinput>x3x3</userinput>, <userinput>dNdS</userinput>, and <userinput>mut_sel</userinput> models
	can be used to build up codon models piecewise:
	<itemizedlist>
	  <listitem><userinput>mg94</userinput> is equivalent to <userinput>f81 +> x3 +> dNdS</userinput>.</listitem>
	  <listitem><userinput>mg94k</userinput> is equivalent to <userinput>hky85 +> x3 +> dNdS</userinput>.</listitem>
	  <listitem><userinput>gy94</userinput> is equivalent to <userinput>hky85_sym +> x3_sym +> f +> dNdS</userinput>.</listitem>
	  <listitem><userinput>fMutSel</userinput> is equivalent to <userinput>gtr +> x3 +> dNdS +> mut_sel</userinput>.</listitem>
	  <listitem><userinput>fMutSel0</userinput> is equivalent to <userinput>gtr +> x3 +> dNdS +> mut_sel_aa</userinput>.</listitem>
	</itemizedlist>
	</para>
      </section>

      <section xml:id="codon-frequencies">
      <info><title>Frequencies</title></info>
      <para>Frequencies are estimated by default.  Frequencies can be fixed by setting the <userinput>pi</userinput> parameter to a constant value, if the model allows unequal frequencies.</para>
      <para>Constant frequencies are specified as a list of pairs that associates each letter with its frequency.</para>
      <programlisting language="java">gy94(pi={"AAA":0.01, "C":0.02,...})
mg94(pi={"A":0.1, "C":0.2, "T":0.3, "G":0.4})
</programlisting>
      <para>Frequencies can also be specified using functions:</para>
      <para>
	<programlisting language="java">gy94(pi=f1x4)              // nucleotide frequencies are estimated</programlisting>
      </para>


      <informaltable>
	<tgroup cols="3">
	  <colspec colnum="1" colname="col1" colwidth="1*"/>
	  <colspec colnum="2" colname="col2" colwidth="1*"/>
	  <colspec colnum="3" colname="col3" colwidth="1*"/>
	  <thead><row>
	    <entry>Model</entry>
	    <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	    <entry>Summary</entry>
	  </row></thead>

	  <tbody>
	    <row>
	      <entry><userinput>Frequencies.uniform</userinput></entry>
	      <entry>0</entry>
	      <entry>Equal frequencies</entry>
	    </row>

	    <row>
	      <entry><userinput>f1x4</userinput></entry>
	      <entry>3</entry>
	      <entry>Constructs codon frequencies from independent nucleotide frequencies.</entry>
	    </row>

	    <row>
	      <entry><userinput>f3x4</userinput></entry>
	      <entry>9</entry>
	      <entry>Constructs codon frequencies from independent nucleotide frequencies for each codon position.</entry>
	    </row>
	    
	  </tbody>
	</tgroup>
      </informaltable>
    </section>

      <section xml:id="genetic-codes">
	<info><title>Genetic Codes</title></info>
      
	<para>When using a codon-based substitution model like <userinput>gy94</userinput>, you may select the genetic code by specifying <userinput>-A Codons(,<replaceable>genetic-code</replaceable>)</userinput>.
        Available genetic codes are:</para>
	<informaltable>
	  <tgroup cols="3">
	    <thead><row>
	      <entry>Name</entry>
	      <entry>Number</entry>
	      <entry>Description</entry>
	    </row></thead>
	    <tbody>
<row><entry>standard</entry><entry> 1</entry><entry>Standard</entry></row>
<row><entry>mt-vert</entry><entry> 2</entry><entry>Mt: Vertebrate</entry></row>
<row><entry>mt-yeast</entry><entry> 3</entry><entry>Mt: Yeast</entry></row>
<row><entry>mt-protozoa</entry><entry> 4</entry><entry>*: Mold, Protozoan and Coelenterate Mitochondrial Code and Mycoplasma/Spiroplasma</entry></row>
<row><entry>mt-invert</entry><entry> 5</entry><entry>Mt: Invertebrate</entry></row>
<row><entry>nuc-ciliate</entry><entry> 6</entry><entry>Nuc: Ciliate, Dasycladacean and Hexamita</entry></row>
<row><entry>mt-echinoderm</entry><entry> 9</entry><entry>Mt:  Echinoderm and Flatworm</entry></row>
<row><entry>nuc-euplotid</entry><entry> 10</entry><entry>Nuc: Euplotid</entry></row>
<row><entry>bacteria</entry><entry> 11</entry><entry>*:   Bacterial, Archaeal and Plant Plastid</entry></row>
<row><entry>nuc-yeast-alt</entry><entry> 12</entry><entry>Nuc: Alternative Yeast</entry></row>
<row><entry>mt-ascidian</entry><entry> 13</entry><entry>Mt:  Ascidian</entry></row>
<row><entry>mt-flatworm-alt</entry><entry> 14</entry><entry>Mt:  Alternative Flatworm</entry></row>
<row><entry>nuc-blepharisma</entry><entry> 15</entry><entry>Nuc: Blepharisma Nuclear Code</entry></row>
<row><entry>mt-chlorophycean</entry><entry> 16</entry><entry>Mt:  Chlorophycean</entry></row>
<row><entry>mt-trematode</entry><entry> 21</entry><entry>Mt:   Trematode</entry></row>
<row><entry>mt-scenedesmus-obliquus</entry><entry> 22</entry><entry>Mt:   Scenedesmus obliquus</entry></row>
<row><entry>mt-thraustochytrium</entry><entry> 23</entry><entry>Mt:   Thraustochytrium</entry></row>
<row><entry>mt-rhabdopleuridae</entry><entry> 24</entry><entry>Mt:   Rhabdopleuridae</entry></row>
<row><entry>bacteria-sr1</entry><entry> 25</entry><entry>*:    Candidate Division SR1 and Gracilibacteria</entry></row>
<row><entry>nuc-pachysolen-tannophilus</entry><entry> 26</entry><entry>Nuc:  Pachysolen tannophilus</entry></row>
<row><entry>nuc-karyorelict</entry><entry> 27</entry><entry>Nuc:  Karyorelict</entry></row>
<row><entry>nuc-condylostoma</entry><entry> 28</entry><entry>Nuc:  Condylostoma</entry></row>
<row><entry>nuc-mesodinium</entry><entry> 29</entry><entry>Nuc:  Mesodinium</entry></row>
<row><entry>nuc-peritrich</entry><entry> 30</entry><entry>Nuc:  Peritrich</entry></row>
<row><entry>nuc-blastocrithidia</entry><entry> 31</entry><entry>Nuc:  Blastocrithidia</entry></row>
<row><entry>mt-cephalodiscidae</entry><entry> 33</entry><entry>Mt:   Cephalodiscidae UAA-Tyr</entry></row>

            </tbody>
          </tgroup>
        </informaltable>
	      

	<para>Genetic codes may be specified by name or by <userinput>code<replaceable>n</replaceable></userinput> where <replaceable>n</replaceable> is the code number.
        For example <userinput>code1</userinput> is the standard code.
If the genetic code is not specified, then the standard code is used:
<screen><prompt>%</prompt> bali-phy <replaceable>sequence-file</replaceable> -S gy94 -A Codons
<prompt>%</prompt> bali-phy <replaceable>sequence-file</replaceable> -S gy94 -A Codons(RNA)</screen>
	These examples specify the vertebrate mitochondrial code:
	<screen><prompt>%</prompt> bali-phy <replaceable>sequence-file</replaceable> -S gy94 -A Codons(DNA,mt-vert)
<prompt>%</prompt> bali-phy <replaceable>sequence-file</replaceable> -S gy94 -A Codons(,mt-vert)</screen>	
</para>
      </section>
      <section>
	<info><title>Heterogeneous dN/dS and tests for positive selection</title></info>
	<informaltable>
	  <tgroup cols="3">
	    <thead><row>
	      <entry>Model</entry>
	      <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	      <entry>Summary</entry>
	    </row></thead>
	    <tbody>
	      
	      <row>
		<entry>
		  <para><userinput>m1a</userinput></para>
		</entry>
		<entry>df(<replaceable>submodel</replaceable>)+2</entry>
		<entry>
		  <para>A mixture of conserved and neutral sites.</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1534/genetics.104.031153">
		    (Wong et al., 2004)
		  </link>
		</entry>
	      </row>

	      <row>
		<entry>
		  <para><userinput>m2a</userinput></para>
		</entry>
		<entry>df(<replaceable>submodel</replaceable>)+4</entry>
		<entry>
		  <para>A mixture of conserved, neutral, and positively-selected sites.</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1534/genetics.104.031153">
		    (Wong et al., 2004)
		  </link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>m2a_test</userinput></entry>
		<entry>df(<replaceable>submodel</replaceable>)+4</entry>
		<entry>
		  <para>A Bayesian test for positive selection that compares M2a with M1a.</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1534/genetics.104.031153">
		    (Wong et al., 2004)
		  </link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>m3</userinput></entry>
		<entry>df(<replaceable>submodel</replaceable>)+2*$n$-1</entry>
		<entry><para>An free mixture of $n$ categories of conserved dN/dS values.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/genetics/155.1.431">
		  (Yang et al., 2000)
		</link>
		</entry>
	      </row>

	      <row>
		<entry>
		  <para><userinput>m3_test</userinput></para>
		</entry>
		<entry>df(<replaceable>submodel</replaceable>)+2*$n$+1</entry>
		<entry>
		  <para>A Bayesian test for positive selection based on the M3 model extended with an extra category of either neutral of positively-selected sites.</para>
		</entry>
	      </row>

	      <row>
		<entry><para><userinput>m7</userinput></para></entry>
		<entry>df(<replaceable>submodel</replaceable>)+2</entry>
		<entry><para>The M7 model places a beta distribution on dN/dS.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/genetics/155.1.431">
		  (Yang et al., 2000)
		</link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>m8a</userinput></entry>
		<entry>df(<replaceable>submodel</replaceable>)+3</entry>
		<entry><para>The M8a model adds a category of <emphasis>neutral</emphasis> sites to the M7 model.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a004233">
		  (Swanson et al., 2003)
		</link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>m8</userinput></entry>
		<entry>df(<replaceable>submodel</replaceable>)+4</entry>
		<entry><para>The M8 model adds a category of <emphasis>positively-selected</emphasis> sites to the M7 model.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/genetics/155.1.431">
		  (Yang et al., 2000)
		</link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>m8a_test</userinput></entry>
		<entry>df(<replaceable>submodel</replaceable>)+4</entry>
		<entry><para>A Bayesian test for positive selection that compares the M8 to the M8a model.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a004233">
		  (Swanson et al., 2003)
		</link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>branch_site</userinput></entry>
		<entry>df(<replaceable>submodel</replaceable>)+4</entry>
		<entry><para>A Bayesian test for positive selection that on some (unknown) sites and some (known) branches.</para>
		<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/molbev/msi237">
		  (Zhang et al., 2005)
		</link>
		</entry>

	      </row>

	    </tbody>

	  </tgroup>
	</informaltable>
      </section>

      <section><info><title>The branch-site substitution model</title></info>
      <para>In order to use the branch-site substitution model, the user needs to specify an unrooted tree topology and fix the topology:
    <screen><prompt>%</prompt> bali-phy <replaceable>alignment</replaceable>.fasta -S branch_site -T <replaceable>tree</replaceable>.tree --fix=topology</screen>
    The tree file should be in Newick format, with foreground branches labelled using &amp; attributes. The attribute must be applied to the branch, not the node, so it must occur after a colon.

<example><title>An tree with a foreground branch</title>
(((A1, B1),(C1, D1)),((E1:[&amp;foreground=1], F1:[&amp;foreground=1]),(G1, H1)),(((A2, B2),(C2, D2)),((E2, F2),(G2, H2))));
</example>
      </para>
      <para>The posterior probability of positive selection is the posterior mean of the posSelection parameter.  This may be computed using the statreport program with the <userinput>--mean</userinput> option. In case this probability is extremely close to 1 or 0, you may wish to add the option <userinput>--Rao-Blackwellize branch_site:posSelection</userinput>.  This will report the log-probability of positive selection each iteration.  The user may exponentiate the reported values and then average them (using R, for example) in order to compute a more accurate estimate of the posterior probability of positive selection.
      </para>
      </section>

    </section>

    <section><info><title>Heterogenous Rates across Sites</title></info>
    
    <para>
      Complex substitution models in <application>BAli-Phy</application>
      are constructed as mixtures of reversible CTMC models that run at different rates (e.g. $\Gamma_4 + INV$)
      or have different parameters (e.g. an M2a codon model).
    </para>

      <informaltable>

      <tgroup cols="3">
	  <thead><row>
	      <entry>Model</entry>
	      <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	      <entry>Summary</entry>
	  </row></thead>
	  <tbody>

	    <row>
	      <entry><userinput><replaceable>submodel</replaceable>&nbsp;+>&nbsp;Rates.gamma</userinput></entry>
	      <entry>df(<replaceable>submodel</replaceable>)+1</entry>
	      <entry><para>Site rates follow a discrete approximation to the Gamma distribution</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1007/BF00160154">
		    (Yang, 1994)
		  </link>
	      </entry>
	    </row>

	    <row>
	      <entry>
		<para><userinput><replaceable>submodel</replaceable>&nbsp;+>&nbsp;Rates.log_normal</userinput></para>
	      </entry>
	      <entry>df(<replaceable>submodel</replaceable>)+1</entry>
	      <entry><para>Site rates follow a discrete approximation to the logNormal distribution</para>
	      </entry>
	    </row>

	    <row>
	      <entry><para><userinput><replaceable>submodel</replaceable>&nbsp;+>&nbsp;Rates.free</userinput></para></entry>
	      <entry>df(<replaceable>submodel</replaceable>)+2($n$-1)</entry>
	      <entry><para>Sites fall in one of $n$ categories. Each category has its own rate.</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1093/genetics/139.2.993">
		    (Yang, 1995)
		  </link>
	      </entry>
	    </row>

	    <row>
	      <entry><userinput><replaceable>submodel</replaceable>&nbsp;+>&nbsp;multi_rate(<replaceable>dist</replaceable>)</userinput></entry>
	      <entry>df(<replaceable>submodel</replaceable>)+df(<replaceable>dist</replaceable>)</entry>
	      <entry><para>Site rates follow a discrete approximation to the distribution <replaceable>dist</replaceable>.</para></entry>
	    </row>

	    <row>
	      <entry><userinput><replaceable>submodel</replaceable>&nbsp;+>&nbsp;inv</userinput></entry>
	      <entry>df(<replaceable>submodel</replaceable>)+1</entry>
	      <entry><para>Some fraction inv:p_inv of sites are invariable.</para>
	      </entry>
	    </row>
	  </tbody>
	</tgroup>
      </informaltable>

    </section>
    <section xml:id="covarion_models">
      <info><title>Heterotachy models</title></info>
      <para>
        These models attempt to model the fact that evolutionary rates may change over time within a single column.
        These models are sometimes called "covarion" models, based on the idea that changes in rate might be caused
        by changes in an unspecified covarying site.
      </para>
      <para>
        These models are "Markov modulated" models that create multiple different states for each letter by augmenting
        each letter with some unobserved hidden state.  They attempt to model the fact that substitution processes might
        not be Markov on the letters, but might become more Markov given the hidden state.
      </para>

      <informaltable>
      <tgroup cols="3">
	  <thead><row>
	      <entry>Model</entry>
	      <entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
	      <entry>Summary</entry>
	  </row></thead>
	  <tbody>

	    <row>
	      <entry><userinput><replaceable>Q</replaceable>&nbsp;+>&nbsp;Covarion.ts98</userinput></entry>
	      <entry>df(<replaceable>submodel</replaceable>)+2</entry>
	      <entry>
                <para>Each state in rate matrix Q is split into an ON and OFF variant.  Models burstiness.</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink"  xlink:href="https://doi.org/10.1016/S0025-5564(97)00081-3">
		    (Tuffley and Steel, 1998)
		  </link>
	      </entry>
	    </row>

	    <row>
	      <entry>
                <para><userinput><replaceable>Q</replaceable>&nbsp;+>&nbsp;Rates.gamma&nbsp;+>&nbsp;Covarion.hb02</userinput></para>
                <para><userinput><replaceable>submodel</replaceable>&nbsp;+>&nbsp;Covarion.hb02</userinput></para>
              </entry>
	      <entry>
                <para>df(<replaceable>Q+Rates.gamma</replaceable>)+2</para>
                <para>df(<replaceable>submodel</replaceable>)+2</para>
              </entry>
	      <entry>
                <para>Combines Gamma (or other) rate heterogeneity with the Tuffley-Steel model.</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink"  xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a004128">
		    (Huelsenbeck, 2002)
		  </link>
	      </entry>
	    </row>

	    <row>
	      <entry>
                <para><userinput><replaceable>Q</replaceable>&nbsp;+>&nbsp;Rates.gamma&nbsp;+>&nbsp;Covarion.gt01</userinput></para>
                <para><userinput><replaceable>submodel</replaceable>&nbsp;+>&nbsp;Covarion.gt01</userinput></para>
              </entry>
	      <entry>
                <para>df(<replaceable>Q+Rates.gamma</replaceable>)+2</para>
                <para>df(<replaceable>submodel</replaceable>)+2</para>
              </entry>
	      <entry>
                <para>Allows switching between Gamma (or other) rate classes over time.  Models changes in conservation.</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink"  xlink:href="https://doi.org/10.1093/oxfordjournals.molbev.a003868">
		    (Galtier, 2001)
		  </link>
	      </entry>
	    </row>

	    <row>
	      <entry>
                <para><userinput><replaceable>Q</replaceable>&nbsp;+>&nbsp;Rates.gamma&nbsp;+>&nbsp;Covarion.wssr07</userinput></para>
                <para><userinput><replaceable>submodel</replaceable>&nbsp;+>&nbsp;Covarion.wssr07</userinput></para>
              </entry>
	      <entry>
                <para>df(<replaceable>Q+Rates.gamma</replaceable>)+4</para>
                <para>df(<replaceable>submodel</replaceable>)+4</para>
              </entry>
	      <entry>
                <para>Allows switching between ON/OFF states and <emphasis>also</emphasis> between Gamma (or other) rate classes over time.  Models both burstiness and changes in conservation.</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink"  xlink:href="https://doi.org/10.1093/molbev/msl155">
		    (Wang et al., 2007)
		  </link>
	      </entry>
	    </row>
          </tbody>1
	</tgroup>
      </informaltable>
      <para>
        <note>
          Note that the obvious way to combine the Tuffley-Steel model with rate heterogeneity is wrong:
          <itemizedlist>
            <listitem><para><userinput>Q +> Covarion.ts98 +> Rates.gamma</userinput>: This is <emphasis>wrong</emphasis>!  Under this model, sites with faster substitution rates will switch between the ON/OFF states faster.</para></listitem>
            <listitem><para><userinput>Q +> Rates.gamma +> Covarion.hb02</userinput>: This is correct.  Sites switch between ON/OFF states independent of the speed of substitution.</para></listitem>
          </itemizedlist>
        </note>
      </para>
    </section>
  </section>


    <section xml:id="indel_models"><info><title>Insertion/deletion models</title></info>
      
    <para>Each of these models is a probability distribution on pairwise alignments.  The probability distribution on multiple sequence alignments $\Pr(A|T,\tau,\Lambda)$ is constructed by factoring the multiple sequence alignment into pairwise alignments along each branch of the tree, as described in Redelings and Suchard (2005).</para>

	<para>The default insertion/deletion model is <userinput>rs07</userinput>.</para>
	
    <informaltable>
	  
	  <tgroup cols="3">
	    <colspec colnum="1" colname="col1" colwidth="1*"/>
	    <colspec colnum="2" colname="col2" colwidth="1*"/>
	    <colspec colnum="3" colname="col3" colwidth="1*"/>
	    <thead><row>
		<entry>Model</entry>
		<entry>&nbsp;&nbsp;d.f.&nbsp;&nbsp;</entry>
		<entry>Summary</entry>
	    </row></thead>
	    <tbody>	    
	      <row>
		<entry><userinput>rs05</userinput></entry>
		<entry>3</entry>
		<entry>
		  <para>A symmetric insertion-deletion model with geometrically-distributed indel lengths.</para>
		  <para>Indels occur on all branches with the same probability, regardless of branch length.</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1080/10635150590947041">
		    (Redelings and Suchard, 2005)
		  </link>
		</entry>
	      </row>

	      <row>
		<entry><userinput>rs07</userinput></entry>
		<entry>2</entry>
		<entry>
		  <para>A symmetric insertion-deletion model with geometrically-distributed indel lengths.</para>
		  <para>Longer branches have more indels.</para>
		  <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1186/1471-2148-7-40">
		    (Redelings and Suchard, 2007)
		  </link>
		</entry>
	      </row>
	      
	      <row>
		<entry>
		  <para><userinput>none</userinput></para>
		</entry>
		<entry/>
		<entry>
		  <para>No indel model for the partition, indels uninformative.</para>
		  <para>Fixed alignment for the partition.</para>
		</entry>
	      </row>
	      
	    </tbody>
	  </tgroup>
	</informaltable>
	    
	<para>The user can specify priors and parameters for indel models (See section <xref linkend="functions"/>):
<programlisting>rs07(log_rate~log_laplace(-4,0.707),mean_length=2)</programlisting>
	</para>

    </section>

  <section xml:id="functions"><info><title>Models and Priors</title></info>

  <section><info><title>Models and distributions are functions</title></info>
  <para>Models, probability distributions, and functions are treated the same in BAli-Phy because all of them have parameters or arguments. Parameters have names in BAli-Phy.  Parameter values are specified using square brackets as follows:
  <programlisting>hky85(kappa=2)            // model
log(x=2)                  // function
normal(mean=0,sigma=1)    // probability distribution</programlisting>
It is possible to specify parameter values by position instead of by name:
  <programlisting>hky85(2)
log(2)
normal(0,1)</programlisting>
It is even possible to mix positional and named arguments, as long as all the positional arguments come before all the named arguments:
<programlisting>normal(0,sigma=1)   // OK
normal(mean=0,1)    // not OK</programlisting>

  The order and type of parameters for a function can be found with the <userinput>help</userinput> command.  For example,
<screen><prompt>%</prompt> <userinput>bali-phy help hky85</userinput></screen>
A value must be given for each parameter, unless the parameter has a default value (See <xref linkend="default_values"/>).
  </para>
	<note>
	  <para>
	    You need to put single quotes around terms with parenthesis or square brackets on the command-line:
<screen><prompt>%</prompt> <userinput>bali-phy file.fasta -S 'hky85(kappa=2)'</userinput>
<prompt>%</prompt> <userinput>bali-phy file.fasta -S 'mixture([tn93,hky85(2)])'</userinput></screen>
	  </para>

	  <para>If you do not add quotes, the shell will try to interpret the parentheses or square brackets and give an error message
                without running bali-phy.  For example, "<computeroutput>-bash: syntax error near unexpected token `('</computeroutput>" (for <command>bash</command>) or
          "<computeroutput>Badly placed ()'s</computeroutput>" (for <command>csh</command>) or "<computeroutput>zsh: no matches found: mixture([tn93,hky85(2)])</computeroutput>" (for <command>zsh</command>).
	  </para>
	</note>

  </section>

  <section><info><title>Models and '<userinput>+></userinput>' notation</title></info>
  <para>Models in phylogenetics literature are often combined using <userinput>+</userinput>. For example, the model <userinput>WAG + F + G4 + I</userinput> starts with the WAG amino-acid model, and places several modifiers, like " + G4" on the right.</para>
  <para>BAli-Phy follows this convention by treating <userinput>A +> B</userinput> as an abbreviation for <userinput>B(submodel=A)</userinput>.  When there are multiple '<userinput>+></userinput>' symbols they associate to the left, so that <userinput>A +> B +> C</userinput> is understood to mean <userinput>(A +> B) +> C</userinput>.  For example:
<programlisting>hky85 + Rates.gamma               // rewritten to Rates.gamma(submodel=hky85)
hky85 +> inv                      // rewritten to inv(submodel=hky85)
wag +> f                          // rewritten to f(submodel=wag)
wag +> f +> Rates.gamma +> inv    // rewritten to inv(submodel=Rates.gamma(submodel=f(submodel=wag)))
</programlisting>
This allows a simple method for combining models, when one model is an argument to another model.
</para>
  </section>

  <section xml:id="priors"><info><title>Priors</title></info>
  <section><info><title>Specifying priors</title></info>
<para>Priors on model parameters are specified by giving a random value. Random values can be obtained from distributions using the function <userinput>sample</userinput>.  For example, this places a log-normal prior on the parameter <userinput>kappa</userinput> of the <userinput>hky85</userinput> model:
<programlisting>hky85(kappa=sample(log_normal(1,1)))</programlisting>
You can write <userinput>~Dist</userinput> as a shorthand for <userinput>sample(Dist)</userinput>:
<programlisting>hky85(kappa = ~log_normal(1,1))</programlisting>
The <userinput>=~</userinput> can be further shortened to just <userinput>~</userinput>:
<programlisting>hky85(kappa ~ log_normal(1,1))</programlisting>
</para>
</section>

  <section><info><title>Random function arguments</title></info>
<para>It also is possible to use random values as inputs to other functions.  For example:
<programlisting>1.0 + ~exponential(10)</programlisting>
In such cases the parameter value should be specified with <userinput>=</userinput>, as in the following example:
<programlisting>rs07(mean_length=1.0 + ~exponential(10))</programlisting>
</para>
  </section>
<section><info><title>Distributions are not random values</title></info>
<para>Random values and distributions have different types.  For example, the
following is of type <userinput>Distribution&lt;Double&gt;</userinput>:
<programlisting>uniform(0,1)</programlisting>
In contrast, the following are both of type <userinput>Double</userinput>:
<programlisting>sample(uniform(0,1))
~uniform(0,1)</programlisting>
This is important when passing distributions as arguments to other
distributions and functions.  For example, the distribution <userinput>iid</userinput> is used to generate a specific number of samples from another distribution.  Thus, it needs to receive a distribution as an argument:
<programlisting>~iid(4, normal(0,1))      // OK    : 4 samples from the normal(0,1) distribution
~iid(4, ~normal(0,1))     // not OK: 4 samples from ... a random number?</programlisting>
(See <xref linkend="types"/>.)
</para>
  </section>
  </section>

  <section xml:id="default_values"><info><title>Default values and default priors</title></info>
  <para>
Some function arguments have default values.  For example, the <userinput>Rates.gamma</userinput> parameter <userinput>n</userinput> has a default value of 4.  Thus the following are equivalent:
<programlisting>hky85 +> Rates.gamma(n=4) +> inv
hky85 +> Rates.gamma +> inv</programlisting></para>

  <para>When the default value is random, then the argument has a default prior. For example, the <userinput>kappa</userinput> parameter of <userinput>hky85</userinput> has a default value of <userinput>~log_normal(log(2),0.25)</userinput>, so the following are equivalent:
<programlisting>hky85(kappa~log_normal(log(2),0.25))
hky85</programlisting>
The <userinput>help</userinput> command can be used to determine the default value for a parameter, if there is one.</para>
  </section>

  <section xml:id="types"><info><title>Argument and result types</title></info>
  <para>  Every function has a <emphasis>result type</emphasis>, as well as an <emphasis>argument type</emphasis> for each argument.  The argument type specifies what kind of arguments are acceptable, and the result type specifies what kind of result the function produces.  Types include <userinput>Int</userinput> for integers, <userinput>Double</userinput> for double-precision floating point numbers, and <userinput>String</userinput> for text strings.  Integer arguments are implicitly converted to <userinput>Double</userinput> when the argument type is <userinput>Double</userinput>.</para>

  <para>Some types contain parameters.  For example <userinput>List&lt;Int&gt;</userinput> indicates a list of integers and <userinput>List&lt;Double&gt;</userinput> indicates a list of real numbers.  In order to indicate a list of unknown type, we use a <emphasis>type variable</emphasis> <userinput>a</userinput> and write <userinput>List&lt;a&gt;</userinput>.  Type variables always begin with a lower-case letter.  They are able to match any specific type, and their value is found by pattern-matching.  For example, the function <userinput>x+y</userinput> takes two arguments of type <userinput>a</userinput> and has a result of type <userinput>a</userinput>.  Thus:
<programlisting>1 + 2        // arguments are a=Int, so result is of type Int
1.0 + 2.0    // arguments are a=Double, so result is of type Double</programlisting>
<userinput>(a,b)</userinput> is a parameterized type that can be specialized to (for example) <userinput>(String,Double)</userinput> and <userinput>(Int,Int)</userinput>.
  </para>

  <para>Types for components of substitution models are often parameterized by type of the alphabet.  For example, hky85 has a result type of <userinput>RevCTMC&lt;a&gt;</userinput>, where <userinput>a</userinput> could be <userinput>DNA</userinput> or <userinput>RNA</userinput>.  The use of alphabet types in substitution models prevents combining substitution models with mismatched alphabets.
  </para>

  </section>
  </section>
    

    <section><info><title>Partitioned data sets</title></info>

    <section><info><title>Partitions</title></info>
    <para>You should analyze multiple genes under different evolutionary models by putting each one it its own data partition.  Placing different genes in different partitions means that their alignments vary independently.  It also prevents sequences in one gene from being aligned against sequences in another gene.</para>

    <para>Different partitions share the same tree topology and a common set of unscaled branch lengths.  However, branch lengths are scaled by a different factor in each partition, since some genes may evolve faster than others.</para>

    <para>To put different genes in different partitions, you can place the sequences from each partition in a different FASTA or Phylip file.     The sequence names in files for all partitions should be the same. 
    <screen><prompt>%</prompt> <userinput>bali-phy gene1.fasta gene2.fasta</userinput></screen>
    You can also select different sites from a single larger file:
    <screen><prompt>%</prompt> <userinput>bali-phy sequences.fasta:3-350 sequences.fasta:351-570</userinput></screen>
    </para>
    </section>

    <section><info><title>Unlinked models</title></info>
    <para>By default, each partition will have its own substitution model, insertion/deletion model, and scaled tree length.  For example, even if all partitions are assigned a <userinput>tn93</userinput> substitution model, their base frequencies will all be estimated independently.  When parameters are estimated separately for two partitions, we say that the parameters for those partitions are "unlinked".</para>

    <para>A substitution model or insertion-deletion model that is specified without qualification will apply to every partition.  However, each partition will recieve its own copy of each model with unlinked parameter values:
      <screen><prompt>%</prompt> <userinput>bali-phy <replaceable>sequence-file1</replaceable> <replaceable>sequence-file2</replaceable> -S tn93 -I rs07</userinput></screen></para>

<para>You can select partition-specific values for 4 options: <userinput>-S</userinput>, <userinput>-I</userinput>, <userinput>-A</userinput>, and <userinput>--scale</userinput>.  For example, to specify different substitution models but the same alphabet:
<screen><prompt>%</prompt> <userinput>bali-phy <replaceable>sequence-file1</replaceable> <replaceable>sequence-file2</replaceable> -S 1:tn93 -S 2:gtr -A DNA</userinput></screen></para>
    </section>

    <section><info><title>Fixing the alignment in some partitions</title></info>
<para>You can fix the alignment and ignore insertion/deletion information in one partition, while allowing the alignment to vary and using insertion/deletion information in another partition:
<screen><prompt>%</prompt> <userinput>bali-phy <replaceable>sequence-file1</replaceable> <replaceable>sequence-file2</replaceable> -I 2:none</userinput></screen>
Since alignments are estimated by default, the alignment will be estimated in the first partition, but fixed in the second partition.</para>
<para>Specifying specify <userinput>-I none</userinput> fixes the alignment in all partitions:
<screen><prompt>%</prompt> <userinput>bali-phy <replaceable>sequence-file1</replaceable> <replaceable>sequence-file2</replaceable> -I none</userinput></screen>
</para>
    </section>
    <section><info><title>Linked models</title></info>
<para>You can also specify that two partitions share a single copy of a single substitution model or indel model.  For example, if two partitions both have a <userinput>tn93</userinput> model, linking these models would force the partitions to have the same nucleotide frequencies and substitution rates.  Linking partitions reduces the number of parameters that need to be estimated, and also pools information between the partitions:
<screen><prompt>%</prompt> <userinput>bali-phy <replaceable>sequence-file1</replaceable> <replaceable>sequence-file2</replaceable> -S 1,2:tn93 -I 1,2:rs07</userinput></screen>
By default each partition has a separate scale, but you can force groups of partitions to share a scale as follows:
<screen><prompt>%</prompt> <userinput>bali-phy <replaceable>sequence-file1</replaceable> <replaceable>sequence-file2</replaceable> --scale 1,2:</userinput></screen>
</para>
    </section>
    <section><info><title>Linking models via the <userinput>link</userinput> command</title></info>

    <para>The <userinput>--link</userinput> command is provided to allow specifying a model for each partition separately, and then afterwards choose which partitions to link.
    <screen><prompt>%</prompt> <userinput>bali-phy <replaceable>sequence-file1</replaceable> <replaceable>sequence-file2</replaceable> -S 1:tn93 -S 2:tn93 --link=1,2 -t</userinput>
<prompt>%</prompt> <userinput>bali-phy <replaceable>sequence-file1</replaceable> <replaceable>sequence-file2</replaceable> -S tn93             --link=1,2 -t</userinput>   </screen>
    If the linked partitions are given different models, BAli-Phy will give an error and refuse to run:
    <screen><prompt>%</prompt> <userinput>bali-phy <replaceable>sequence-file1</replaceable> <replaceable>sequence-file2</replaceable> -S 1:tn93 --link=1,2 -t</userinput>
bali-phy: Error! Partitions 1 and 2 cannot be linked because they have differing values 'tn93' and ''</screen></para>
    <para>You can also specify which of the 3 attributes "smodel", "imodel", and "scale" are being linked:
    <screen><prompt>%</prompt> <userinput>bali-phy <replaceable>sequence-file1</replaceable> <replaceable>sequence-file2</replaceable> --link=1,2:smodel,scale -t</userinput>    // Don&apos;t link the indel model</screen>
    </para>
    </section>
    </section>

    <section xml:id="ancestral_sequence_reconstruction">
      <info><title>Ancestral sequence reconstruction</title></info>

      <section>
        <info><title>Ancestral sequences with gaps</title></info>
        <para>
          BAli-Phy can reconstruct ancestral sequences for all internal nodes. Unlike some programs,
          BAli-Phy explicitly infers the presence and absence of characters in ancestral sequences. This
          means that if the ancestral sequence has no character for a column, the reconstructed
          ancestors will have a gap there. BAli-Phy reconstructs ancestors for fixed-alignment partitions
          as well as variable-alignment partitions, but it won&apos;t write out fixed alignment samples unless
          you add the flag <userinput>--set write-fixed-alignments=true</userinput>. Additionally, if you
          have an ambiguous character such as <userinput>N</userinput> in an observed sequence bali-phy
          can impute this character, but will not do so unless you add the flag
          <userinput>--set infer-ambiguous-observed=true</userinput>.
        </para>
      </section>

    <section>
      <info><title>Generating a summary alignment with ancestral sequences</title></info>

    <para>BAli-Phy can now reconstruct ancestral sequences for a given tree topology and (leaf sequence) alignment.
    This is similar to the ancestor-reconstruction that is usually done for fixed-alignment analyses.
    However, it is not quite the same, because of uncertainty in the tree and the alignment.
    When computing the probability of an ancestral residue, this summary averages over uncertainty in the topology,
    the alignment, and the ancestral state itself. 

    <screen># Construct the leaf sequence alignment to annotate using posterior decoding
<prompt>%</prompt> <userinput>cut-range <replaceable>dir</replaceable>-1/C1.P1.fastas <replaceable>dir</replaceable>-2/C1.P1.fastas --skip=<replaceable>burn-in</replaceable> | alignment-chop-internal --tree c50.tree | alignment-max &gt; P1-max.fasta</userinput>
# Construct the tree topology to annotate
<prompt>%</prompt> <userinput>trees-consensus <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees | tree-tool - --strip-internal-names --name-all-nodes &gt; c50.tree</userinput>
# Reconstruct ancestral sequences on the given tree and alignment
<prompt>%</prompt> <userinput>summarize-ancestors P1.max.fasta -A <replaceable>dir</replaceable>-1/C1.P1.fastas -T <replaceable>dir</replaceable>-1/C1.trees -A <replaceable>dir</replaceable>-2/C1.P1.fastas -T <replaceable>dir</replaceable>-2/C1.trees -n c50.tree -g c50.tree > P1.ancestors.fasta</userinput></screen>
    
BAli-Phy uses an alignment estimate (here, P1-max.fasta) as a template to construct a summary alignment with ancestral sequences.  BAli-Phy doesn&apos;t condition on the alignment columns, because (i) many columns occur only once in a posterior sample and (ii) conditioning on the column gives too much weight to the template alignment.
</para>

<para>Because the alignment is uncertain, residues in the same column of the template alignment may end up in different columns in an MCMC sample.  Therefore, in a given MCMC sample, different leaf residues in the same column may have different ancestors at the same internal node!  However, in our ancestral reconstruction, a given column may only display a single ancestral residue.</para>

<para>BAli-Phy addresses this problem by averaging across the different ancestral residues in each column of the template alignment.  When identifying the ancestral character to column C from a sampled alignment A, we random select a residue in C and use it to select a column from A.  This procedure has the nice property that it will yield the traditional ancestral residue prediction if the alignment column is fixed.
    </para>
    </section>

      <section>
        <info><title>Sampled alignments contain ancestral sequences</title></info>
        <para>
          Ancestral sequences are written as part of the alignment matrix in each iteration.  Ancestral sequences
          are given names starting with the letter <userinput>A</userinput>.  For example, in the
          following alignment, the sequences <userinput>A5</userinput>, <userinput>A6</userinput>, and
          <userinput>A7</userinput> are reconstructed ancestors:
          <programlisting>&gt;Halobacterium
-T-TAAGGCGGCCATAGCGGTGGGGTTACTCCCGTAC
&gt;Pyrococcus
GG-TACGGCGGTCATAGCGGGGGGGCCACACCCGGTC
&gt;Sulfolobus
GC-CCACCCGGTCACAGTGAGCGGGCAACACCCGGAC
&gt;Homo
GTCTACGGC---CATACCACCCTGAACGCGCCCGATC
&gt;Escherichia
TG-CCTGGCGGCCGTAGCGCGGTGGTCCCACCTGACC
&gt;A5   
GG-CAAGGCGGCCATAGCGGGGGGGCCACACCCGGCC
&gt;A6   
GT-CAAGGCGGCCATAGCGGGGGGGCTACACCCGGTC
&gt;A7   
GT-CAAGGCGGCCATAGCGGGGGGGCTACACCCGGTC</programlisting>
          Sampled alignments for the <replaceable>n</replaceable>th partition are in the file.
          <filename>C1.P<replaceable>n</replaceable>.fastas</filename>. 
        </para>
        <para>
          Ancestral states in these alignments are randomly sampled from their joint posterior and do
          <emphasis>not</emphasis> represent the most probable ancestral state.  The alignment of
          ancestral sequences is also inferred, so these sequences may contain gaps.  The length of
          ancestral sequences may vary between samples when the length of the ancestral sequence is
          uncertain.
        </para>
      </section>

      <section>
        <info><title>Sampled alignments correspond to specific sampled trees</title></info>
        <para>
          Each sampled alignment matrix corresponds to a tree in the file <filename>C1.trees</filename>
          that is written in the same iteration. This tree specifies the phylogenetic location of each
          ancestral sequence by labelling the internal nodes of the tree.  For example, the tree below
          shows where the internal nodes <userinput>A5</userinput>, <userinput>A6</userinput>, and <userinput>A7</userinput> are
          located on the tree:
          <programlisting>(Halobacterium:0.213240,((Escherichia:0.435762,Pyrococcus:0.122678)<emphasis role="strong">A5</emphasis>:0.114725,Sulfolobus:0.427210))<emphasis role="strong">A6</emphasis>:0.042527,Homo:0.427026))<emphasis role="strong">A7</emphasis>;</programlisting>
          While the tree is written every iteration, the alignment is only written every 10 iterations
          (by default) in order to save disk space.  One method for extracting the trees that correspond
          to saved alignments is to extract every 10th tree with the program
          <userinput>bali-subsample</userinput>: 
            <screen><prompt>%</prompt> <userinput>bali-subsample 10 &lt; C1.trees &gt; C1.10.trees</userinput></screen>
        </para>
    </section>

    <section>
      <info><title>Tree uncertainty in ancestral sequence reconstruction.</title></info>
      <para>
        In Bayesian phylogenetic analyses, the tree is not fixed. Therefore the internal node
        corresponding to the ancestral sequence you wish to reconstruct may not exist in every iteration.  The standard Bayesian approach to tree uncertainty is to reconstruct the ancestor for each 
        node by conditioning on the existence of that node in the tree.  This allows the reconstructed
        ancestor for each node to average over uncertainty about the existence of other nodes.
      </para>
      <para>
        BAli-Phy additionally allows the researcher to condition on branches, since a branch
        condition is less restrictive.  BAli-Phy does not run a separate MCMC chain with a tree constraint for each node, but instead performs conditioning by selecting samples from a single run that satisfy the  condition.
      </para>
    <section>
      <info><title>Extracting and naming sequences that satisfy a query</title></info>
      <para>
        Note that the sequence names (e.g. A6) for internal nodes may change over time. Therefore, you
        cannot simply extract ancestral sequences with a given name.

        To extract ancestral sequences for a given node, you need to specify a method of identifying
        that node on a tree, and a name to give to the sequence at that node.  This is called a
        <emphasis>query</emphasis>.
      </para>
        <para>For example, you might
        specify how to identify the ancestor node of Eukaryotes, and the name "Eukaryotes" to use for the
        sequence there.  You can then use the program <userinput>extract-ancestors</userinput> to
        extract ancestral sequences from the sampled trees and alignment, and label them with useable names.

    <screen><prompt>%</prompt> <userinput>trees-consensus <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees | tree-tool - --strip-internal-names --name-all-nodes &gt; c50.tree</userinput>
<prompt>%</prompt> <userinput>extract-ancestors -A <replaceable>dir</replaceable>-1/C1.P1.fastas -T <replaceable>dir</replaceable>-1/C1.trees -A <replaceable>dir</replaceable>-2/C1.P1.fastas -T <replaceable>dir</replaceable>-2/C1.trees -n c50.tree -g c50.tree > P1.ancestors.fastas</userinput></screen>
       Here the options <userinput>-n c50.tree</userinput> and <userinput>-g c50.tree</userinput> specify
       node-based queries and branch-based queries.
    </para>
    </section>

    <section><info><title>Conditioning on a node: node-based queries</title></info>
    <para>A node exists in a sampled tree if every branch connected to that node exists in the sampled tree.
    A node-based query asks for the reconstructed ancestral sequence only from samples where every branch
    connected to that node exists. A node-based query is more stringent than a branch-based query, since it
    requires multiple branches to exist.</para>
    <para>BAli-Phy allows constructing node-based queries by passing in a Newick tree with labelled internal nodes.
    A node-based query is automatically constructed from each internal node that is labelled.
    </para>
    </section>

    <section><info><title>Conditioning on a branch: branch-based queries</title></info>
    <para>A branch-based query requires only that a single branch exist in a sampled tree.  The branch-based
    query asks for the reconstructed ancestral sequence on one endpoint of that (directed) branch.  When the focus
    is on changes that occur on a particular branch, this makes more sense than a node-based query.
    </para>
    <para>BAli-Phy allows constructing branch-based queries from a file where every line is either a Newick tree <emphasis>or</emphasis> a named group of taxa.  For each line that contains a Newick tree, a branch-based query is automatically constructed from each branch where <emphasis>both</emphasis> endpoints are labelled.  For a branch from <userinput>node1</userinput> to <userinput>node2</userinput>, the query is named <userinput>"node2&lt;=node1"</userinput>.
    </para>
    <para>
      Branch-based query files can also contain lines of the form
      <programlisting>name = taxon1 taxon2 ... taxonN</programlisting>
      This matches branches that separate the listed taxa from all other taxa, and points toward the listed taxa.
    </para>
    </section>

    </section>

    <!-- section><info><title>Alignment uncertainty in ancestral sequence reconstruction.</title></info>
    <para>
      Most programs for reconstructing ancestral sequences assume that the alignment is known.
      When this is true, identifying the ancestor at a particular node and column is trivial if the node exists in the tree.
    </para>
    <para>
      However, BAli-Phy allows estimating ancestral sequences when the alignment is not known.  This is more
      complicated, the length of the ancestral sequence at a given node may be different between different sample.
      Even worse, identifying the ancestral character in a given column no longer makes sense, since the particular
      set of leaf characters that identify the column may not always be aligned.
    </para>
    <para>
      Another way of stating this problem is that if we seek to identify the ancestral character for
      one letter in a column, it may be different that the ancestral character for another letter in the same column,
      since those two letters may not be homologous in a given ancestral sample.
    </para>
    <para>
      BAli-Phy currently solves this problem by selecting a representative letter in a template alignment to identify
      that column.  When finding the ancestral character from a particular sampled alignment, BAli-Phy chooses the
      ancestral character from the sampled alignment column that contains the representative letter.
      This approach collapses to the standard approach for columns that are definitely homologous.
      However, this is a challenging problem that is not completely solved.
    </para>
    </section -->


    <section><info><title>Statistical inferences without a summary alignment.</title></info>
    <para>Inferences about ancestral sequence are sometimes done by analyzing the summary alignment and
    its ancestral sequences.  A more correct approach is to analyze each sampled alignment separately, and then average the results.  (This yield the posterior mean of the analysis result.)
When this
    approach is feasible, it is more statistically rigorous than analyzing the summary alignment,
    because it operates on joint reconstructions and because it incorporates uncertainty in the
    phylogeny, alignment, and ancestral sequences.
    </para>
    <para>Analyzing the samples and pooling the results also allows each sampled alignment to be
    analyzed in combination with the corresponding sampled tree.</para>
    </section>


    </section>
  <section xml:id="mixing_and_convergence"><info><title>Convergence and Mixing: Is it done yet?</title></info>
    

    <para>
      When using Markov chain Monte Carlo (MCMC) programs like
      <application>MrBayes</application>, <application>BEAST</application> or
      <application>BAli-Phy</application>, it is hard to determine in
      advance how many iterations are required to give a good
      estimate. The number depends on the specific data set that is
      being examined. As a result, <application>BAli-Phy</application>
      relies on the user to analyze the output of a running chain
      periodically in order to determine when enough samples have been
      obtained.  This section describes a number of techniques to
      diagnose when more samples must be taken.
    </para>

    <para>Some of the better diagnostics for lack of convergence rely on running at least 2 independent copies of the Markov chain (preferably 4-10) from different random starting points to see if the sampled posterior distributions for each chain are the same.  Unfortunately, when the distributions all seem to be this same, this doesn&apos;t <emphasis>prove</emphasis> that they have all converged to the equilibrium distribution.  However, if the distributions are different then you can reject either convergence or good mixing.</para>

    <section><info><title>Definition of Convergence</title></info>
      

      <para>Convergence refers to the the tendency of a Markov chain to
	to "forget" its starting value and become typical of its
	equilibrium distribution. Note that convergence is a property
	of the Markov chain itself, not of individual runs of the
	Markov chain.  Ideally a number of individual runs should be
	examined in order to determine how many initial iterations to
	discard as "burnin".
      </para>
    </section>
    
    <section><info><title>Definition of Mixing</title></info>
      
      <para>
	In MCMC, each sample is not fully independent of previous
	samples.  In fact, even after a Markov chain has converged,
	it can get "stuck" in one part of the parameter space for a
	long time, before jumping to an equally important part.  When
	this happens, each new sample contributes very little new
	information, and we need to obtain many more samples to get
	good precision on our parameter estimates.  In such a case, we say 
	that the chain isn&apos;t "mixing" well. 
      </para>
    </section>

    
    <section><info><title>Diagnostics: Variation in split frequencies across runs (ASDSF/MSDSF)</title></info>
      
      <section><info><title>ASDSF and MSDSF</title></info>
	
<para>
To calculate the ASDSF and MSDSF run:
<screen><prompt>%</prompt> trees-bootstrap <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees ... <replaceable>dir-n</replaceable>/C1.trees &gt; partitions.bs</screen>	
For each split, the SDSF value is just the standard deviation across
runs of the Posterior Probabilities for that split.  By averaging the
resulting SDSF values across splits, we may obtain the ASDSF value
(Huelsenbeck and Ronquist 2001).  This is commonly considered
acceptable if it is &lt; 0.01.
</para>

<para>However, it is also useful to consider the maximum of the SDSF
  values (MSDSF).  This represents the range of variation in PP across
  the runs for the split with the most variation.
</para>
      </section>
      <section><info><title>Split-frequency comparison plot</title></info>
	
	<para>To generate the split-frequency comparison plot, you must have R installed.  Locate the script <filename>compare-runs.R</filename>.  Then run:
<screen><prompt>%</prompt> trees-bootstrap <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees ... <replaceable>dir-n</replaceable>/C1.trees --LOD-table=LOD-table &gt; partitions.bs 
<prompt>%</prompt> R --slave --vanilla --args LOD-table compare-SF.pdf &lt; compare-runs.R</screen>
	  Following <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1080/10635150600812544">Beiko et al. (2006)</link>, this displays the variation in
	  estimates of split frequencies across runs.  Splits are
	  arranged on the x-axis in increasing order of 
	  Posterior Probability (PP), which is obtained by averaging over
	  runs.  We then plot a vertical bar from the minimum PP to the
	  maximum PP.
	</para>
	</section>
    </section>


    <section><info><title>Diagnostics: Potential Scale Reduction Factors (PSRF)</title></info>
      
<para>
Potential Scale Reduction Factors check that different runs have
similar posterior distributions.  Only numerical variables may have a
PSRF. To calculate the PSRF for each
numerical parameter, you may run: 

<screen><prompt>%</prompt> statreport <replaceable>dir-1</replaceable>/C1.log <replaceable>dir-2</replaceable>/C2.p ... <replaceable>dir-n</replaceable>/C1.log &gt; Report </screen>
The PSRF is a ratio of the width of the pooled distribution to the
average width of each distribution, and should ideally be 1.  The PSRF
is customarily considered to be small enough if it is less than 1.01.
</para>

<para>
We compare the PSRF based on the length of 80% credible intervals
(Brooks and Gelman 1998) and report the result as PSRF-80%CI.  For
integer-valued parameters, we avoid excessively large PSRF values by
subtracting 1 from the width of the pooled CI.
</para>

<para>
We also report a new PSRF that is more sensitive for integer
distributions.  For each individual distribution, we find the 80%
credible interval.  We divide the probability of that interval (which
may be more than 80%) by the probability of the same interval under the
pooled distribution.  The average of this measure over all
distributions gives us a PSRF that we report as PSRF-RCF.
</para>

<para>This convergence diagnostic gives a criterion for
detecting when a parameter value has stabilized at different
values in several independent runs, indicating a lack of
convergence. This situation might occur if different runs of
the Markov chain were trapped in different modes and failed to
adequately mix between modes.</para>
    </section>

    <section><info><title>Diagnostics: Effective sample sizes (ESS)</title></info>
      
      <section><info><title>ESS for numerical values</title></info>
	
      <para>To calculate the split ESS values, run:
<screen><prompt>%</prompt> statreport <replaceable>dir-1</replaceable>/C1.log <replaceable>dir-2</replaceable>/C1.log ... <replaceable>dir-n</replaceable>/C1.log &gt; Report </screen>
      We calculate effective sample sizes based on integrated
      autocorrelation times.  This method has the nice property that
      simply duplicating every sample does not increase the ESS.
      </para>

      <para>The
      program <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://evolve.zoo.ox.ac.uk/software/tracer/">Tracer</link>
      also computes ESS values.</para>
      </section>

      <section><info><title>ESS for split frequencies</title></info>
	
      <para>As desribed in <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.3852/10-120">Gaya et al. (2011)</link>, we can also compute ESS values for splits on the tree:
<screen><prompt>%</prompt> trees-bootstrap <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees ... <replaceable>dir-n</replaceable>/C1.trees &gt; partitions.bs</screen>
      To compute the ESS for a split, we consider the presence or absence
      of a split in each iteration as a series of binary values.  We
      compute the integrated autocorrelation time for this binary
      sequence, which leads to an ESS.  This approach is similar to
      dividing the iterations into blocks and computing the ESS on the
      PP estimates in the blocks.  It is also similar to estimating
      the variance reduction under a block bootstrap.
      </para>
    </section>
</section>

    <section><info><title>Diagnostics: Stabilization</title></info>
      
      <section><info><title>Stabilization of numerical values</title></info>
	
<para>To obtain estimates of the stabilization time for each
numerical  parameter, you may run:
<screen><prompt>%</prompt> statreport C1.log &gt; Report </screen>
Each series of values is counted as having stabilized after
the series crosses its upper and then lower 95% confidence bounds
twice (if the initial value is below the median) or crosses its lower
and then upper confidence bounds twice (if the initial value is above
the median). The confidence bounds are those based on its
equilibrium distribution as calculated from the last third of the
values in the sequence.</para>
      </section>

      <section><info><title>Stabilization of tree topologies and tree distances</title></info>
	
	<para>In addition to examining convergence diagnostics for continuous
	parameters, it is important to examine convergence diagnostics
	for the topology as well
	(<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://doi.org/10.1080/10635150600812544">Beiko
	et al., 2006</link>).  In theory, we recommend the web tool <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://ceb.csit.fsu.edu/awty/">Are We There Yet (AWTY)</link> (Wilgenbush et al., 2004).  However, AWTY gives incorrect results if you upload plain NEWICK tree samples -- which is what BAli-Phy outputs.  Therefore, if you wish to use AWTY, you must convert the tree samples files to NEXUS before you upload them to AWTY in order to get correct results.</para>

<para>It is also be possible to assess stabilization of tree topologies using tools distributed with <application>bali-phy</application> by using commands like the following.  Here, sub-sampling and burnin does not apply to the equilibrium tree files. Also, note that you need to manually construct the equilibrium samples, which we recommend to contain at least 500 trees; you might do this by sub-sampling using the <application>BAli-Phy</application> tool <command>sub-sample</command>.</para>

<orderedlist inheritnum="ignore" continuation="restarts">
<listitem><para>To report the average distances within and between two tree samples:
<screen><prompt>%</prompt> trees-distances --skip=<replaceable>burnin</replaceable> --subsample=<replaceable>factor</replaceable> compare <replaceable>dir-1</replaceable>/C1.trees <replaceable>dir-2</replaceable>/C1.trees</screen>
</para></listitem>

<listitem><para>To compute the distance from each tree in C1.trees to all trees equilibrium.trees, as a time series:
<screen><prompt>%</prompt> trees-distances --skip=<replaceable>burnin</replaceable> --subsample=<replaceable>factor</replaceable> convergence <filename>C1.trees</filename> <filename>equilibrium.trees</filename></screen>
</para></listitem>

<listitem><para>To assess when the above time series stabilizes:
<screen><prompt>%</prompt> trees-distances --skip=<replaceable>burnin</replaceable> --subsample=<replaceable>factor</replaceable> converged <filename>C1.trees</filename> <filename>equilibrium.trees</filename></screen>
The stabilization criterion is the same one described above for numerical values.
</para></listitem>
</orderedlist>

<para>Note that the running time is the product of the number of trees in the two files.  Therefore, comparing two complete tree samples without sub-sampling will take too long.</para>

   </section>
	
    </section>

    <!-- sect2>
      <title>Diagnostics: Visual Inspection</title>
      <sect3>
	<title>Numerical Parameters</title>
	<para>
	  To inspect the Markov chain generated by
	  <application>BAli-Phy</application>, we recommend the program
	  <ulink url="http://evolve.zoo.ox.ac.uk/software/tracer/">Tracer</ulink>. 
	  You can open the file <filename>C1.log</filename> in Tracer to view
	  traceplots and to estimate the effective sample size.
	</para>
      </sect3>
      <sect3>
	<title>Topologies</title>
      <para>
	<screen><prompt>%</prompt> trees-view2 C1.trees C2.trees</screen>
      </para>
    </sect3>
  </sect2 -->
  </section>


  <section xml:id="alignment-utilities"><info><title>Alignment utilities: brief overview</title></info>
    

  <para>This section gives a brief overview showing <emphasis>some</emphasis> of the things that can be done with the included alignment utilities.  It is intended to be helpful, but not exhaustive.  To see the full set of options for each tool, give the argument "<userinput>--help</userinput>" on the command line.</para>

    <section><info><title>alignment-info</title></info>
      
      <para>Show basic information about the alignment:</para>
<screen><prompt>%</prompt> alignment-info file.fasta
<prompt>%</prompt> alignment-info file.fasta file.tree</screen>
    </section>
    
    <section><info><title>alignment-cat</title></info>
      
      <para>To select columns from an alignment:</para>
<screen><prompt>%</prompt> alignment-cat -c1-10,50-100,600- file.fasta > result.fasta
<prompt>%</prompt> alignment-cat -c5-250/3 file.fasta > first_codon_position.fasta
<prompt>%</prompt> alignment-cat -c6-250/3 file.fasta > second_codon_position.fasta</screen>

  <para>To concatenate two or more alignments:</para>
  <screen><prompt>%</prompt> alignment-cat file1.fasta file2.fasta > all.fasta</screen>
    </section>
    
    <section><info><title>alignment-thin</title></info>
      <para>Remove columns without a minimum number of letters:</para> 
      <screen><prompt>%</prompt> alignment-thin --min-letters=5 <replaceable>file</replaceable>.fasta > <replaceable>file</replaceable>-thinned.fasta</screen>
      <para>Remove sequences by name:</para>
      <screen><prompt>%</prompt> alignment-thin --remove=seq1,seq2 <replaceable>file</replaceable>.fasta > <replaceable>file</replaceable>2.fasta</screen>
      <para>Remove short sequences:</para>
      <screen><prompt>%</prompt> alignment-thin --longer-than=250 <replaceable>file</replaceable>.fasta > <replaceable>file</replaceable>-long.fasta</screen>
      <para>Remove sequences with &lt;= 5 differences from the closest other sequence:</para>
      <screen><prompt>%</prompt> alignment-thin --cutoff=5 file.fasta > more-than-5-differences.fasta</screen>
      <para>Like <userinput>--cutoff</userinput>, but stop when we have the right number of sequences:</para>
      <screen><prompt>%</prompt> alignment-thin --down-to=30 <replaceable>file</replaceable>.fasta > <replaceable>file</replaceable>-30taxa.fasta</screen>
      <para>Protect some sequences from being removed:</para>
      <screen><prompt>%</prompt> alignment-thin --down-to=30 <replaceable>file</replaceable>.fasta --protect=seq1,seq2 > <replaceable>file</replaceable>-30taxa.fasta</screen>
      <para>Remove sequences that are missing conserved columns:</para> 
      <screen><prompt>%</prompt> alignment-thin --remove-crazy=10 <replaceable>file</replaceable>.fasta > <replaceable>file</replaceable>2.fasta</screen>
    </section>

    <section><info><title>alignment-draw</title></info>
      
      <para>Draw an alignment to HTML, optionally coloring residues by AU.</para>
<screen><prompt>%</prompt>  alignment-draw <replaceable>file</replaceable>.fasta --show-ruler --color-scheme=DNA+contrast > <replaceable>file</replaceable>.html
<prompt>%</prompt>  alignment-draw <replaceable>file</replaceable>.fasta --show-ruler --AU=<replaceable>file</replaceable>-AU.prob --color-scheme=DNA+contrast+fade+fade+fade+fade > <replaceable>file</replaceable>-AU.html</screen>
    </section>

    <section><info><title>alignment-find</title></info>
      
      <para>Find the last (or first) FastA alignment in a file.</para>
<screen><prompt>%</prompt> alignment-find --first &lt; <replaceable>file</replaceable>.fastas &gt; first.fasta
<prompt>%</prompt> alignment-find &lt; <replaceable>file</replaceable>.fastas &gt; last.fasta</screen>
    </section>

    <section><info><title>alignment-indices</title></info>
      
      <para>Turn columns from a template alignment into alignment constraints:</para>
<screen><prompt>%</prompt> alignment-indices template.fasta > constraints.txt
<prompt>%</prompt> alignment-indices -c100-110,200,300- template.fasta > constraints.txt</screen>

      <para>Each line in this file corresponds to one
	alignment column.</para>
    </section>

    <section><info><title>alignment-chop-internal</title></info>
      
      <para>Remove internal-node ancestral sequences from an alignment.  (This
	probably only works for alignments output by bali-phy.) </para>
<screen><prompt>%</prompt> alignment-chop-internal <replaceable>file</replaceable>.fasta > <replaceable>file</replaceable>-chopped.fasta</screen>
    </section>

  </section>

  <section xml:id="tree-utilities"><info><title>Tree utilities: brief overview</title></info>

  <para>This section gives a brief overview showing <emphasis>some</emphasis> of the things that can be done with the included tree utilities.  It is intended to be helpful, but not exhaustive.  To see the full set of options for each tool, give the argument "<userinput>--help</userinput>" on the command line.</para>
    
    <section><info><title>trees-consensus</title></info>
      
      <para>This program analyzes the tree sample contained in
	<replaceable>file</replaceable>.  It reports the MAP topology, the
	supported taxa partitions (including partial partitions), and the
	majority consensus topology.
      </para> 
    </section>

    <section><info><title>trees-bootstrap</title></info>
      
      <para>Usage: trees-bootstrap <replaceable>file1</replaceable>
	[<replaceable>file2</replaceable> ... ] --predicates
	<replaceable>predicate-file</replaceable> [OPTIONS] </para>
      <para>This program analyzes the tree samples contained in
	<replaceable>file1</replaceable>, <replaceable>file2</replaceable>,
	etc.  It gives the support of each tree sample for each predicate in
	<replaceable>predicate-file</replaceable>, and reports a confidence
	interval based on the block bootstrap.
      </para> 

      <para>Each predicate is the intersection of a set of partitions, and
	is specified as a list of partitions or (multifurcating) trees, one
	per line.  Predicates are separated by blank lines.
      </para>
    </section>

    <section><info><title>trees-to-SRQ</title></info>
      

      <para>Usage: trees-to-SRQ <replaceable>predicate-file</replaceable> [OPTIONS] <replaceable>trees-file</replaceable> </para>

      <para>This program analyzes the tree samples contained in
	<replaceable>trees-file</replaceable>.  It uses them to produce an
	SRQ plot for each predicate in
	<replaceable>predicate-file</replaceable>.  Plots are produced in
	<application>gnuplot</application> format, with one point per line
	and with plots separated by a blank line.</para>

      <para>If <userinput>--mode sum </userinput> is specified, then a "sum"
	plot is produced instead of an SRQ plot.  In this plot, the slope of
	the curve corresponds to the posterior probability of the event.  If the
	<userinput>--invert</userinput> option is used then the slope of the
	curve correspond to the probability of the inverse event.  This is
	recommended if the probability of the event is near 1.0, because the
	sum plot does not distinguish variation in probabilities near 1.0 well.
      </para>

    </section>

  </section>

    <section xml:id="compilation"><info><title>Compiling <application>BAli-Phy</application></title></info>
    

    <para>Compiling <application>BAli-Phy</application> is intended to be a relatively painless process.  However, most people will want to use the pre-compiled binaries as described in the standard installation instructions at <xref linkend="installation"/> instead of compiling BAli-Phy themselves.  You might want to compile BAli-Phy yourself if you want to 
    <itemizedlist>
      <listitem>run BAli-Phy on a non-Intel CPU (such as ARM64 or Alpha).</listitem>
      <listitem>run BAli-Phy on Mac OS X versions older than 10.9</listitem>
      <listitem>enable the <application>draw-tree</application> program on Windows or Mac (this requires the Cairo graphics library).</listitem>
      <listitem>modify the source code and submit a patch with new functionality.</listitem>
      <listitem>change the optimization options used to compile BAli-Phy in the pre-compiled binaries.</listitem>
      <listitem>compile with debugging options to find the cause of a bug, and maybe fix it.</listitem>
    </itemizedlist>
    Otherwise, the pre-compiled binaries will be fine.
    </para>

    <section><info><title>Setup</title></info>
      

    <para>In order to compile BAli-Phy, you need
    <itemizedlist>
      <listitem>a <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://en.wikipedia.org/wiki/C%2B%2B14">C++20</link> compiler</listitem>
      <listitem><link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://mesonbuild.com">meson</link> (version >= 1.0)</listitem>
    </itemizedlist>
    We recommend the GNU C++ Compiler (<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://gcc.gnu.org">GCC</link>) version 10.0 (or higher) or the <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://clang.llvm.org">Clang</link> compiler version 13 or higher. The <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.cairographics.org/">Cairo</link> graphics library is optional, but if it is missing, the <command>drawtree</command> tool that is used to draw consensus trees won&apos;t be built. See also <xref linkend="software_req"/>. </para>

    <section><info><title>Linux</title></info>
    <para>On Debian and Ubuntu, you can type:
<screen><prompt>%</prompt> <userinput>sudo apt-get install g++ git libcairo2-dev pandoc</userinput></screen>

    </para>
If your version of Debian or Ubuntu is recent enough to contain meson version 1.0 or higher, you can install meson with apt-get:
<screen><prompt>%</prompt> <userinput>sudo apt-get install meson</userinput>
<prompt>%</prompt> <userinput>dpkg -s meson | grep Version</userinput>
Version: 1.0.1-5
</screen>

<para>On computing clusters, you might want to use miniconda to install the build tools.

<screen><prompt>%</prompt> <userinput>conda create -n devel -c conda-forge --strict-channel-priority</userinput>
<prompt>%</prompt> <userinput>conda activate devel</userinput>
<prompt>%</prompt> <userinput>conda install meson gxx boost-cpp cmake pkg-config cairo</userinput>
<prompt>%</prompt> <userinput>export BOOST_ROOT=$CONDA_PREFIX</userinput></screen>
</para>


<para>
Otherwise you can install meson through pip3:
<screen><prompt>%</prompt> <userinput>sudo apt-get install python3 python3-pip ninja</userinput>
<prompt>%</prompt> <userinput>python3 -m venv meson</userinput>
<prompt>%</prompt> <userinput>source meson/bin/activate</userinput>
<prompt>%</prompt> <userinput>pip3 install meson</userinput>
</screen>
</para>
    </section>

    <section><info><title>Mac</title></info>
    <para>On Mac OS X, the simplest way to get a compiler is to install <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://developer.apple.com/xcode/">XCode</link> (version 11 or newer) command line tools, which come with <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://clang.llvm.org">clang</link>.
 <screen><prompt>%</prompt> <userinput>xcode-select --install</userinput></screen>    To get the other tools, first install <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://brew.sh/">homebrew</link>, and then type:
<screen><prompt>%</prompt> <userinput>brew install git meson cairo pandoc</userinput></screen>
    </para>
    <!-- para>You can also install BAli-Phy with homebrew.  The recipe is in <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://github.com/Homebrew/homebrew-science/blob/master/README.md">homebrew/science</link>. However, this recipe may not install the latest version.</para -->

    </section>
    
    <section><info><title>Windows (native)</title></info>
    <para>The <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.msys2.org">MSYS2</link> project provides an MINGW64 compiler that can create native windows executables.  MSYS2 itself is actually non-native (it is derived from cygwin), and therefore the MSYS2 shell refers to drives as <filename>/c/</filename> instead of <filename>C:/</filename>.</para>
    <screen><prompt>%</prompt> <userinput>pacman --needed --noconfirm -Sy pacman-mirrors</userinput>
<prompt>%</prompt> <userinput>pacman -Sy</userinput>
<prompt>%</prompt> <userinput>pacman -S mingw-w64-x86_64-ninja</userinput>
<prompt>%</prompt> <userinput>pacman -S mingw-w64-x86_64-toolchain</userinput>
<prompt>%</prompt> <userinput>pacman -S mingw-w64-python3-pip</userinput>
<prompt>%</prompt> <userinput>PATH=/c/msys64/mingw64/bin:&#36;PATH</userinput> # Put the mingw64 executables into your path
<prompt>%</prompt> <userinput>pip3 install meson</userinput></screen>
    <para>Keep in mind that MSYS2 keeps its (non-native) executables in <filename>C:/msys64/usr/bin</filename>, while it keeps the (native) MINGW executables in <filename>C:/msys64/mingw64/bin</filename>.  If you want to use the native MINGW executables, you need to make sure that <filename>/c/msys64/mingw64/bin/</filename> is in your PATH.  If you forget to put the MINGW executables in the path, some of the installed MINGW programs (such as pip3 above) will show up as missing when you try to run them.</para>
    </section>

    <!-- section><info><title>Windows (Cygwin)</title></info>
    The <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.cygwin.com/">Cygwin</link> project provides a non-native POSIX environment.
    </section -->
    <!-- section><info><title>Windows (non-native)</title></info>
    <para>BAli-Phy can be compiled as either a <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.cygwin.com/">Cygwin</link> executable or a native Windows executable.  The Cygwin executable needs the <filename>cygwin1.dll</filename> to run, and can handle cygwin filenames like <filename>/cygdrive/C/Users/</filename>.  To compile bali-phy for Cygwin, install Cygwin and the Cygwin packages for gcc, git, meson, and cairo.  Then you can build bali-phy within Cygwin using the build instructions below.</para>

    <para>You can also compile native windows executables using the <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://mingw-w64.org/doku.php">Mingw-w64</link> version of GCC.  These native windows executables do not need <filename>cygwin1.dll</filename>, and only understand Windows filenames, like <filename>C:\Users\</filename>.  You can build these executables in the <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.msys2.org">MSYS2</link> shell, which is a modified version of Cygwin for compiling native windows executables using the Mingw-w64 compiler.</para>

    <para>You can also build Mingw-w64 executables using either Linux or Cygwin as the host environment, if you install a mingw-w64 "cross-compiler".  You can obtain cross compilers for Mingw-w64 on both Linux and Cygwin.  To inform the <filename>configure.sh</filename> script that you wish to use a cross compiler, add the flag <userinput>- -host=x86_64-w64-mingw32</userinput> to build for 64-bit windows, and <userinput>- -host=i686-w64-mingw32</userinput> to build 32-bit executables.</para>
    </section -->

	  
    </section>

    <section xml:id="quickstart"><info><title>Clone, Configure, Compile</title></info>
       
    <para>First check out the code using git:
<screen><prompt>%</prompt><userinput> git clone https://github.com/bredelings/BAli-Phy.git</userinput>
<prompt>%</prompt><userinput> cd BAli-Phy</userinput></screen>
</para>
<para>
Then run meson to configure the build process:
<screen><prompt>%</prompt><userinput> meson setup build --prefix=&#36;HOME/Applications/bali-phy-&version;/ --buildtype=release</userinput></screen>
</para>
<para>
Finally, build and install the software:
<screen><prompt>%</prompt><userinput> ninja -C build test</userinput>
<prompt>%</prompt><userinput> ninja -C build install</userinput>
</screen>
The command <command>bali-phy</command> and its associated tools should then be located in <filename>&install.path;/bin/</filename>. To install to another directory <replaceable>dir</replaceable>, specify --prefix=<replaceable>dir</replaceable> to <command>meson</command>.
      </para>

    </section>
      <section><info><title>Options: compiler and linker flags</title></info>
	
      <para>You can select the C++ compiler by setting the CXX variable.  A useful example of this is to use <command>g++-10</command> on systems where <command>g++</command> invokes a compiler that is too old:
 <screen><prompt>%</prompt> <userinput>CXX=g++-10 meson setup build --prefix=&#36;HOME/Applications/bali-phy-&version; --buildtype=release</userinput></screen>
 You may also set compiler and linker options using the CPPFLAGS, CXXFLAGS, and LDFLAGS variables.  For example, you can instruct the compiler to use all the features of your chip, instead of producing generic code that will run anywhere:
 <screen><prompt>%</prompt> <userinput>CXXFLAGS="-mtune=native -march=native" meson setup --prefix=&#36;HOME/Applications/bali-phy-&version;</userinput></screen>

 For example, you can set the CPPFLAGS and LDFLAGS variables to instruct the compiler where to look for libraries, such as cairo:
	  <screen><prompt>%</prompt> <userinput>CPPFLAGS="-I/usr/local/include" LDFLAGS="-L/usr/local/lib" meson setup build --prefix=&#36;HOME/Applications/bali-phy-&version; --buildtype=release</userinput></screen>
 Another useful example of this is to produce an OS X executable on that can run on older versions of OS X:
	  <screen><prompt>%</prompt> <userinput>CXXFLAGS="-mmacosx-version-min=10.9" LDFLAGS="-mmacosx-version-min=10.9" meson setup build --prefix=&#36;HOME/Applications/bali-phy-&version; --buildtype=release</userinput></screen>	</para>
      </section>

    </section>


  <section xml:id="FAQ"><info><title>Frequently Asked Questions (FAQ)</title></info>
    
    <section><info><title>Input files</title></info>
      <qandaset>
	<qandaentry>
	  <question><para>Does BAli-Phy accept the wildcard characters "N" or "X"?  How does it treat them?</para></question>
	  <answer>
	    <para>Yes, BAli-Phy accepts the wildcard characters "N"
	    (for DNA) and "X" (for proteins).  These characters
	    indicate that some letter is present (as opposed to a
	    gap), but that you don&apos;t know <emphasis>which</emphasis>
	    letter it is.  
	    </para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>Does BAli-Phy accept "?" characters?</para></question>
	  <answer>
	    <para>
	      No.  "?" characters are often used to indicate
	      <emphasis>either</emphasis> letter presence (e.g. "N",
	      "X") <emphasis>or</emphasis> absence (e.g. "-").
	      BAli-phy will insist that you replace each "?" with
	      either "N"/"X" or "-" to indicate which one you mean. 
	    </para>

	    <para>(Most programs ignore indels and consider only
	    substitutions, and in that case "N" and "-" have the same
	    effect on the likelihood or parsimony score.  However,
	    since BAli-Phy takes indels into account, these two
	    alternatives are quite different.)
	    </para>

	  </answer>
	</qandaentry>

      <qandaentry>
	<question><para>Does BAli-Phy accept the characters "R" and "Y", etc.?</para></question>
	  <answer>
	    <para>
	      Yes.  BAli-Phy accepts the characters Y, R, W, S, K, M,
	      B, D, H, and V for DNA, RNA, and Codon alphabets.
	      BAli-Phy also accepts the characters B, Z, and J 
	      for amino acids.  These characters indicate partial
	      knowledge about a letter.  For example, R indicates
	      that a nucleotide is present, and is a puRine (A or
	      G). J indicates that an amino acid is present and is
	      either I or L.  
	    </para>

	    <para>
	      (Note that sequences sometimes contain such ambiguity
	      codes because the DNA that was sequenced contains
	      <emphasis>both</emphasis> values.  This might occur when
	      sequencing a heterozygote or when sequencing pooled DNA
	      from several individuals.  However, the model in
	      BAli-Phy (and other phylogeny inference programs) is
	      that only one letter is correct, but we do not know
	      which one it is.  This is probably not problematic when
	      dealing with pooled sequences, but should be considered.)
	    </para>
	  </answer>
	</qandaentry>

      <!-- qandaentry>
	<question><para>Can I specify a stop codon?</para></question>
	  <answer>
	  <para>
	  Well, yes...  but how do the models treat it?
	  </para>
	  </answer>
      </qandaentry -->

      </qandaset>
    </section>

    <section><info><title>Running <command>bali-phy</command>.</title></info>

      <qandaset>
	<qandaentry>
	  <question><para>Can I fix the alignment and ignore indel information, like MrBayes, BEAST, PhyloBayes and other MCMC programs?</para></question>
	  <answer>
	    <para>Yes.  Add <userinput>-Inone</userinput> or <userinput>-I none</userinput> on the command line.</para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>Can I fix the tree topology, while allowing the alignment to vary?</para></question>
	  <answer>
	    <para>Yes.  Add <userinput>--fix=topology --tree=<replaceable>treefile</replaceable></userinput> on the command line.</para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>Can I fix the tree topology and <emphasis>absolute</emphasis> branch lengths <emphasis>in all data partitions</emphasis>, while allowing the alignment to vary?</para></question>
	  <answer>
	    <para>Yes.  Add <userinput>--fix=tree --tree=<replaceable>treefile</replaceable></userinput> on the command line.</para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>Can I fix the tree topology and <emphasis>relative</emphasis> branch lengths, while allowing the alignment to vary?</para></question>
	  <answer>
	    <para>Yes.  Add <userinput>--fix=tree --tree=<replaceable>treefile</replaceable> '--scale=~gamma(0.5,2)'</userinput> on the command line.</para>
	  </answer>
	</qandaentry>

      </qandaset>

    </section>

    <section><info><title>Run-time error messages</title></info>
      
      
      <qandaset>
	<qandaentry>
	  <question><para>I tried to use <userinput>-S 'lg08 +> Rates.gamma(6)'</userinput> and I got an error message "bali-phy: No match."  What gives?</para></question>
	  <answer>
	    <para>You are probably using the C-shell as your command line shell.  It is trying to interpret <userinput>lg08 +> Rates.gamma(6)</userinput> as an array before running the command, and it is not succeeding.  Therefore, it doesn&apos;t even run <command>bali-phy</command>.</para>
	    <para>To avoid this, put quotes around the substitution model, like this: <userinput>-S 'lg08 +> Rates.gamma(6)'</userinput>.  This will keep the C-shell from interfering with your command.
	    </para>
	  </answer>
	</qandaentry>
      </qandaset>
    </section>

    <section><info><title>Stopping <command>bali-phy</command>.</title></info>
      

      <qandaset>
	<qandaentry>
	  <question><para>Why is <command>bali-phy</command> still
	      running? How long will it take?</para></question>
	  <answer>
	    <para>It runs until you stop it.  Stop it when its done.</para>
	    <para>The longer answer is that is is hard to predict how long MCMC will take to converge, since it depends on each data set in complex ways.  Automatic rules for determining when to stop an MCMC chain can be difficult to get right.  BAli-Phy does not contain an automatic stopping rule yet, so it relies on the user to run convergence diagnostics and determine when to stop the run.</para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>How do I stop a <command>bali-phy</command>
	  run on my personal computer?</para></question>
	  <answer>
	    <para>Simply kill the process -- there is no special
	    command to stop <command>bali-phy</command>. If you are
	    running it on your personal workstation, then you can use
	    the command <command>kill</command>.  To do that, you need
	    to find the PID (process ID) of the running program.  You
	    can find this by examining the beginning of the file
	    <filename>C1.out</filename>.  For 
	    example:
<screen><prompt>%</prompt> less 5d-1/C1.out
command: bali-phy 5d.fasta -I none --iter=10 --seed=0
start time: Wed Jul  4 17:13:25 2018

VERSION: 3.3-b1  [HEAD -> logging, origin/logging commit 96a43e550]  (Jul 04 2018 16:25:09)
BUILD: Jul  4 2018 17:12:29
ARCH: linux x86_64
COMPILER: gcc 8.1.0 x86_64
directory: /home/bredelings/Work
subdirectory: 5d-675
hostname: telomere
<emphasis>PID: 18838</emphasis>
...
</screen>
Here the PID is 18838.  Therefore you can type:
<screen><prompt>%</prompt> kill 18838</screen>
On some operating systems you can also type:
<screen><prompt>%</prompt> killall bali-phy</screen>
However, be aware that this will terminate <emphasis>all</emphasis> of
your <command>bali-phy</command> runs on that computer.
	    </para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>How do I stop a <command>bali-phy</command>
	  run on a computing cluster?</para></question>
	  <answer>
	    <para>Simply terminate the submitted job.  The specific command
	    to terminate a job will depend on the queue manager that
	    is installed on your cluster.  Examine the documentation
	    for your cluster, or ask your cluster support staff how to delete
	    running jobs on your cluster.
	    </para>

	    <para>As an example, if the SGE software is used
	    to submit jobs, then the command <command>qstat</command>
	    should list your jobs and their job ID numbers (which is
	    different than the process ID number).  You can then use
	    the command <command>qdel</command> to delete jobs by ID
	    number.  The SGE documentation describes how to use these
	    commands. 
	    </para>
	  </answer>
	</qandaentry>


	<qandaentry>
	  <question><para>So, how can I know when to stop it?</para></question>
	  <answer>
	    <para>You can stop when it has both converged and also run for long enough to give
	      you &gt;1000 effectively independent samples.  </para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>How can I tell when the chain has converged?</para></question>
	  <answer>
	    <para>See section <xref linkend="mixing_and_convergence"/>.</para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>How can I check how many iterations the chain
	      has finished?</para></question>
	  <answer>
	    <para>Run <command>wc -l C1.log</command> inside the output
	      directory, and subtract 2.
	    </para>
	  </answer>
	</qandaentry>
      </qandaset>
    </section>


    <section><info><title>Running <command>bp-analyze</command>.</title></info>
      <qandaset>

	<qandaentry>
	  <question><para>Why does <command>bp-analyze</command> say "Program 'draw-tree' not found.  Tree pictures will not be generated"?</para></question>
	  <answer>
	    <para>The program <command>draw-tree</command> was not distributed on this platform (Windows, Mac).  This is not a fatal error message, it just means that a pretty picture of the tree will not be generated automatically.  You can still view the tree with <application>FigTree</application>, for example.</para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>Why does <command>bp-analyze</command> say "Program 'gnuplot' not found.  Trace plots will not be generated"?</para></question>
	  <answer>
	    <para>This is because you have not installed <application>gnuplot</application>.  This is not a fatal error message, it just means that pictures of partition support, and SRQ plots will not be generated automatically.</para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>Why does <command>bp-analyze</command> say "Program 'R' not found.  Some mixing graphs will not be generated"?</para></question>
	  <answer>
	    <para>This is because you have not installed <application>R</application>.  This is not a fatal error message, it just means that a plot showing differences in clade probabilities between runs will not be generated.</para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>Why is <command>bp-analyze</command> stopping early, or failing to generate some files?</para></question>
	  <answer>
	    <para>Look in the file <filename>Results/commands.log</filename>.  This should contain the actual commands that were run, along with error message from these commands.  These error message should give you a hint as to what the problem might be.</para>
	  </answer>
	</qandaentry>
      </qandaset>
    </section>


    <section><info><title>Interpreting the results.</title></info>
      

      <qandaset>
	<qandaentry>
	  <question><para>How do I compute the clade support?</para></question>
	  <answer>
	    <para>Actually, BAli-Phy uses unrooted trees, so it only estimates bi-partition support.  A bi-partition is a division of taxa into two groups, but it does not specify which group contains the root. </para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>How do I compute the split/bi-partition support?</para></question>
	  <answer>
	    <para>After you analyze the output (<xref linkend="analysis"/>), the partition support is indicated in
	      <filename>Results/consensus</filename> and in <filename>Results/c50.PP.tree</filename>. </para> 
	  </answer>
	</qandaentry>
      </qandaset>
    </section>

    <section><info><title>How do I...</title></info>
      
      <qandaset>
	<qandaentry>
	  <question><para>How do I concatenate alignments?</para></question>
	  <answer><para>
 	    <screen><prompt>%</prompt> alignment-cat <replaceable>filename1.fasta</replaceable> <replaceable>filename2.fasta</replaceable> &gt; result.fasta</screen>
	      The alignments must have the same sequence names, but
	      the names need not be in the same order.
	    </para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question><para>How do I select columns from an alignment?</para></question>
	  <answer><para>
	    You can now select columns for analysis by specifying a range:
	    <screen><prompt>%</prompt> <userinput>bali-phy sequences.fasta:1-200,401-600 sequences.fasta:201-400</userinput></screen>
	    You can create a new alignment from selected columns using <userinput>alignment-cat</userinput>:
	    <screen><prompt>%</prompt> alignment-cat -c1-10,50-100,600- <replaceable>filename.fasta</replaceable> &gt; result.fasta</screen>
	    The resulting alignment will contain the selected columns in the order you specified.
	  </para>
	  </answer>
	</qandaentry>

	<qandaentry>
	  <question xml:id="generating_constraint_files"><para>How do I create an alignment-constraint file
	      from an alignment?</para></question>
	  <answer>
	    <para>To constrain the alignment to match some alignment
	      file <replaceable>filename.fasta</replaceable> in columns
	      100, 200-250, and 300, run:
	      <screen><prompt>%</prompt> alignment-indices -c100,200-250,300 <replaceable>filename.fasta</replaceable> &gt; filename.constraint</screen>
	    </para>
	  </answer>	
	</qandaentry>

      </qandaset>
    </section>
  </section>

</article>
