<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://guhaogao.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://guhaogao.com/" rel="alternate" type="text/html" /><updated>2026-07-02T12:50:00+08:00</updated><id>https://guhaogao.com/feed.xml</id><title type="html">Haogao Gu</title><subtitle>Modeling virus evolution/transmission and virus/host interactions.</subtitle><author><name>Haogao Gu</name><email>work@guhaogao.com</email></author><entry><title type="html">Time Zone Converter for Meeting Scheduling</title><link href="https://guhaogao.com/posts/2026/01/timezone-converter/" rel="alternate" type="text/html" title="Time Zone Converter for Meeting Scheduling" /><published>2026-01-07T00:00:00+08:00</published><updated>2026-01-07T00:00:00+08:00</updated><id>https://guhaogao.com/posts/2026/01/timezone-converter</id><content type="html" xml:base="https://guhaogao.com/posts/2026/01/timezone-converter/"><![CDATA[<p>A simple tool to convert time across different time zones and find overlapping working hours with collaborators around the world.</p>

<style>
.tz-container {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  max-width: 100%;
  margin: 2em 0;
  padding: 1.5em;
  background: #fafaf9;
  border-radius: 8px;
  border: 1px solid #d6d3d1;
  box-sizing: border-box;
  overflow: hidden;
}

.tz-container * {
  box-sizing: border-box;
}

.tz-title-row {
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;
  gap: 0.5em;
  margin-bottom: 1.5em;
}

.tz-title {
  margin: 0;
  color: #1a3a34;
  font-size: 1.2em;
  font-weight: 600;
}

.tz-subtitle {
  margin: 0;
  color: #737373;
  font-size: 0.85em;
}

.tz-detected {
  display: inline-block;
  padding: 0.2em 0.5em;
  background: #ecfdf5;
  color: #14532d;
  border-radius: 4px;
  font-size: 0.75em;
  margin-left: 0.5em;
  font-weight: normal;
}

.tz-section-header {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 0.5em;
  margin-bottom: 1em;
}

.tz-input-group {
  display: flex;
  flex-wrap: wrap;
  gap: 1em;
  margin-bottom: 1.5em;
  padding-bottom: 1.5em;
  border-bottom: 1px solid #e5e5e5;
}

.tz-input-item {
  flex: 1;
  min-width: 150px;
}

.tz-input-item label {
  display: block;
  margin-bottom: 0.4em;
  font-size: 0.85em;
  color: #525252;
  font-weight: 500;
}

.tz-input-item input,
.tz-input-item select {
  width: 100%;
  padding: 0.6em 0.8em;
  border: 1px solid #d6d3d1;
  border-radius: 4px;
  font-size: 0.95em;
  background: #fff;
  color: #292524;
  box-sizing: border-box;
}

.tz-input-item input:focus,
.tz-input-item select:focus {
  outline: none;
  border-color: #1a3a34;
  box-shadow: 0 0 0 2px rgba(26, 58, 52, 0.1);
}

.tz-section {
  margin-bottom: 1.5em;
  padding-bottom: 1.5em;
  border-bottom: 1px solid #e5e5e5;
}

.tz-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.tz-section-title {
  font-size: 0.95em;
  font-weight: 600;
  color: #404040;
  margin-bottom: 1em;
}

.tz-work-hours {
  display: flex;
  align-items: center;
  gap: 0.5em;
  margin-top: 1em;
  flex-wrap: wrap;
}

.tz-work-hours label {
  font-size: 0.85em;
  color: #525252;
}

.tz-work-hours input {
  width: 80px;
  max-width: 100%;
  padding: 0.4em;
  border: 1px solid #d6d3d1;
  border-radius: 4px;
  font-size: 0.9em;
}

.tz-legend {
  display: flex;
  gap: 1.5em;
  margin-bottom: 1em;
  flex-wrap: wrap;
}

.tz-legend-item {
  display: flex;
  align-items: center;
  gap: 0.4em;
  font-size: 0.8em;
  color: #525252;
}

.tz-legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 3px;
}

.tz-legend-dot.working {
  background: #14532d;
}

.tz-legend-dot.outside {
  background: #a3a3a3;
}

.tz-legend-dot.overlap {
  background: #059669;
  box-shadow: 0 0 0 2px #d1fae5;
}

.tz-zones-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1em;
}

.tz-zones-title {
  font-size: 0.95em;
  color: #404040;
  font-weight: 500;
}

.tz-add-btn {
  padding: 0.4em 0.8em;
  background: #1a3a34;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 0.85em;
  cursor: pointer;
  transition: background 0.2s;
}

.tz-add-btn:hover {
  background: #14532d;
}

.tz-results {
  display: flex;
  flex-direction: column;
  gap: 0.8em;
}

.tz-result-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.8em 1em;
  background: #fff;
  border: 1px solid #e5e5e5;
  border-radius: 6px;
  transition: box-shadow 0.2s;
  border-left: 4px solid #a3a3a3;
}

.tz-result-item.working-hours {
  border-left-color: #14532d;
  background: #f0fdf4;
}

.tz-result-item.overlap-hours {
  border-left-color: #059669;
  background: #ecfdf5;
  box-shadow: 0 0 0 1px #a7f3d0;
}

.tz-result-item.your-time {
  background: linear-gradient(135deg, #fafaf9 0%, #f5f5f4 100%);
  border: 1px dashed #d6d3d1;
  border-left: 4px solid #1a3a34;
}

.tz-result-item.your-time .tz-result-zone {
  font-weight: 600;
}

.tz-result-item.your-time .tz-you-badge {
  display: inline-block;
  background: #1a3a34;
  color: #fff;
  font-size: 0.7em;
  padding: 0.15em 0.5em;
  border-radius: 3px;
  margin-left: 0.5em;
  vertical-align: middle;
}

.tz-result-item:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.tz-result-left {
  display: flex;
  flex-direction: column;
  gap: 0.2em;
}

.tz-result-zone {
  font-size: 0.9em;
  color: #525252;
}

.tz-result-status {
  font-size: 0.75em;
  padding: 0.2em 0.5em;
  border-radius: 3px;
  display: inline-block;
  width: fit-content;
}

.tz-result-status.working {
  background: #dcfce7;
  color: #14532d;
}

.tz-result-status.outside {
  background: #f5f5f5;
  color: #737373;
}

.tz-result-status.overlap {
  background: #a7f3d0;
  color: #065f46;
  font-weight: 500;
}

.tz-result-right {
  display: flex;
  align-items: center;
}

.tz-result-time {
  font-size: 1.1em;
  font-weight: 600;
  color: #1a3a34;
  font-family: "SF Mono", Monaco, monospace;
}

.tz-result-date {
  font-size: 0.8em;
  color: #737373;
  margin-left: 0.5em;
}

.tz-remove-btn {
  margin-left: 1em;
  padding: 0.2em 0.5em;
  background: none;
  border: 1px solid #d6d3d1;
  border-radius: 3px;
  color: #737373;
  cursor: pointer;
  font-size: 0.8em;
}

.tz-remove-btn:hover {
  background: #fee2e2;
  border-color: #fca5a5;
  color: #991b1b;
}

.tz-copy-btn {
  padding: 0.6em 1.2em;
  background: #f5f5f4;
  border: 1px solid #d6d3d1;
  border-radius: 4px;
  color: #404040;
  cursor: pointer;
  font-size: 0.9em;
  transition: all 0.2s;
}

.tz-copy-btn:hover {
  background: #e5e5e5;
}

.tz-copy-btn.copied {
  background: #14532d;
  color: #fff;
  border-color: #14532d;
}

.tz-action-buttons {
  display: flex;
  gap: 0.8em;
  margin-top: 1em;
  flex-wrap: wrap;
}

.tz-ics-btn {
  padding: 0.6em 1.2em;
  background: #1a3a34;
  border: 1px solid #1a3a34;
  border-radius: 4px;
  color: #fff;
  cursor: pointer;
  font-size: 0.9em;
  transition: all 0.2s;
}

.tz-ics-btn:hover {
  background: #14532d;
}

.tz-ics-btn.downloaded {
  background: #059669;
  border-color: #059669;
}

.tz-suggestion-result {
  padding: 1em;
  background: linear-gradient(135deg, #ecfdf5, #d1fae5);
  border: 1px solid #a7f3d0;
  border-radius: 8px;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-5px); }
  to { opacity: 1; transform: translateY(0); }
}

.tz-suggestion-title {
  font-size: 1em;
  font-weight: 600;
  color: #065f46;
  margin-bottom: 0.8em;
  display: flex;
  align-items: center;
  gap: 0.5em;
}

.tz-suggestion-time {
  font-size: 1.4em;
  font-weight: 700;
  color: #14532d;
  margin-bottom: 0.5em;
}

.tz-suggestion-detail {
  font-size: 0.85em;
  color: #525252;
  line-height: 1.6;
}

.tz-suggestion-breakdown {
  margin-top: 0.8em;
  padding-top: 0.8em;
  border-top: 1px solid #a7f3d0;
  font-size: 0.85em;
}

.tz-suggestion-options {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1em;
  margin-top: 1em;
}

.tz-suggestion-option {
  padding: 1em;
  background: #fff;
  border: 1px solid #d6d3d1;
  border-radius: 8px;
  transition: all 0.2s;
}

.tz-suggestion-option:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.tz-suggestion-option.excellent {
  border-color: #059669;
  background: linear-gradient(135deg, #ecfdf5, #d1fae5);
}

.tz-suggestion-option.good {
  border-color: #14532d;
  background: #f0fdf4;
}

.tz-suggestion-option.acceptable {
  border-color: #ca8a04;
  background: #fefce8;
}

.tz-suggestion-option.challenging {
  border-color: #ea580c;
  background: #fff7ed;
}

.tz-suggestion-option.difficult {
  border-color: #dc2626;
  background: #fef2f2;
}

.tz-suggestion-option.disabled {
  background: #f5f5f4;
  border-color: #d6d3d1;
}

.tz-suggestion-option-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5em;
}

.tz-suggestion-option-title {
  font-weight: 600;
  font-size: 0.95em;
  color: #404040;
}

.tz-suggestion-option .tz-suggestion-time {
  font-size: 1.2em;
  margin-bottom: 0.5em;
}

.tz-suggestion-option .tz-suggestion-breakdown {
  border-top-color: #e5e5e5;
  margin-top: 0.5em;
  padding-top: 0.5em;
}

.tz-apply-btn {
  margin-top: 0.8em;
  padding: 0.5em 1em;
  background: #1a3a34;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 0.85em;
  cursor: pointer;
  transition: background 0.2s;
  width: 100%;
}

.tz-apply-btn:hover {
  background: #14532d;
}

.tz-apply-btn.applied {
  background: #059669;
  cursor: default;
}

.tz-apply-btn.applied:hover {
  background: #059669;
}

.tz-more-options {
  margin-top: 1em;
  padding-top: 1em;
  border-top: 1px dashed #d6d3d1;
}

.tz-more-options-title {
  font-size: 0.85em;
  color: #737373;
  margin-bottom: 0.6em;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.3em;
}

.tz-more-options-title:hover {
  color: #525252;
}

.tz-more-options-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5em;
}

.tz-mini-option {
  display: inline-flex;
  align-items: center;
  gap: 0.4em;
  padding: 0.4em 0.7em;
  background: #fff;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  font-size: 0.8em;
  cursor: pointer;
  transition: all 0.2s;
}

.tz-mini-option:hover {
  border-color: #1a3a34;
  background: #f0fdf4;
}

.tz-mini-option.applied {
  background: #059669;
  border-color: #059669;
  color: #fff;
}

.tz-mini-option-time {
  font-weight: 600;
  font-family: "SF Mono", Monaco, monospace;
}

.tz-mini-option-quality {
  font-size: 0.9em;
}

.tz-suggestion-score {
  display: inline-block;
  padding: 0.2em 0.6em;
  background: #14532d;
  color: #fff;
  border-radius: 4px;
  font-size: 0.8em;
}

.tz-priority-selector {
  display: flex;
  align-items: center;
  gap: 0.8em;
  margin-bottom: 1em;
  padding: 0.8em;
  background: #f5f5f4;
  border-radius: 6px;
  flex-wrap: wrap;
}

.tz-priority-selector label {
  font-size: 0.9em;
  color: #404040;
}

.tz-priority-selector select {
  padding: 0.5em 0.8em;
  border: 1px solid #d6d3d1;
  border-radius: 4px;
  font-size: 0.9em;
  background: #fff;
  min-width: 180px;
}

.tz-focus-checkbox {
  display: flex;
  align-items: center;
  gap: 0.4em;
  margin-left: auto;
  padding: 0.4em 0.8em;
  background: #fff;
  border: 1px solid #d6d3d1;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.tz-focus-checkbox:hover {
  border-color: #14532d;
}

.tz-focus-checkbox.checked {
  background: #ecfdf5;
  border-color: #14532d;
}

.tz-focus-checkbox input {
  margin: 0;
  cursor: pointer;
}

.tz-focus-checkbox span {
  font-size: 0.85em;
  color: #404040;
  white-space: nowrap;
}

/* Mobile responsive styles */
@media (max-width: 600px) {
  .tz-container {
    padding: 1em;
    overflow-x: hidden;
  }
  
  .tz-title {
    font-size: 1.2em;
  }
  
  .tz-section {
    padding: 0.8em;
    overflow: hidden;
  }
  
  .tz-input-group {
    flex-direction: column;
    gap: 0.8em;
    margin-bottom: 1em;
    padding-bottom: 1em;
  }
  
  .tz-input-item {
    width: 100%;
    min-width: 0;
  }
  
  .tz-input-item select,
  .tz-input-item input {
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
  }
  
  /* Fix for date/time inputs on mobile */
  .tz-input-item input[type="date"],
  .tz-input-item input[type="time"] {
    min-width: 0;
    width: 100%;
    max-width: 100%;
  }
  
  .tz-work-hours {
    flex-direction: column;
    align-items: stretch;
    gap: 0.5em;
  }
  
  .tz-work-hours label {
    margin-bottom: 0.3em;
  }
  
  .tz-work-hours input {
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
  }
  
  .tz-work-hours input[type="time"] {
    min-width: 0;
    width: 100%;
  }
  
  .tz-result-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5em;
    padding: 0.8em;
  }
  
  .tz-result-right {
    width: 100%;
    justify-content: space-between;
  }
  
  .tz-result-time {
    font-size: 1.2em;
  }
  
  .tz-remove-btn {
    margin-left: auto;
  }
  
  .tz-legend {
    flex-direction: column;
    gap: 0.5em;
  }
  
  .tz-priority-selector {
    flex-direction: column;
    align-items: stretch;
    gap: 0.6em;
  }
  
  .tz-priority-selector select {
    width: 100%;
    min-width: unset;
    box-sizing: border-box;
  }
  
  .tz-focus-checkbox {
    margin-left: 0;
    justify-content: center;
  }
  
  .tz-suggestion-result {
    padding: 0.8em;
    overflow: hidden;
  }
  
  .tz-suggestion-options {
    grid-template-columns: 1fr;
    gap: 0.8em;
    margin-top: 0.8em;
  }
  
  .tz-suggestion-option {
    padding: 0.8em;
    width: 100%;
    box-sizing: border-box;
  }
  
  .tz-suggestion-option-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.3em;
  }
  
  .tz-suggestion-score {
    align-self: flex-start;
  }
  
  .tz-suggestion-time {
    font-size: 1.1em !important;
  }
  
  .tz-suggestion-breakdown {
    font-size: 0.8em;
  }
  
  .tz-copy-btn {
    width: 100%;
    text-align: center;
    box-sizing: border-box;
  }
  
  .tz-action-buttons {
    flex-direction: column;
  }
  
  .tz-ics-btn {
    width: 100%;
    text-align: center;
    box-sizing: border-box;
  }
  
  .tz-zones-header {
    flex-direction: column;
    gap: 0.5em;
    align-items: stretch;
  }
  
  .tz-add-btn {
    width: 100%;
    text-align: center;
  }
}

/* Extra small screens */
@media (max-width: 380px) {
  .tz-container {
    padding: 0.8em;
  }
  
  .tz-section {
    padding: 0.6em;
  }
  
  .tz-result-time {
    font-size: 1em;
  }
  
  .tz-result-date {
    font-size: 0.7em;
  }
}
</style>

<div class="tz-container">
  <div class="tz-title-row">
    <h3 class="tz-title">🌍 Time Zone Converter</h3>
    <span class="tz-subtitle">— Find the best meeting time across time zones</span>
  </div>
  
  <!-- Section 1: Your Settings -->
  <div class="tz-section">
    <div class="tz-section-header">
      <div class="tz-section-title" style="margin-bottom:0;">📍 Your Settings</div>
      <span class="tz-detected" id="tz-detected"></span>
    </div>
    <div class="tz-input-group">
      <div class="tz-input-item">
        <label for="tz-source">Your City</label>
        <select id="tz-source"></select>
      </div>
      <div class="tz-input-item">
        <label for="tz-date">Date</label>
        <input type="date" id="tz-date" />
      </div>
      <div class="tz-input-item">
        <label for="tz-time">Time</label>
        <input type="time" id="tz-time" value="10:00" />
      </div>
    </div>
    <div class="tz-work-hours">
      <label>Working hours for everyone:</label>
      <input type="time" id="tz-work-start" value="09:00" />
      <span>to</span>
      <input type="time" id="tz-work-end" value="17:00" />
    </div>
  </div>
  
  <!-- Section 2: Collaborators -->
  <div class="tz-section">
    <div class="tz-zones-header">
      <div class="tz-section-title">👥 Collaborators</div>
      <button class="tz-add-btn" onclick="addTargetZone()">+ Add City</button>
    </div>
    
    <div class="tz-results" id="tz-results"></div>
    
    <div class="tz-legend" id="tz-legend" style="display:none;">
      <div class="tz-legend-item">
        <div class="tz-legend-dot working"></div>
        <span>In working hours</span>
      </div>
      <div class="tz-legend-item">
        <div class="tz-legend-dot outside"></div>
        <span>Outside working hours</span>
      </div>
    </div>
    
    <div class="tz-action-buttons" id="tz-action-buttons" style="display:none;">
      <button class="tz-copy-btn" id="tz-copy-btn" onclick="copyResults()">📋 Copy All Times</button>
      <button class="tz-ics-btn" id="tz-ics-btn" onclick="downloadICS()">📅 Download .ics</button>
    </div>
  </div>
  
  <!-- Section 3: Best Time Suggestions (auto-shown when collaborators added) -->
  <div class="tz-section" id="tz-suggestion-section" style="display:none;">
    <div class="tz-section-title">🎯 Best Meeting Times</div>
    
    <div class="tz-priority-selector">
      <label for="tz-priority">Priority participant:</label>
      <select id="tz-priority">
        <option value="none">⚖️ Everyone equally</option>
      </select>
      <label class="tz-focus-checkbox" id="tz-force-work-label" style="display:none;">
        <input type="checkbox" id="tz-force-work" />
        <span>Must be in their working hours</span>
      </label>
    </div>
    
    <div id="tz-suggestion-result"></div>
  </div>
</div>

<script>
// Comprehensive list of world cities with timezones
const worldCities = [
  // Asia
  { value: 'Asia/Hong_Kong', label: 'Hong Kong', country: 'China' },
  { value: 'Asia/Shanghai', label: 'Shanghai', country: 'China' },
  { value: 'Asia/Shanghai', label: 'Beijing', country: 'China' },
  { value: 'Asia/Shanghai', label: 'Shenzhen', country: 'China' },
  { value: 'Asia/Shanghai', label: 'Guangzhou', country: 'China' },
  { value: 'Asia/Shanghai', label: 'Chongqing', country: 'China' },
  { value: 'Asia/Taipei', label: 'Taipei', country: 'Taiwan' },
  { value: 'Asia/Tokyo', label: 'Tokyo', country: 'Japan' },
  { value: 'Asia/Tokyo', label: 'Osaka', country: 'Japan' },
  { value: 'Asia/Seoul', label: 'Seoul', country: 'South Korea' },
  { value: 'Asia/Seoul', label: 'Busan', country: 'South Korea' },
  { value: 'Asia/Singapore', label: 'Singapore', country: 'Singapore' },
  { value: 'Asia/Kuala_Lumpur', label: 'Kuala Lumpur', country: 'Malaysia' },
  { value: 'Asia/Bangkok', label: 'Bangkok', country: 'Thailand' },
  { value: 'Asia/Ho_Chi_Minh', label: 'Ho Chi Minh City', country: 'Vietnam' },
  { value: 'Asia/Bangkok', label: 'Hanoi', country: 'Vietnam' },
  { value: 'Asia/Jakarta', label: 'Jakarta', country: 'Indonesia' },
  { value: 'Asia/Manila', label: 'Manila', country: 'Philippines' },
  { value: 'Asia/Kolkata', label: 'Mumbai', country: 'India' },
  { value: 'Asia/Kolkata', label: 'Delhi', country: 'India' },
  { value: 'Asia/Kolkata', label: 'Bangalore', country: 'India' },
  { value: 'Asia/Kolkata', label: 'Hyderabad', country: 'India' },
  { value: 'Asia/Kolkata', label: 'Chennai', country: 'India' },
  { value: 'Asia/Kolkata', label: 'Kolkata', country: 'India' },
  { value: 'Asia/Kolkata', label: 'Pune', country: 'India' },
  { value: 'Asia/Dhaka', label: 'Dhaka', country: 'Bangladesh' },
  { value: 'Asia/Karachi', label: 'Karachi', country: 'Pakistan' },
  { value: 'Asia/Karachi', label: 'Lahore', country: 'Pakistan' },
  { value: 'Asia/Dubai', label: 'Dubai', country: 'UAE' },
  { value: 'Asia/Dubai', label: 'Abu Dhabi', country: 'UAE' },
  { value: 'Asia/Riyadh', label: 'Riyadh', country: 'Saudi Arabia' },
  { value: 'Asia/Jerusalem', label: 'Tel Aviv', country: 'Israel' },
  { value: 'Asia/Jerusalem', label: 'Jerusalem', country: 'Israel' },
  { value: 'Asia/Tehran', label: 'Tehran', country: 'Iran' },
  { value: 'Europe/Istanbul', label: 'Istanbul', country: 'Turkey' },
  
  // Europe
  { value: 'Europe/London', label: 'London', country: 'UK' },
  { value: 'Europe/London', label: 'Cambridge', country: 'UK' },
  { value: 'Europe/London', label: 'Oxford', country: 'UK' },
  { value: 'Europe/London', label: 'Birmingham', country: 'UK' },
  { value: 'Europe/London', label: 'Bristol', country: 'UK' },
  { value: 'Europe/London', label: 'Leeds', country: 'UK' },
  { value: 'Europe/London', label: 'Liverpool', country: 'UK' },
  { value: 'Europe/London', label: 'Manchester', country: 'UK' },
  { value: 'Europe/London', label: 'Glasgow', country: 'UK' },
  { value: 'Europe/London', label: 'Edinburgh', country: 'UK' },
  { value: 'Europe/Dublin', label: 'Dublin', country: 'Ireland' },
  { value: 'Europe/Paris', label: 'Paris', country: 'France' },
  { value: 'Europe/Paris', label: 'Lyon', country: 'France' },
  { value: 'Europe/Berlin', label: 'Berlin', country: 'Germany' },
  { value: 'Europe/Berlin', label: 'Munich', country: 'Germany' },
  { value: 'Europe/Berlin', label: 'Frankfurt', country: 'Germany' },
  { value: 'Europe/Berlin', label: 'Hamburg', country: 'Germany' },
  { value: 'Europe/Zurich', label: 'Zurich', country: 'Switzerland' },
  { value: 'Europe/Zurich', label: 'Geneva', country: 'Switzerland' },
  { value: 'Europe/Amsterdam', label: 'Amsterdam', country: 'Netherlands' },
  { value: 'Europe/Amsterdam', label: 'Rotterdam', country: 'Netherlands' },
  { value: 'Europe/Amsterdam', label: 'Utrecht', country: 'Netherlands' },
  { value: 'Europe/Amsterdam', label: 'Leiden', country: 'Netherlands' },
  { value: 'Europe/Brussels', label: 'Brussels', country: 'Belgium' },
  { value: 'Europe/Brussels', label: 'Leuven', country: 'Belgium' },
  { value: 'Europe/Vienna', label: 'Vienna', country: 'Austria' },
  { value: 'Europe/Rome', label: 'Rome', country: 'Italy' },
  { value: 'Europe/Rome', label: 'Milan', country: 'Italy' },
  { value: 'Europe/Madrid', label: 'Madrid', country: 'Spain' },
  { value: 'Europe/Madrid', label: 'Barcelona', country: 'Spain' },
  { value: 'Europe/Lisbon', label: 'Lisbon', country: 'Portugal' },
  { value: 'Europe/Stockholm', label: 'Stockholm', country: 'Sweden' },
  { value: 'Europe/Oslo', label: 'Oslo', country: 'Norway' },
  { value: 'Europe/Copenhagen', label: 'Copenhagen', country: 'Denmark' },
  { value: 'Europe/Helsinki', label: 'Helsinki', country: 'Finland' },
  { value: 'Europe/Warsaw', label: 'Warsaw', country: 'Poland' },
  { value: 'Europe/Prague', label: 'Prague', country: 'Czech Republic' },
  { value: 'Europe/Budapest', label: 'Budapest', country: 'Hungary' },
  { value: 'Europe/Athens', label: 'Athens', country: 'Greece' },
  { value: 'Europe/Moscow', label: 'Moscow', country: 'Russia' },
  { value: 'Europe/Moscow', label: 'St Petersburg', country: 'Russia' },
  
  // North America
  { value: 'America/New_York', label: 'New York', country: 'USA' },
  { value: 'America/New_York', label: 'Boston', country: 'USA' },
  { value: 'America/New_York', label: 'Cambridge MA', country: 'USA' },
  { value: 'America/New_York', label: 'New Haven', country: 'USA' },
  { value: 'America/New_York', label: 'Princeton', country: 'USA' },
  { value: 'America/New_York', label: 'Philadelphia', country: 'USA' },
  { value: 'America/New_York', label: 'Baltimore', country: 'USA' },
  { value: 'America/New_York', label: 'Washington DC', country: 'USA' },
  { value: 'America/New_York', label: 'Pittsburgh', country: 'USA' },
  { value: 'America/New_York', label: 'Durham NC', country: 'USA' },
  { value: 'America/New_York', label: 'Chapel Hill', country: 'USA' },
  { value: 'America/New_York', label: 'Miami', country: 'USA' },
  { value: 'America/New_York', label: 'Atlanta', country: 'USA' },
  { value: 'America/Chicago', label: 'Chicago', country: 'USA' },
  { value: 'America/Chicago', label: 'Ann Arbor', country: 'USA' },
  { value: 'America/Chicago', label: 'Madison', country: 'USA' },
  { value: 'America/Chicago', label: 'Minneapolis', country: 'USA' },
  { value: 'America/Chicago', label: 'Houston', country: 'USA' },
  { value: 'America/Chicago', label: 'Dallas', country: 'USA' },
  { value: 'America/Chicago', label: 'Austin', country: 'USA' },
  { value: 'America/Denver', label: 'Denver', country: 'USA' },
  { value: 'America/Denver', label: 'Boulder', country: 'USA' },
  { value: 'America/Denver', label: 'Salt Lake City', country: 'USA' },
  { value: 'America/Phoenix', label: 'Phoenix', country: 'USA' },
  { value: 'America/Los_Angeles', label: 'Los Angeles', country: 'USA' },
  { value: 'America/Los_Angeles', label: 'San Francisco', country: 'USA' },
  { value: 'America/Los_Angeles', label: 'Berkeley', country: 'USA' },
  { value: 'America/Los_Angeles', label: 'Stanford', country: 'USA' },
  { value: 'America/Los_Angeles', label: 'San Diego', country: 'USA' },
  { value: 'America/Los_Angeles', label: 'Seattle', country: 'USA' },
  { value: 'America/Los_Angeles', label: 'Portland', country: 'USA' },
  { value: 'America/Anchorage', label: 'Anchorage', country: 'USA' },
  { value: 'Pacific/Honolulu', label: 'Honolulu', country: 'USA' },
  { value: 'America/Toronto', label: 'Toronto', country: 'Canada' },
  { value: 'America/Toronto', label: 'Montreal', country: 'Canada' },
  { value: 'America/Toronto', label: 'Ottawa', country: 'Canada' },
  { value: 'America/Vancouver', label: 'Vancouver', country: 'Canada' },
  { value: 'America/Edmonton', label: 'Calgary', country: 'Canada' },
  { value: 'America/Edmonton', label: 'Edmonton', country: 'Canada' },
  { value: 'America/Mexico_City', label: 'Mexico City', country: 'Mexico' },
  
  // South America
  { value: 'America/Sao_Paulo', label: 'São Paulo', country: 'Brazil' },
  { value: 'America/Sao_Paulo', label: 'Rio de Janeiro', country: 'Brazil' },
  { value: 'America/Argentina/Buenos_Aires', label: 'Buenos Aires', country: 'Argentina' },
  { value: 'America/Santiago', label: 'Santiago', country: 'Chile' },
  { value: 'America/Lima', label: 'Lima', country: 'Peru' },
  { value: 'America/Bogota', label: 'Bogota', country: 'Colombia' },
  
  // Oceania
  { value: 'Australia/Sydney', label: 'Sydney', country: 'Australia' },
  { value: 'Australia/Melbourne', label: 'Melbourne', country: 'Australia' },
  { value: 'Australia/Brisbane', label: 'Brisbane', country: 'Australia' },
  { value: 'Australia/Perth', label: 'Perth', country: 'Australia' },
  { value: 'Australia/Adelaide', label: 'Adelaide', country: 'Australia' },
  { value: 'Australia/Sydney', label: 'Canberra', country: 'Australia' },
  { value: 'Australia/Hobart', label: 'Hobart', country: 'Australia' },
  { value: 'Pacific/Auckland', label: 'Auckland', country: 'New Zealand' },
  { value: 'Pacific/Auckland', label: 'Wellington', country: 'New Zealand' },
  { value: 'Pacific/Auckland', label: 'Christchurch', country: 'New Zealand' },
  
  // Africa
  { value: 'Africa/Cairo', label: 'Cairo', country: 'Egypt' },
  { value: 'Africa/Johannesburg', label: 'Johannesburg', country: 'South Africa' },
  { value: 'Africa/Cape_Town', label: 'Cape Town', country: 'South Africa' },
  { value: 'Africa/Lagos', label: 'Lagos', country: 'Nigeria' },
  { value: 'Africa/Nairobi', label: 'Nairobi', country: 'Kenya' },
  { value: 'Africa/Casablanca', label: 'Casablanca', country: 'Morocco' },
];

let targetZones = [];  // Start with empty list
let userTimezone = '';

function init() {
  // Detect user timezone
  userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  const userCity = worldCities.find(c => c.value === userTimezone);
  const detectedDiv = document.getElementById('tz-detected');
  detectedDiv.textContent = `Detected: ${userCity ? `${userCity.label}, ${userCity.country}` : userTimezone}`;
  
  // Populate source select with search
  populateSourceSelect();
  
  // Set default date to tomorrow
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  document.getElementById('tz-date').value = tomorrow.toISOString().split('T')[0];
  
  // Add event listeners for all inputs - auto update everything
  const autoUpdateHandler = () => {
    updateResults();
    autoUpdateBestTime();
  };
  
  document.getElementById('tz-date').addEventListener('change', autoUpdateHandler);
  document.getElementById('tz-time').addEventListener('change', autoUpdateHandler);
  document.getElementById('tz-source').addEventListener('change', autoUpdateHandler);
  document.getElementById('tz-work-start').addEventListener('change', autoUpdateHandler);
  document.getElementById('tz-work-end').addEventListener('change', autoUpdateHandler);
  
  // Setup force work hours checkbox styling and auto-update
  const forceWorkCheckbox = document.getElementById('tz-force-work');
  const forceWorkLabel = document.getElementById('tz-force-work-label');
  forceWorkCheckbox.addEventListener('change', () => {
    forceWorkLabel.classList.toggle('checked', forceWorkCheckbox.checked);
    autoUpdateBestTime();
  });
  // Initialize checked state
  forceWorkLabel.classList.toggle('checked', forceWorkCheckbox.checked);
  
  // Add event listener for priority selector change
  document.getElementById('tz-priority').addEventListener('change', () => {
    updateForceWorkVisibility();
    autoUpdateBestTime();
  });
  
  updateResults();
}

// Auto-update best time when inputs change
function autoUpdateBestTime() {
  if (targetZones.length > 0) {
    suggestBestTime();
  }
}

function populateSourceSelect() {
  const sourceSelect = document.getElementById('tz-source');
  const uniqueTimezones = [...new Map(worldCities.map(c => [c.value, c])).values()];
  
  uniqueTimezones.forEach(tz => {
    const option = document.createElement('option');
    option.value = tz.value;
    option.textContent = `${tz.label}, ${tz.country}`;
    sourceSelect.appendChild(option);
  });
  
  // Set default to user's timezone
  const hasUserTz = uniqueTimezones.some(tz => tz.value === userTimezone);
  sourceSelect.value = hasUserTz ? userTimezone : 'Asia/Hong_Kong';
}

function getTimeInZone(date, timezone) {
  try {
    const formatter = new Intl.DateTimeFormat('en-US', {
      timeZone: timezone,
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });
    const parts = formatter.formatToParts(date);
    const hour = parseInt(parts.find(p => p.type === 'hour').value);
    const minute = parseInt(parts.find(p => p.type === 'minute').value);
    return hour * 60 + minute;
  } catch (e) {
    return 0;
  }
}

function isWorkingHours(timeInMinutes, workStart, workEnd) {
  return timeInMinutes >= workStart && timeInMinutes <= workEnd;
}

function updateResults() {
  const dateStr = document.getElementById('tz-date').value;
  const timeStr = document.getElementById('tz-time').value;
  const sourceTz = document.getElementById('tz-source').value;
  const workStartStr = document.getElementById('tz-work-start').value;
  const workEndStr = document.getElementById('tz-work-end').value;
  
  if (!dateStr || !timeStr) return;
  
  const workStart = parseInt(workStartStr.split(':')[0]) * 60 + parseInt(workStartStr.split(':')[1]);
  const workEnd = parseInt(workEndStr.split(':')[0]) * 60 + parseInt(workEndStr.split(':')[1]);
  
  const resultsDiv = document.getElementById('tz-results');
  resultsDiv.innerHTML = '';
  
  // If no collaborators, show empty state and hide sections
  if (targetZones.length === 0) {
    resultsDiv.innerHTML = '<div style="color:#737373;font-size:0.9em;padding:1em;text-align:center;background:#f5f5f4;border-radius:6px;">Click "+ Add City" to add collaborator locations.</div>';
    document.getElementById('tz-suggestion-section').style.display = 'none';
    document.getElementById('tz-legend').style.display = 'none';
    document.getElementById('tz-action-buttons').style.display = 'none';
    document.getElementById('tz-suggestion-result').innerHTML = '';
    return;
  }
  
  // Show sections and update priority selector
  document.getElementById('tz-suggestion-section').style.display = 'block';
  document.getElementById('tz-legend').style.display = 'flex';
  document.getElementById('tz-action-buttons').style.display = 'flex';
  updatePrioritySelector();
  
  // Create date in source timezone
  const sourceDate = new Date(`${dateStr}T${timeStr}:00`);
  
  // Check source timezone working hours
  const sourceTimeMinutes = getTimeInZone(sourceDate, sourceTz);
  const sourceIsWorking = isWorkingHours(sourceTimeMinutes, workStart, workEnd);
  
  // Check all target zones
  let allInWorkingHours = sourceIsWorking;
  const zoneResults = [];
  
  targetZones.forEach((tz, index) => {
    const cityInfo = worldCities.find(c => c.value === tz.value && c.label === tz.label);
    const tzLabel = cityInfo ? `${cityInfo.label}, ${cityInfo.country}` : tz.label;
    const timeInMinutes = getTimeInZone(sourceDate, tz.value);
    const isWorking = isWorkingHours(timeInMinutes, workStart, workEnd);
    
    if (!isWorking) allInWorkingHours = false;
    
    const targetFormatter = new Intl.DateTimeFormat('en-US', {
      timeZone: tz.value,
      weekday: 'short',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });
    
    const formatted = targetFormatter.format(sourceDate);
    const parts = formatted.split(', ');
    const dayDate = parts.slice(0, 2).join(', ');
    const time = parts[2] || parts[1];
    
    zoneResults.push({
      tz: tz.value, tzLabel, time, dayDate, isWorking, index
    });
  });
  
  // Render user's own time first
  const sourceFormatter = new Intl.DateTimeFormat('en-US', {
    timeZone: sourceTz,
    weekday: 'short',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  });
  const sourceFormatted = sourceFormatter.format(sourceDate);
  const sourceParts = sourceFormatted.split(', ');
  const sourceDayDate = sourceParts.slice(0, 2).join(', ');
  const sourceTime = sourceParts[2] || sourceParts[1];
  const sourceCityInfo = worldCities.find(c => c.value === sourceTz);
  const sourceLabel = sourceCityInfo ? `${sourceCityInfo.label}, ${sourceCityInfo.country}` : sourceTz.split('/').pop().replace(/_/g, ' ');
  
  const yourStatusClass = sourceIsWorking ? 'working' : 'outside';
  const yourStatusText = sourceIsWorking ? '✓ Working hours' : '○ Outside hours';
  
  const yourItem = document.createElement('div');
  yourItem.className = `tz-result-item your-time ${sourceIsWorking ? 'working-hours' : ''}`;
  yourItem.innerHTML = `
    <div class="tz-result-left">
      <span class="tz-result-zone">${sourceLabel}<span class="tz-you-badge">You</span></span>
      <span class="tz-result-status ${yourStatusClass}">${yourStatusText}</span>
    </div>
    <div class="tz-result-right">
      <span class="tz-result-time">${sourceTime}</span>
      <span class="tz-result-date">${sourceDayDate}</span>
    </div>
  `;
  resultsDiv.appendChild(yourItem);
  
  // Render collaborators results
  zoneResults.forEach(result => {
    const statusClass = result.isWorking ? 'working' : 'outside';
    const statusText = result.isWorking ? '✓ Working hours' : '○ Outside hours';
    const itemClass = result.isWorking ? 'working-hours' : '';
    
    const item = document.createElement('div');
    item.className = `tz-result-item ${itemClass}`;
    item.innerHTML = `
      <div class="tz-result-left">
        <span class="tz-result-zone">${result.tzLabel}</span>
        <span class="tz-result-status ${statusClass}">${statusText}</span>
      </div>
      <div class="tz-result-right">
        <span class="tz-result-time">${result.time}</span>
        <span class="tz-result-date">${result.dayDate}</span>
        <button class="tz-remove-btn" onclick="removeZone(${result.index})">✕</button>
      </div>
    `;
    resultsDiv.appendChild(item);
  });
}

function formatMinutes(minutes) {
  const h = Math.floor(minutes / 60);
  const m = minutes % 60;
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
}

function addTargetZone() {
  // Create search container
  const container = document.createElement('div');
  container.className = 'tz-search-container';
  container.style.cssText = 'margin-bottom:1em;padding:1em;background:#fff;border:1px solid #d6d3d1;border-radius:6px;';
  
  const searchInput = document.createElement('input');
  searchInput.type = 'text';
  searchInput.placeholder = 'Search city name... (↑↓ to navigate, Enter to select)';
  searchInput.style.cssText = 'width:100%;padding:0.6em;border:1px solid #d6d3d1;border-radius:4px;font-size:0.95em;box-sizing:border-box;';
  
  const resultsList = document.createElement('div');
  resultsList.style.cssText = 'max-height:200px;overflow-y:auto;margin-top:0.5em;border:1px solid #e5e5e5;border-radius:4px;display:none;';
  
  const btnContainer = document.createElement('div');
  btnContainer.style.cssText = 'display:flex;justify-content:flex-end;margin-top:0.5em;';
  
  const cancelBtn = document.createElement('button');
  cancelBtn.textContent = 'Cancel';
  cancelBtn.style.cssText = 'padding:0.4em 0.8em;background:#f5f5f4;border:1px solid #d6d3d1;border-radius:4px;cursor:pointer;font-size:0.85em;';
  cancelBtn.onclick = () => container.remove();
  btnContainer.appendChild(cancelBtn);
  
  let currentMatches = [];
  let selectedIndex = -1;
  
  const updateSelection = () => {
    const items = resultsList.querySelectorAll('.tz-search-item');
    items.forEach((item, index) => {
      if (index === selectedIndex) {
        item.style.background = '#ecfdf5';
        item.style.borderLeft = '3px solid #14532d';
        // Scroll into view if needed
        item.scrollIntoView({ block: 'nearest' });
      } else {
        item.style.background = '#fff';
        item.style.borderLeft = 'none';
      }
    });
  };
  
  const selectCity = (city) => {
    targetZones.push({ value: city.value, label: city.label });
    container.remove();
    updateResults();
    autoUpdateBestTime();
  };
  
  searchInput.addEventListener('keydown', (e) => {
    if (currentMatches.length === 0) return;
    
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      selectedIndex = Math.min(selectedIndex + 1, currentMatches.length - 1);
      updateSelection();
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      selectedIndex = Math.max(selectedIndex - 1, 0);
      updateSelection();
    } else if (e.key === 'Enter') {
      e.preventDefault();
      if (selectedIndex >= 0 && selectedIndex < currentMatches.length) {
        selectCity(currentMatches[selectedIndex]);
      } else if (currentMatches.length > 0) {
        // If nothing selected, select first match
        selectCity(currentMatches[0]);
      }
    } else if (e.key === 'Escape') {
      container.remove();
    }
  });
  
  searchInput.addEventListener('input', () => {
    const query = searchInput.value.toLowerCase().trim();
    resultsList.innerHTML = '';
    selectedIndex = -1;
    currentMatches = [];
    
    if (query.length < 1) {
      resultsList.style.display = 'none';
      return;
    }
    
    currentMatches = worldCities.filter(c => {
      const searchStr = `${c.label} ${c.country}`.toLowerCase();
      const alreadyAdded = targetZones.some(t => t.value === c.value && t.label === c.label);
      return searchStr.includes(query) && !alreadyAdded;
    }).slice(0, 10);
    
    if (currentMatches.length === 0) {
      resultsList.innerHTML = '<div style="padding:0.8em;color:#737373;font-size:0.9em;">No matching cities found</div>';
      resultsList.style.display = 'block';
      return;
    }
    
    currentMatches.forEach((city, index) => {
      const item = document.createElement('div');
      item.className = 'tz-search-item';
      item.style.cssText = 'padding:0.6em 0.8em;cursor:pointer;border-bottom:1px solid #f5f5f5;font-size:0.9em;transition:background 0.1s;';
      item.innerHTML = `<strong>${city.label}</strong><span style="color:#737373;margin-left:0.5em;">${city.country}</span>`;
      item.onmouseenter = () => {
        selectedIndex = index;
        updateSelection();
      };
      item.onclick = () => selectCity(city);
      resultsList.appendChild(item);
    });
    
    resultsList.style.display = 'block';
  });
  
  container.appendChild(searchInput);
  container.appendChild(resultsList);
  container.appendChild(btnContainer);
  
  document.getElementById('tz-results').insertAdjacentElement('beforebegin', container);
  searchInput.focus();
}

function removeZone(index) {
  targetZones.splice(index, 1);
  updateResults();
  autoUpdateBestTime();
}

function copyResults() {
  if (targetZones.length === 0) {
    alert('No collaborators added yet.');
    return;
  }
  
  const dateStr = document.getElementById('tz-date').value;
  const timeStr = document.getElementById('tz-time').value;
  const sourceTz = document.getElementById('tz-source').value;
  const sourceCity = worldCities.find(c => c.value === sourceTz);
  const sourceLabel = sourceCity ? `${sourceCity.label}, ${sourceCity.country}` : sourceTz;
  
  let text = `📅 Meeting Time\n`;
  text += `━━━━━━━━━━━━━━━━━━\n`;
  text += `${sourceLabel}: ${dateStr} ${timeStr}\n\n`;
  
  const sourceDate = new Date(`${dateStr}T${timeStr}:00`);
  
  targetZones.forEach(tz => {
    const cityInfo = worldCities.find(c => c.value === tz.value && c.label === tz.label);
    const tzLabel = cityInfo ? `${cityInfo.label}, ${cityInfo.country}` : tz.label;
    const formatter = new Intl.DateTimeFormat('en-US', {
      timeZone: tz.value,
      weekday: 'short',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });
    text += `${tzLabel}: ${formatter.format(sourceDate)}\n`;
  });
  
  navigator.clipboard.writeText(text).then(() => {
    const btn = document.querySelector('.tz-copy-btn');
    btn.textContent = '✓ Copied!';
    btn.classList.add('copied');
    setTimeout(() => {
      btn.textContent = '📋 Copy All Times';
      btn.classList.remove('copied');
    }, 2000);
  });
}

function downloadICS() {
  if (targetZones.length === 0) {
    alert('No collaborators added yet.');
    return;
  }
  
  const dateStr = document.getElementById('tz-date').value;
  const timeStr = document.getElementById('tz-time').value;
  const sourceTz = document.getElementById('tz-source').value;
  const sourceCity = worldCities.find(c => c.value === sourceTz);
  const sourceLabel = sourceCity ? sourceCity.label : 'Meeting';
  
  // Parse date and time
  const [year, month, day] = dateStr.split('-').map(Number);
  const [hour, minute] = timeStr.split(':').map(Number);
  
  // Create start date (local time based on source timezone)
  const startDate = new Date(`${dateStr}T${timeStr}:00`);
  
  // Default meeting duration: 1 hour
  const endDate = new Date(startDate.getTime() + 60 * 60 * 1000);
  
  // Format date for ICS (UTC format: YYYYMMDDTHHMMSSZ)
  const formatICSDate = (date) => {
    return date.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
  };
  
  // Format date for DTSTART with timezone
  const formatICSDateLocal = (date) => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    const h = String(date.getHours()).padStart(2, '0');
    const min = String(date.getMinutes()).padStart(2, '0');
    return `${y}${m}${d}T${h}${min}00`;
  };
  
  // Build description with all timezone info
  let description = 'Meeting times for all participants:\\n\\n';
  description += `${sourceLabel}: ${dateStr} ${timeStr}\\n`;
  
  targetZones.forEach(tz => {
    const cityInfo = worldCities.find(c => c.value === tz.value && c.label === tz.label);
    const tzLabel = cityInfo ? cityInfo.label : tz.label;
    const formatter = new Intl.DateTimeFormat('en-US', {
      timeZone: tz.value,
      weekday: 'short',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });
    description += `${tzLabel}: ${formatter.format(startDate)}\\n`;
  });
  
  // Build attendee list for description
  const attendeeLocations = targetZones.map(tz => {
    const cityInfo = worldCities.find(c => c.value === tz.value && c.label === tz.label);
    return cityInfo ? cityInfo.label : tz.label;
  }).join(', ');
  
  // Generate unique ID
  const uid = `meeting-${Date.now()}-${Math.random().toString(36).substr(2, 9)}@timezone-converter`;
  
  // Create ICS content
  const icsContent = [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//Timezone Converter//guhaogao.com//EN',
    'CALSCALE:GREGORIAN',
    'METHOD:PUBLISH',
    'BEGIN:VEVENT',
    `UID:${uid}`,
    `DTSTAMP:${formatICSDate(new Date())}`,
    `DTSTART;TZID=${sourceTz}:${formatICSDateLocal(startDate)}`,
    `DTEND;TZID=${sourceTz}:${formatICSDateLocal(endDate)}`,
    `SUMMARY:Meeting (${sourceLabel} + ${attendeeLocations})`,
    `DESCRIPTION:${description}`,
    'STATUS:CONFIRMED',
    'END:VEVENT',
    'END:VCALENDAR'
  ].join('\r\n');
  
  // Create download link
  const blob = new Blob([icsContent], { type: 'text/calendar;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `meeting-${dateStr}-${timeStr.replace(':', '')}.ics`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
  
  // Update button state
  const btn = document.getElementById('tz-ics-btn');
  btn.textContent = '✓ Downloaded!';
  btn.classList.add('downloaded');
  setTimeout(() => {
    btn.textContent = '📅 Download .ics';
    btn.classList.remove('downloaded');
  }, 2000);
}

// Calculate penalty score for a given hour (0-23)
// Lower score = better time
function getTimePenalty(hourInMinutes) {
  const hour = hourInMinutes / 60;
  
  // Midnight to 6am: Heavy penalty (sleep time)
  if (hour >= 0 && hour < 6) {
    return 100 + (6 - hour) * 20; // 100-220 penalty
  }
  // 6am to 8am: Moderate penalty (early morning)
  if (hour >= 6 && hour < 8) {
    return 30 + (8 - hour) * 15; // 30-60 penalty
  }
  // 8am to 9am: Light penalty
  if (hour >= 8 && hour < 9) {
    return 10;
  }
  // 9am to 18pm: Ideal working hours - no penalty
  if (hour >= 9 && hour < 18) {
    return 0;
  }
  // 18pm to 20pm: Light penalty (evening)
  if (hour >= 18 && hour < 20) {
    return 10 + (hour - 18) * 5; // 10-20 penalty
  }
  // 20pm to 22pm: Moderate penalty
  if (hour >= 20 && hour < 22) {
    return 30 + (hour - 20) * 15; // 30-60 penalty
  }
  // 22pm to midnight: Heavy penalty
  if (hour >= 22) {
    return 80 + (hour - 22) * 10; // 80-100 penalty
  }
  return 50; // fallback
}

// Calculate distance from ideal working hours center (13:30 = 810 minutes)
function getWorkingHoursDistance(timeInMinutes, workStart, workEnd) {
  const workCenter = (workStart + workEnd) / 2;
  const workHalfRange = (workEnd - workStart) / 2;
  
  // If within working hours, calculate distance from center
  if (timeInMinutes >= workStart && timeInMinutes <= workEnd) {
    return Math.abs(timeInMinutes - workCenter) / workHalfRange * 10; // 0-10 score
  }
  
  // If outside working hours, add extra penalty based on distance
  if (timeInMinutes < workStart) {
    return 20 + (workStart - timeInMinutes) / 30; // 20+ penalty
  }
  return 20 + (timeInMinutes - workEnd) / 30; // 20+ penalty
}

function suggestBestTime() {
  if (targetZones.length === 0) {
    document.getElementById('tz-suggestion-result').innerHTML = '';
    return;
  }
  
  const dateStr = document.getElementById('tz-date').value;
  const sourceTz = document.getElementById('tz-source').value;
  const workStartStr = document.getElementById('tz-work-start').value;
  const workEndStr = document.getElementById('tz-work-end').value;
  const prioritySelect = document.getElementById('tz-priority');
  const focusTzValue = prioritySelect.value;
  const hasFocusCity = focusTzValue !== 'none';
  const focusTz = hasFocusCity ? focusTzValue : sourceTz; // Use source for AM/PM split when no focus
  const forceWorkHours = hasFocusCity && document.getElementById('tz-force-work').checked;
  
  const workStart = parseInt(workStartStr.split(':')[0]) * 60 + parseInt(workStartStr.split(':')[1]);
  const workEnd = parseInt(workEndStr.split(':')[0]) * 60 + parseInt(workEndStr.split(':')[1]);
  
  // All timezones to consider (source + targets)
  const allZones = [{ value: sourceTz, label: 'Your timezone' }, ...targetZones];
  
  // For "fair mode" (no priority), find two good but different options
  // For "priority mode", split by AM/PM of priority participant
  let bestOption1 = { hour: 10, score: Infinity, breakdown: [] };
  let bestOption2 = { hour: 14, score: Infinity, breakdown: [] };
  
  // Collect all scored slots first
  const allSlots = [];
  
  // Check every 30-minute slot
  for (let slot = 0; slot < 48; slot++) {
    const hour = Math.floor(slot / 2);
    const minute = (slot % 2) * 30;
    const testDate = new Date(`${dateStr}T${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00`);
    
    // Check focus city time first (only relevant when hasFocusCity)
    const focusTime = getTimeInZone(testDate, focusTz);
    
    // If force working hours is enabled, skip times outside working hours for focus city
    if (forceWorkHours) {
      if (focusTime < workStart || focusTime > workEnd) {
        continue; // Skip this slot
      }
    }
    
    let totalScore = 0;
    let breakdown = [];
    let hasExtremeTime = false;
    
    for (const tz of allZones) {
      const timeInMinutes = getTimeInZone(testDate, tz.value);
      const timePenalty = getTimePenalty(timeInMinutes);
      const distancePenalty = getWorkingHoursDistance(timeInMinutes, workStart, workEnd);
      const zoneScore = timePenalty + distancePenalty;
      
      // Check for extreme times (midnight to 6am)
      const hourInZone = timeInMinutes / 60;
      if (hourInZone >= 0 && hourInZone < 6) {
        hasExtremeTime = true;
      }
      
      totalScore += zoneScore;
      
      const cityInfo = worldCities.find(c => c.value === tz.value && c.label === tz.label);
      const label = cityInfo ? cityInfo.label : (tz.label === 'Your timezone' ? 'You' : tz.value);
      breakdown.push({
        label,
        value: tz.value,
        timeInMinutes,
        score: zoneScore,
        timePenalty,
        distancePenalty
      });
    }
    
    // Add extra penalty for having any extreme time
    if (hasExtremeTime) {
      totalScore += 50;
    }
    
    allSlots.push({ hour, minute, score: totalScore, breakdown: [...breakdown], focusTime });
  }
  
  if (hasFocusCity) {
    // Priority mode: split by AM/PM of priority participant
    for (const slot of allSlots) {
      const isAM = slot.focusTime < 720; // 720 = 12:00
      if (isAM && slot.score < bestOption1.score) {
        bestOption1 = slot;
      } else if (!isAM && slot.score < bestOption2.score) {
        bestOption2 = slot;
      }
    }
  } else {
    // Fair mode: find two good options with at least 3-hour difference
    // Sort by score to get best options
    allSlots.sort((a, b) => a.score - b.score);
    
    if (allSlots.length > 0) {
      bestOption1 = allSlots[0];
      
      // Find second best that's at least 3 hours different
      for (const slot of allSlots) {
        const hourDiff = Math.abs((slot.hour + slot.minute/60) - (bestOption1.hour + bestOption1.minute/60));
        if (hourDiff >= 3 && slot.score < bestOption2.score) {
          bestOption2 = slot;
          break;
        }
      }
      
      // If no option with 3+ hour difference, just take second best
      if (bestOption2.score === Infinity && allSlots.length > 1) {
        bestOption2 = allSlots[1];
      }
    }
  }
  
  // Get focus city label for display
  const focusCityInfo = hasFocusCity ? getFocusCityInfo(focusTz) : null;
  
  // Collect more alternatives (different from main options, at least 2 hours apart)
  const moreOptions = [];
  const usedHours = new Set();
  usedHours.add(bestOption1.hour);
  usedHours.add(bestOption2.hour);
  
  // Sort all slots by score
  const sortedSlots = [...allSlots].sort((a, b) => a.score - b.score);
  
  for (const slot of sortedSlots) {
    if (moreOptions.length >= 4) break; // Max 4 more options
    if (slot.score === Infinity) continue;
    
    // Check if this slot is at least 2 hours away from all used hours
    let tooClose = false;
    for (const usedHour of usedHours) {
      const hourDiff = Math.abs((slot.hour + slot.minute/60) - usedHour);
      if (hourDiff < 2) {
        tooClose = true;
        break;
      }
    }
    
    if (!tooClose) {
      moreOptions.push(slot);
      usedHours.add(slot.hour + slot.minute/60);
    }
  }
  
  // Display both results with more options
  displaySuggestions(bestOption1, bestOption2, dateStr, sourceTz, workStart, workEnd, focusCityInfo, forceWorkHours, hasFocusCity, moreOptions);
}

function getFocusCityInfo(focusTz) {
  const sourceTz = document.getElementById('tz-source').value;
  if (focusTz === sourceTz) {
    const sourceCity = worldCities.find(c => c.value === sourceTz);
    return sourceCity ? `${sourceCity.label} (You)` : 'Your timezone';
  }
  const targetCity = targetZones.find(t => t.value === focusTz);
  if (targetCity) {
    const cityInfo = worldCities.find(c => c.value === targetCity.value && c.label === targetCity.label);
    return cityInfo ? cityInfo.label : targetCity.label;
  }
  return focusTz;
}

function updatePrioritySelector() {
  const select = document.getElementById('tz-priority');
  const sourceTz = document.getElementById('tz-source').value;
  const currentValue = select.value;
  
  // Build options - keep "Everyone equally" as first option
  select.innerHTML = '<option value="none">⚖️ Everyone equally</option>';
  
  // Add source (your) timezone
  const sourceCity = worldCities.find(c => c.value === sourceTz);
  const sourceOption = document.createElement('option');
  sourceOption.value = sourceTz;
  sourceOption.textContent = sourceCity ? `🏠 ${sourceCity.label} (You)` : '🏠 Your timezone';
  select.appendChild(sourceOption);
  
  // Add collaborator timezones
  targetZones.forEach(tz => {
    const cityInfo = worldCities.find(c => c.value === tz.value && c.label === tz.label);
    const option = document.createElement('option');
    option.value = tz.value;
    option.textContent = cityInfo ? `👤 ${cityInfo.label}, ${cityInfo.country}` : `👤 ${tz.label}`;
    option.dataset.label = tz.label;
    select.appendChild(option);
  });
  
  // Restore previous selection if still valid
  const validValues = ['none', sourceTz, ...targetZones.map(t => t.value)];
  if (currentValue && validValues.includes(currentValue)) {
    select.value = currentValue;
  }
  
  // Hide/show force work hours checkbox based on priority selection
  updateForceWorkVisibility();
}

function updateForceWorkVisibility() {
  const focusValue = document.getElementById('tz-priority').value;
  const forceWorkLabel = document.getElementById('tz-force-work-label');
  
  if (focusValue === 'none') {
    forceWorkLabel.style.display = 'none';
  } else {
    forceWorkLabel.style.display = 'flex';
  }
}

function displaySuggestions(bestAM, bestPM, dateStr, sourceTz, workStart, workEnd, focusCityLabel, forceWorkHours, hasFocusCity, moreOptions = []) {
  const resultDiv = document.getElementById('tz-suggestion-result');
  const sourceCity = worldCities.find(c => c.value === sourceTz);
  const sourceLabel = sourceCity ? sourceCity.label : sourceTz;
  
  // Reset all apply buttons to default state when regenerating suggestions
  document.querySelectorAll('.tz-apply-btn').forEach(btn => {
    btn.classList.remove('applied');
    btn.innerHTML = '✓ Apply This Time';
    btn.disabled = false;
  });
  
  const constraintInfo = (hasFocusCity && forceWorkHours)
    ? `<span style="color:#14532d;font-size:0.85em;">✓ ${focusCityLabel} constrained to working hours</span>` 
    : '';
  
  // Format quality emoji based on score
  const getQualityEmoji = (score, breakdownLength) => {
    const avgScore = score / breakdownLength;
    if (avgScore < 15) return '🌟';
    if (avgScore < 30) return '👍';
    if (avgScore < 50) return '👌';
    if (avgScore < 80) return '⚠️';
    return '😓';
  };
  
  // Format more options as compact list
  const formatMoreOptions = () => {
    if (moreOptions.length === 0) return '';
    
    const optionsHtml = moreOptions.map(opt => {
      const timeStr = `${opt.hour.toString().padStart(2, '0')}:${(opt.minute || 0).toString().padStart(2, '0')}`;
      const emoji = getQualityEmoji(opt.score, opt.breakdown.length);
      // Build tooltip with all times
      const tooltip = opt.breakdown.map(b => {
        const h = Math.floor(b.timeInMinutes / 60);
        const m = b.timeInMinutes % 60;
        return `${b.label}: ${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
      }).join('\n');
      
      return `<div class="tz-mini-option" onclick="applyBestTime(${opt.hour}, ${opt.minute || 0}, this)" title="${tooltip}">
        <span class="tz-mini-option-quality">${emoji}</span>
        <span class="tz-mini-option-time">${timeStr}</span>
      </div>`;
    }).join('');
    
    return `
      <div class="tz-more-options">
        <div class="tz-more-options-title">📌 More alternatives for your time (hover for details):</div>
        <div class="tz-more-options-list">${optionsHtml}</div>
      </div>
    `;
  };
  
  const formatOption = (best, label) => {
    if (best.score === Infinity) {
      return `<div class="tz-suggestion-option disabled">
        <div class="tz-suggestion-option-title">${label}</div>
        <div style="color:#737373;font-size:0.9em;">No suitable time found</div>
      </div>`;
    }
    
    const timeStr = `${best.hour.toString().padStart(2, '0')}:${(best.minute || 0).toString().padStart(2, '0')}`;
    
    // Quality assessment
    const avgScore = best.score / best.breakdown.length;
    let quality, qualityEmoji, qualityClass;
    if (avgScore < 15) {
      quality = 'Excellent'; qualityEmoji = '🌟'; qualityClass = 'excellent';
    } else if (avgScore < 30) {
      quality = 'Good'; qualityEmoji = '👍'; qualityClass = 'good';
    } else if (avgScore < 50) {
      quality = 'Acceptable'; qualityEmoji = '👌'; qualityClass = 'acceptable';
    } else if (avgScore < 80) {
      quality = 'Challenging'; qualityEmoji = '⚠️'; qualityClass = 'challenging';
    } else {
      quality = 'Difficult'; qualityEmoji = '😓'; qualityClass = 'difficult';
    }
    
    let breakdownHtml = best.breakdown.map(b => {
      const hour = Math.floor(b.timeInMinutes / 60);
      const minute = b.timeInMinutes % 60;
      const tStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
      const isInWorkHours = b.timeInMinutes >= workStart && b.timeInMinutes <= workEnd;
      const emoji = isInWorkHours ? '✓' : (hour >= 0 && hour < 7 ? '🌙' : (hour >= 20 ? '🌆' : '○'));
      return `<div>${emoji} <strong>${b.label}</strong>: ${tStr}</div>`;
    }).join('');
    
    return `
      <div class="tz-suggestion-option ${qualityClass}">
        <div class="tz-suggestion-option-header">
          <div class="tz-suggestion-option-title">${label}</div>
          <span class="tz-suggestion-score">${qualityEmoji} ${quality}</span>
        </div>
        <div class="tz-suggestion-time">${sourceLabel}: ${timeStr}</div>
        <div class="tz-suggestion-breakdown">${breakdownHtml}</div>
        <button class="tz-apply-btn" onclick="applyBestTime(${best.hour}, ${best.minute || 0}, this)">
          ✓ Apply This Time
        </button>
      </div>
    `;
  };
  
  // Different display based on whether there's a focus city
  if (hasFocusCity) {
    resultDiv.innerHTML = `
      <div class="tz-suggestion-result">
        <div class="tz-suggestion-title">🎯 Best Meeting Times Found</div>
        <div class="tz-suggestion-detail">
          Two options based on <strong>${focusCityLabel}</strong>'s morning/afternoon. ${constraintInfo}
        </div>
        <div class="tz-suggestion-options">
          ${formatOption(bestAM, `☀️ Morning in ${focusCityLabel}`)}
          ${formatOption(bestPM, `🌤️ Afternoon in ${focusCityLabel}`)}
        </div>
        ${formatMoreOptions()}
      </div>
    `;
  } else {
    // Fair mode: show two best options (at least 3 hours apart)
    resultDiv.innerHTML = `
      <div class="tz-suggestion-result">
        <div class="tz-suggestion-title">🎯 Best Meeting Times Found</div>
        <div class="tz-suggestion-detail">
          <span style="color:#14532d;">⚖️ Fair for everyone</span> — two options optimized to minimize inconvenience for all participants.
        </div>
        <div class="tz-suggestion-options">
          ${formatOption(bestAM, `🥇 Best Option`)}
          ${formatOption(bestPM, `🥈 Alternative`)}
        </div>
        ${formatMoreOptions()}
      </div>
    `;
  }
}

function applyBestTime(hour, minute, buttonElement) {
  document.getElementById('tz-time').value = `${hour.toString().padStart(2, '0')}:${(minute || 0).toString().padStart(2, '0')}`;
  updateResults();
  
  // Reset all apply buttons to default state
  document.querySelectorAll('.tz-apply-btn').forEach(btn => {
    btn.classList.remove('applied');
    btn.innerHTML = '✓ Apply This Time';
    btn.disabled = false;
  });
  
  // Reset all mini options to default state
  document.querySelectorAll('.tz-mini-option').forEach(opt => {
    opt.classList.remove('applied');
  });
  
  // Mark clicked button/option as applied
  if (buttonElement) {
    buttonElement.classList.add('applied');
    if (buttonElement.classList.contains('tz-apply-btn')) {
      buttonElement.innerHTML = '✓ Applied';
    }
  }
  
  // Scroll to results
  document.getElementById('tz-results').scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// Initialize
document.addEventListener('DOMContentLoaded', init);
if (document.readyState !== 'loading') init();
</script>

<h2 id="features">Features</h2>

<ul>
  <li><strong>Auto-detect timezone</strong>: Automatically detects your local timezone based on browser settings</li>
  <li><strong>100+ world cities</strong>: Search from major cities across all continents, including university towns (Cambridge, Stanford, Oxford, etc.)</li>
  <li><strong>Keyboard navigation</strong>: Use ↑↓ arrows to navigate search results, Enter to select, Esc to cancel</li>
  <li><strong>Working hours indicator</strong>: Visual markers show which times fall within/outside working hours</li>
  <li><strong>Overlap detection</strong>: Highlights when all participants are in their working hours simultaneously</li>
  <li><strong>🎯 Smart Best Time Finder</strong>:
    <ul>
      <li><strong>Priority mode</strong>: Optimize around a specific participant’s schedule (AM/PM options)</li>
      <li><strong>Fair mode</strong>: Find times that minimize inconvenience for everyone equally</li>
      <li><strong>Smart scoring</strong>: Heavily penalizes sleep hours (0-6am), moderately penalizes early/late hours</li>
      <li><strong>Multiple alternatives</strong>: Shows additional backup time options at a glance</li>
    </ul>
  </li>
  <li><strong>📋 Copy all times</strong>: One-click copy of formatted meeting times for easy sharing</li>
  <li><strong>📅 ICS download</strong>: Export to calendar file compatible with Google Calendar, Apple Calendar, Outlook, etc.</li>
</ul>

<h2 id="tips-for-scheduling-international-meetings">Tips for Scheduling International Meetings</h2>

<table>
  <thead>
    <tr>
      <th>Route</th>
      <th>Recommended Time</th>
      <th>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Asia ↔ Europe</strong></td>
      <td>08:00-10:00 HKT</td>
      <td>Afternoon in Europe (15:00-17:00 CET)</td>
    </tr>
    <tr>
      <td><strong>Asia ↔ US East</strong></td>
      <td>21:00-22:00 HKT</td>
      <td>Morning in NYC (08:00-09:00 EST)</td>
    </tr>
    <tr>
      <td><strong>Asia ↔ US West</strong></td>
      <td>09:00-10:00 HKT</td>
      <td>Evening before in SF (17:00-18:00 PST, previous day)</td>
    </tr>
    <tr>
      <td><strong>Europe ↔ US East</strong></td>
      <td>14:00-17:00 GMT</td>
      <td>Morning in US (09:00-12:00 EST)</td>
    </tr>
    <tr>
      <td><strong>Australia ↔ Europe</strong></td>
      <td>08:00-09:00 AEDT</td>
      <td>Evening before in Europe (21:00-22:00 CET)</td>
    </tr>
  </tbody>
</table>]]></content><author><name>Haogao Gu</name><email>work@guhaogao.com</email></author><category term="Productivity" /><summary type="html"><![CDATA[A simple tool to convert time across different time zones and find overlapping working hours with collaborators around the world.]]></summary></entry><entry><title type="html">Course notes: Molecular Evolution workshop in Marine Biological Laboratory, US</title><link href="https://guhaogao.com/posts/2025-05-22-MBL_ME_workshop" rel="alternate" type="text/html" title="Course notes: Molecular Evolution workshop in Marine Biological Laboratory, US" /><published>2025-05-22T00:00:00+08:00</published><updated>2025-05-22T00:00:00+08:00</updated><id>https://guhaogao.com/posts/MBL_ME_worksop</id><content type="html" xml:base="https://guhaogao.com/posts/2025-05-22-MBL_ME_workshop"><![CDATA[<p>Course materials are available at <a href="https://molevolworkshop.github.io/schedule/">here</a>.</p>

<h1 id="day-1">Day 1</h1>
<h2 id="introduction-to-phylogenetics---tracy-heath">Introduction to phylogenetics - Tracy Heath</h2>

<ul>
  <li>The Metazoa Phylogeny
    <ul>
      <li>There is scientific controversy over whether sponges (Porifera) or ctenophores (Ctenophora) are the earliest-diverging animal lineage; traditional morphological evidence supports sponges, but some molecular studies suggest ctenophores may be more basal.</li>
      <li>This debate impacts our understanding of early animal evolution—especially whether complex traits like nervous systems evolved early and were later lost in sponges, or evolved independently in multiple lineages.</li>
      <li>Check <a href="https://www.nature.com/articles/s41586-023-05936-6">this</a> new evidence in Nature.</li>
    </ul>
  </li>
</ul>

<h2 id="scientific-ethics---joseph-bielawski">Scientific ethics - Joseph Bielawski</h2>

<ul>
  <li>Ethical reasoning focus on what <em>I</em> (or <em>we</em>) should do, but not blaming others.</li>
  <li>Normalization of Deviance, you should not start doing something just because it is common, or you think it has small consequences.</li>
  <li>Take the anti-vax movement as an example, at first it was a small group of people (deviance, Andrew Wakefield etc.), but then it became normalized and now it is a big problem.</li>
  <li>If you do noting, you can be contributing to normalization of deviance.</li>
  <li>Scientist have social privilege, and they have obligations.</li>
</ul>

<h2 id="introduction-to-likelihood---paul-lewis">Introduction to Likelihood - Paul Lewis</h2>

<ul>
  <li>Why do we need the term likelihood?
    <ul>
      <li>Probability is describing the chance of an <strong>event/outcome/data</strong> given one model.</li>
      <li>Likelihood is describing the <strong>model/hypothesis/parameter</strong> given data.</li>
    </ul>
  </li>
  <li>Transition-transversion rate ratio = 1 equivalent to transition-transversion rate = 0.5.</li>
  <li>Site specific rate variation, e.g. $r_1$ for codon positions 1 and 2, $r_2$ for codon position 3.</li>
  <li>He said that even though the parameter in the Gamma and invariable site models can have correlation, a successful bayesian search algorithm should be able to deal with this, and there are no issue with identifiability.</li>
</ul>

<h2 id="model-based-phylogenetics---john-huelsenbeck">Model-based phylogenetics - John Huelsenbeck</h2>

<ul>
  <li>Both likelihood and distance methods can marginalize different histories along the branch (via the CTMC model).</li>
  <li>He revisited the Felsentein pruning algorithm.</li>
  <li>He explained the interpretation of the $Q$ matrix: If the process is in state $i$, we wait an exponentially distributed amount of time with parameter $-q_ii$ until the next substitution occurs; The change (after time of $e^{-q_ii}$) is $\frac{q_ij}{-q_ii}$ if the next state is $j$.</li>
  <li>Explained exponential distribution (waiting time for the first event), the gamma distribution (sum of exponential), the Poisson distribution (number of events in a time interval).</li>
  <li>One can simulate these mutations by simulating the waiting time until the next mutation, and then the change.</li>
  <li>You will arrive at the same result to $P(t)=e^{Qt}$. This accounts for all the ways that the process, starting in state $i$, can end up in state $j$ after time $t$.</li>
  <li>Note that there are two different marginalization: one is the marginalization of the history (Felsenstein), and the other is the marginalization of the multiple hits ($P(t)$).</li>
  <li>Stationary: if the branch length is long enough, no matter where you start, you will end up in one state with equal probability.</li>
  <li>We rescale the Q matrix such that the average rate of the process is $1$, then the time parameter $t$ in $P(t)=e^{Qt}$ directly represents the expected number of substitutions per site (the unit of the branch lengths). When $Q$ is scaled this way, the length of a branch ($v$) is directly interpretable as the expected number of substitutions that have occurred per site along that lineage.</li>
</ul>

<h1 id="day-2">Day 2</h1>

<h2 id="simulating-molecular-evolution---john-huelsenbeck">Simulating molecular evolution - John Huelsenbeck</h2>

<ul>
  <li>Transform a uniform random variable into an exponential random: $t=-\frac{ln(n)}{\lambda}$ (keeping CDF the same).</li>
  <li>Simulation starts from the $\pi_{A,C,G,T}$ from the root. Then we get a random number $u \in [0,1]$, and we find the first $u$ determines the root state.</li>
  <li>Below is an example code for simulating the state changes for v1.</li>
  <li>He also talked about codon model, rate variation and covarion models.</li>
</ul>

<div class="language-r highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Q_matrix</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">matrix</span><span class="p">(</span><span class="nf">c</span><span class="p">(</span><span class="w">
  </span><span class="m">-0.886</span><span class="p">,</span><span class="w"> </span><span class="m">0.19</span><span class="p">,</span><span class="w"> </span><span class="m">0.633</span><span class="p">,</span><span class="w"> </span><span class="m">0.063</span><span class="p">,</span><span class="w">
  </span><span class="m">0.253</span><span class="p">,</span><span class="w"> </span><span class="m">-0.696</span><span class="p">,</span><span class="w"> </span><span class="m">0.127</span><span class="p">,</span><span class="w"> </span><span class="m">0.316</span><span class="p">,</span><span class="w">
  </span><span class="m">1.266</span><span class="p">,</span><span class="w"> </span><span class="m">0.19</span><span class="p">,</span><span class="w"> </span><span class="m">-1.519</span><span class="p">,</span><span class="w"> </span><span class="m">0.063</span><span class="p">,</span><span class="w">
  </span><span class="m">0.253</span><span class="p">,</span><span class="w"> </span><span class="m">0.949</span><span class="p">,</span><span class="w"> </span><span class="m">0.127</span><span class="p">,</span><span class="w"> </span><span class="m">-1.329</span><span class="p">),</span><span class="w"> </span><span class="n">nrow</span><span class="o">=</span><span class="m">4</span><span class="p">,</span><span class="w"> </span><span class="n">byrow</span><span class="o">=</span><span class="kc">TRUE</span><span class="p">)</span><span class="w">

</span><span class="n">mutation_matrix</span><span class="w"> </span><span class="o">&lt;-</span><span class="w">  </span><span class="n">Q_matrix</span><span class="w">
</span><span class="n">diag</span><span class="p">(</span><span class="n">mutation_matrix</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0</span><span class="w">
</span><span class="n">mutation_matrix</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">mutation_matrix</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="n">rowSums</span><span class="p">(</span><span class="n">mutation_matrix</span><span class="p">)</span><span class="w">

</span><span class="n">v1</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0.3</span><span class="w">
</span><span class="n">v6</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0.1</span><span class="w">
</span><span class="n">v5</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0.1</span><span class="w">
</span><span class="n">v4</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0.2</span><span class="w">
</span><span class="n">v2</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0.1</span><span class="w">
</span><span class="n">v3</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">0.1</span><span class="w">

</span><span class="c1"># I    II   III    IV</span><span class="w">
</span><span class="c1">#  \  v2 \  /v3   /</span><span class="w">
</span><span class="c1">#   \     \/     /</span><span class="w">
</span><span class="c1">#    \     \    /</span><span class="w">
</span><span class="c1"># v1  \  v5 \  /</span><span class="w">
</span><span class="c1">#      \     \/</span><span class="w">
</span><span class="c1">#       \    / </span><span class="w">
</span><span class="c1">#        \  / v6</span><span class="w">
</span><span class="c1">#         \/</span><span class="w">

</span><span class="n">pi_vector</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="n">A</span><span class="o">=</span><span class="m">0.4</span><span class="p">,</span><span class="w"> </span><span class="n">C</span><span class="o">=</span><span class="m">0.3</span><span class="p">,</span><span class="w"> </span><span class="n">G</span><span class="o">=</span><span class="m">0.2</span><span class="p">,</span><span class="w"> </span><span class="nb">T</span><span class="o">=</span><span class="m">0.1</span><span class="p">)</span><span class="w">
</span><span class="n">cumsum_pi</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">cumsum</span><span class="p">(</span><span class="n">pi_vector</span><span class="p">)</span><span class="w">

</span><span class="p">(</span><span class="n">u</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">runif</span><span class="p">(</span><span class="m">1</span><span class="p">))</span><span class="w">
</span><span class="p">(</span><span class="n">root_nuc_index</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">max</span><span class="p">(</span><span class="n">which</span><span class="p">(</span><span class="n">u</span><span class="o">&gt;</span><span class="n">cumsum_pi</span><span class="p">))</span><span class="m">+1</span><span class="p">)</span><span class="w">

</span><span class="p">(</span><span class="n">lambda</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="o">-</span><span class="n">Q_matrix</span><span class="p">[</span><span class="n">nuc_index</span><span class="p">,</span><span class="w"> </span><span class="n">nuc_index</span><span class="p">])</span><span class="w">

</span><span class="c1"># for v1</span><span class="w">
</span><span class="n">remaining_time</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">v1</span><span class="w">
</span><span class="n">current_index</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">root_nuc_index</span><span class="w">
</span><span class="k">while</span><span class="p">(</span><span class="n">remaining_time</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="m">0</span><span class="p">){</span><span class="w">
	</span><span class="n">t</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="o">-</span><span class="nf">log</span><span class="p">(</span><span class="n">runif</span><span class="p">(</span><span class="m">1</span><span class="p">))</span><span class="o">/</span><span class="n">lambda</span><span class="w">
	</span><span class="n">print</span><span class="p">(</span><span class="n">t</span><span class="p">)</span><span class="w">
	</span><span class="c1"># get the next event</span><span class="w">
	</span><span class="k">if</span><span class="p">(</span><span class="n">t</span><span class="o">&gt;</span><span class="n">remaining_time</span><span class="p">){</span><span class="w">
		</span><span class="n">state_I_index</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">current_index</span><span class="w">
		</span><span class="k">break</span><span class="w">
	</span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="p">{</span><span class="w">
		</span><span class="n">remaining_time</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">remaining_time</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">t</span><span class="w">
		</span><span class="n">current_index</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">sample</span><span class="p">(</span><span class="m">1</span><span class="o">:</span><span class="m">4</span><span class="p">,</span><span class="w"> </span><span class="m">1</span><span class="p">,</span><span class="w"> </span><span class="n">prob</span><span class="o">=</span><span class="n">mutation_matrix</span><span class="p">[</span><span class="n">current_index</span><span class="p">,])</span><span class="w">
	</span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span><span class="n">print</span><span class="p">(</span><span class="nf">c</span><span class="p">(</span><span class="s2">"A"</span><span class="p">,</span><span class="w"> </span><span class="s2">"C"</span><span class="p">,</span><span class="w"> </span><span class="s2">"G"</span><span class="p">,</span><span class="w"> </span><span class="s2">"T"</span><span class="p">)[</span><span class="n">state_I_index</span><span class="p">])</span><span class="w">

</span></code></pre></div></div>

<h2 id="model-selection---david-swofford"><a href="https://molevolworkshop.github.io/faculty/swofford/pdf/swofford_WH2024_modsel.pdf">Model selection - David Swofford</a></h2>

<ul>
  <li>Models don’t need to reflect reality, but they need to be useful (think about using map vs. the real world) .</li>
  <li>He mentioned Felsenstein’s zone and consistency of the ML methods, compared to the Parsimony methods.</li>
  <li><img src="/files/2025_mole_workshop/gtr.png" alt="alt text" /></li>
  <li><a href="https://pubmed.ncbi.nlm.nih.gov/12116942/">Should we use model-based methods for phylogenetic inference when we know that assumptions about among-site rate variation and nucleotide substitution pattern are violated?</a></li>
  <li>BIC penalizes models with more parameters more strongly than AIC. BIC performs well when true model is contained in model set, and among a set of simple-ish models, AIC often selects a more complex model than the truth (indeed, AIC is formally statistically inconsistent); But in phylogenetics, no model is as complex as the truth, and the true model will never be contained in the model set; BIC often chooses models that seem too simple!; One should consider preferring AIC over BIC in phylogenetics?</li>
  <li>Over-partitioning: Looking closely at the estimated parameters, it is possible that one model is sufficient to explain the data.</li>
  <li>You can use AIC to choose the partitioning scheme, e.g., Rob Lanfear’s PartionFinder. If there are too many partitions combinations, you can use a greedy algorithm to find the best partitioning scheme.</li>
</ul>

<h2 id="introduction-to-paup---david-swofford"><a href="http://paup.phylosolutions.com/">Introduction to PAUP* - David Swofford</a></h2>

<ul>
  <li>PAUP* is a software package for phylogenetic analysis using parsimony and other methods (*: likelihood, and distance methods).</li>
  <li><a href="https://molevolworkshop.github.io/faculty/swofford/pdf/modsel-sim-tutorial.html">Exploring Models and Hypothesis Testing using Simulation</a></li>
  <li>He confirmed an interesting point for my question: 1. when we do model selection we will need a initial tree (model), but after model selection if we choose a different model (e.g. based on AIC), the best tree may change; And changing of the best tree may further change the likelihood for model selection; that will result in a “loop”, and he confirmed that yes, we can do it iteratively.</li>
  <li>PAUP* can often achieve a higher likelihood than RAxML, due to fine-tuning of the optimization algorithm from Swofford.</li>
</ul>

<h2 id="iq-tree-introduction"><a href="https://molevolworkshop.github.io/faculty/mcshea/pdf/MOLE2025-IQ-TREE.pdf">IQ-TREE introduction</a></h2>

<ul>
  <li>IQ-TREE3 is now available.</li>
  <li>MixtureFinder is a new tool for partitioning (TODO).</li>
  <li>Q matrix can be customized via Qmaker or NQmaker.</li>
  <li>Concatenation methods for genome-scale data, and partitioned analysis. <code class="language-plaintext highlighter-rouge">-q</code>, <code class="language-plaintext highlighter-rouge">-p</code>, and <code class="language-plaintext highlighter-rouge">-Q</code> are three different models for linking branch lengths.</li>
  <li>PartitionFinder is used for merging similar partitions, to reduce calculation of considering all possible paris, clustering algorithms are used.</li>
  <li>Q mixture model is available (TODO).</li>
  <li>For species tree, gCF and sCF are useful when bootstrap supports reach 100%.</li>
  <li>IQ-TREE can do K-H, S-H, and AU tests, to compare trees.</li>
  <li>Mixture across sites and trees (MAST) model. MAST assumes that there is a collection of trees, where each site of the alignment can have a certain probability of having evolved under each of the trees. Each tree has its own topology and branch lengths, and optionally different substitution rates, different nucleotide/amino acid frequencies, and even different rate heterogeneities across sites.</li>
</ul>

<h2 id="iq-tree-lab"><a href="https://iqtree.github.io/workshop/molevol_tutorial2025">IQ-TREE lab</a></h2>

<ul>
  <li>I like this tutorial, it looks into a real dataset, which historically caused a lot of confusion.</li>
  <li>Where is turtle in the tree? Different papers, different methods led to different results.</li>
  <li>https://doi.org/10.1186/1741-7007-10-65</li>
  <li>https://academic.oup.com/sysbio/article/66/4/517/2950896?login=true</li>
  <li>https://academic.oup.com/mbe/article/42/1/msae264/7931682?login=true</li>
</ul>

<h1 id="day-3">Day 3</h1>

<h2 id="bayesian-inference---paul-lewis">Bayesian inference - Paul Lewis</h2>
<ul>
  <li>Joint probability, conditional probability, marginal/total probability.</li>
  <li>Baye’s rule: the joint probability can be written as the product of the conditional probability and the marginal/total probability: $P(A\vert B)P(B)=P(B\vert A)P(A)$.</li>
  <li>Note that the <strong>likelihood</strong> $L(\theta\vert D)$ is the <strong>probability</strong> of the data given the model $P(D\vert \theta)$.</li>
  <li>Prior can have huge impact on the posterior distribution, consider the HIV screening test example.</li>
  <li>A continous case: 
\(\underbrace{p(\theta \mid D)}_{\text{Posterior probability density}} \;
=
\frac{
  \underbrace{p(D \mid \theta)}_{\text{Likelihood}}
  \;\times\;
  \underbrace{p(\theta)}_{\text{Prior probability density}}
}{
  \underbrace{\displaystyle \int p(D \mid \theta)\,p(\theta)\,\mathrm{d}\theta}_{\text{Marginal probability of the data (evidence)}}
}\)</li>
  <li>A <strong>informative</strong> prior have <strong>low variance</strong> (not necessarily low bias), and a vague prior have high variance.</li>
  <li>The y-axis of a PDF is not a probability, but a probability density.</li>
  <li>When you use posterior ratio, you can ignore the denominator.</li>
  <li>Metropolis algorithm allows us to explore and characterize the posterior probability distribution $p(θ,ϕ∣D)$ without ever needing to compute the intractable denominator $P(D)$.</li>
  <li><a href="https://plewis.github.io/applets/mcmc-robot/">A nice demonstration of the MCMC robot</a>.</li>
  <li>MCMCMC is a “team effort” where different chains with different “perspectives” (temperatures) on the landscape help each other to map out the entire territory effectively. By adjusting the temperatures, we can control how the posterior distribution being flattened or sharpened, which can help us to explore the posterior distribution more efficiently.</li>
</ul>

<h2 id="mcmc-proposals-in-phylogenetics---paul-lewis">MCMC proposals in phylogenetics - Paul Lewis</h2>

<ul>
  <li>The Largest-Simon move:
    <ul>
      <li>Step 1: Pick 3 contiguous edges randomly, defining two subtrees, X and Y.</li>
      <li>Step 2: Shrink or grow selected 3-edge segment by a random amount.</li>
      <li>Step 3: Choose X or Y randomly, then reposition randomly (NNI).</li>
      <li>After NNI, we get a proposed tree, we will decide whether to accept basing on the log-posterior.</li>
      <li>While the strategy of optimizing topology and then branch lengths iteratively is key to finding a single optimal tree in ML, Bayesian MCMC aims to explore the entire landscape of possibilities. A key of the MCMC proposal is to maintain symmetricly, and making sure that the time it stays at the higher posterior region is longer than the time it stays at the lower posterior region.</li>
    </ul>
  </li>
  <li>Remember that MCMC is primarily about deciding whether to accept a randomly proposed move.
    <ul>
      <li>The proposal mechanism itself is generally “blind” to whether the new state will have a higher or lower posterior probability. It just generates a candidate state. The Metropolis-Hastings acceptance step then evaluates the proposed state’s posterior probability relative to the current state’s and decides whether to accept the move. This acceptance step is what guides the chain towards regions of higher posterior probability over time.</li>
    </ul>
  </li>
  <li>95% HPD interval: highest posterior density interval, the region of parameter space that contains 95% of the posterior probability mass.</li>
  <li>Prior distributions:
    <ul>
      <li>Gamma(a, b): appropriate for parameters that range from 0 to infinity, such as branch lengths or rates.</li>
      <li>Lognormal: ranges from 0 to infinity, yields a paticular mean and variance.</li>
      <li>Beta(a,b) distributions are appropriate for proportions, which must lie between 0 and 1 (inclusive).</li>
      <li>A Dirichlet(a,b,c,d) distribution is ideal for nucleotide relative frequencies.</li>
      <li>Discrete uniform can be used for tree topologies.</li>
      <li>Gamma-Dirichlet can be used for branch lengths
        <ul>
          <li>Gamma prior on Total Tree Length (TL), then Dirichlet Prior on Edge Length Proportions.</li>
          <li>It solves the problem of overestimation by default i.i.d. exponential priors (which implicitly enforce an unwanted informative prior) (the prior mean and variance of the total tree length can increase linearly with the number of taxa, sometimes leading to unrealistically long trees (“branch length overestimation”) if the data is sparse or sequences are highly similar, see <a href="chrome-extension://efaidnbmnnnibpcajpcglclefindmkaj/http://abacus.gene.ucl.ac.uk/ziheng/pdf/2012ZhangRannalaYang.SBv61p779.pdf">Ziheng’s</a>):</li>
        </ul>
      </li>
      <li>Yule (pure birth) prior: a prior distribution that can jointly specify both the tree topology and its edge lengths.</li>
    </ul>
  </li>
  <li>Check <strong>distribution explorer</strong>! https://distribution-explorer.github.io/</li>
  <li>Hierarchical models: some parameters of the prior distributions (called hyperparameters) are themselves drawn from another distribution (a hyperprior).</li>
  <li>Empirical Bayes:
    <ul>
      <li>Instead of setting a hyperprior on a parameter of the prior distribution (like the mean of the branch length prior), the Empirical Bayes uses the data (e.g. MLEs) to get an estimate for this parameter.</li>
      <li>This approach uses the data “twice”: once to inform the prior and again in the likelihood calculation. It’s a pragmatic approach but differs from a fully Bayesian hierarchical model where all parameters, including hyperparameters, have prior distributions.</li>
    </ul>
  </li>
  <li>rjMCMC: a type of Markov Chain Monte Carlo algorithm that allows the MCMC chain to jump between models of different dimensions. Useful for:
    <ul>
      <li>Substitution model averaging/selection</li>
      <li>Species delimitation</li>
    </ul>
  </li>
  <li>Marginal likelihood and Bayes factors
    <ul>
      <li>The marginal likelihood is higher in models when they are true.</li>
      <li>Marginal likelihood inherently penalizes models that are overly complex and do not fit the data well, often favoring models that better capture the true underlying process that generated the data.</li>
    </ul>
  </li>
  <li>Dirichlet process (DP) prior
    <ul>
      <li>The Dirichlet Process prior is presented in the context of analyzing data from multiple loci (e.g., genes A, B, C, D) and wanting a prior that can model the situation where:
        <ul>
          <li>Some loci might share the same tree topology (concordance).</li>
          <li>Other loci might have different tree topologies (discordance), possibly due to processes like incomplete lineage sorting.</li>
        </ul>
      </li>
      <li>BUCKy model: Ané et al. 2007. Molecular Biology and Evolution 24:412–426.</li>
      <li>Use Concentration Parameter($\alpha$) to suggest how frequent different loci share the same tree.</li>
      <li>https://plewis.github.io/applets/dpp/</li>
    </ul>
  </li>
</ul>

<h2 id="intro-to-graphical-models-and-revbayes---jeremy-brown">Intro. to Graphical Models and RevBayes - Jeremy Brown</h2>

<ul>
  <li>In Rev language, <code class="language-plaintext highlighter-rouge">z ~ dnBernoulli(0.5)</code> is creating a random variable <code class="language-plaintext highlighter-rouge">z</code> which is fundamentally a stochastic node in the model graph.</li>
  <li><code class="language-plaintext highlighter-rouge">z.clamp(1)</code> then <code class="language-plaintext highlighter-rouge">z.probability()</code> will return the probability of <code class="language-plaintext highlighter-rouge">z</code> being 1.</li>
  <li>Graphical models provide a means of depicting the dependencies among parameters in probabilistic models.
    <ul>
      <li>Squared boxes represent constant nodes: <code class="language-plaintext highlighter-rouge">x &lt;- 2.3</code></li>
      <li>Dashed circles represent deterministic nodes: <code class="language-plaintext highlighter-rouge">y := 2 * x</code></li>
      <li>Solid circles represent stochastic nodes: <code class="language-plaintext highlighter-rouge">z ~ dnExponential(1)</code></li>
      <li>Filled solid circles represent clamped stochastic nodes: <code class="language-plaintext highlighter-rouge">z.clamp(1)</code></li>
      <li>Plates are used to indicate replication (for loop) in the model.</li>
    </ul>
  </li>
  <li>Setting up MCMC in RevBayes
    <ul>
      <li>We use the <code class="language-plaintext highlighter-rouge">=</code> assignment operator for “workspace” variables: <code class="language-plaintext highlighter-rouge">myModel = model(n)</code></li>
      <li>We need to define a proposal distribution (move) for any parameters we are trying to infer. <code class="language-plaintext highlighter-rouge">moves = VectorMoves()</code> <code class="language-plaintext highlighter-rouge">moves.append( mvSlide(p,delta=0.1,weight=1) )</code>.</li>
      <li>We need to keep track of our progress and sampled parameter values. To do that we use monitors. <code class="language-plaintext highlighter-rouge">monitors = VectorMonitors()</code> <code class="language-plaintext highlighter-rouge">monitors.append( mnScreen(printgen=1000,p) )</code> <code class="language-plaintext highlighter-rouge">monitors.append( mnModel(filename=“myMCMC.log", printgen=10) )</code></li>
      <li>Next we create an MCMC object. <code class="language-plaintext highlighter-rouge">myMCMC = mcmc(myModel,moves,monitors)</code>, and start it with <code class="language-plaintext highlighter-rouge">myMCMC.run(10000)</code>.</li>
    </ul>
  </li>
  <li>We tested a simple example for inferring a parameter in binomial process in RevBayes:
    <div class="language-r highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">p</span><span class="w"> </span><span class="o">~</span><span class="w"> </span><span class="n">dnUnif</span><span class="p">(</span><span class="m">0</span><span class="p">,</span><span class="m">1</span><span class="p">)</span><span class="w">
</span><span class="n">n</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">50</span><span class="w">
</span><span class="n">k</span><span class="w"> </span><span class="o">~</span><span class="w"> </span><span class="n">dnBinomial</span><span class="p">(</span><span class="n">n</span><span class="p">,</span><span class="n">p</span><span class="p">)</span><span class="w">
</span><span class="n">k.clamp</span><span class="p">(</span><span class="m">30</span><span class="p">)</span><span class="w">
</span><span class="n">myModel</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">model</span><span class="p">(</span><span class="n">n</span><span class="p">)</span><span class="w">
</span><span class="n">moves</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">VectorMoves</span><span class="p">()</span><span class="w">
</span><span class="n">moves.append</span><span class="p">(</span><span class="w"> </span><span class="n">mvSlide</span><span class="p">(</span><span class="n">p</span><span class="p">,</span><span class="n">delta</span><span class="o">=</span><span class="m">0.1</span><span class="p">,</span><span class="n">weight</span><span class="o">=</span><span class="m">1</span><span class="p">)</span><span class="w"> </span><span class="p">)</span><span class="w">
</span><span class="n">monitors</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">VectorMonitors</span><span class="p">()</span><span class="w">
</span><span class="n">monitors.append</span><span class="p">(</span><span class="w"> </span><span class="n">mnScreen</span><span class="p">(</span><span class="n">printgen</span><span class="o">=</span><span class="m">1000</span><span class="p">,</span><span class="n">p</span><span class="p">)</span><span class="w"> </span><span class="p">)</span><span class="w">
</span><span class="n">monitors.append</span><span class="p">(</span><span class="w"> </span><span class="n">mnModel</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s2">"myMCMC.log"</span><span class="p">,</span><span class="w"> </span><span class="n">printgen</span><span class="o">=</span><span class="m">100</span><span class="p">)</span><span class="w"> </span><span class="p">)</span><span class="w">
</span><span class="n">myMCMC</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">mcmc</span><span class="p">(</span><span class="n">myModel</span><span class="p">,</span><span class="n">moves</span><span class="p">,</span><span class="n">monitors</span><span class="p">)</span><span class="w">
</span><span class="n">myMCMC.run</span><span class="p">(</span><span class="m">2000000</span><span class="p">)</span><span class="w">
</span><span class="n">quit</span><span class="p">()</span><span class="w">
</span></code></pre></div>    </div>
    <p>Run it by <code class="language-plaintext highlighter-rouge">rb myMCMC.rb</code>.</p>
  </li>
  <li>It is nice that he demonstrated the Gamma-Dirichlet model in RevBayes.</li>
  <li>There are example Rev scripts for JC, HKY, GTR, GTR+G+I available.</li>
  <li><img src="/files/2025_mole_workshop/Gamme_dirchlet.png" alt="alt text" /></li>
  <li>The weights in moves determine the probability of different moves being selected.</li>
  <li>An MCMC iteration isn’t just one move; it’s typically a series of these individual parameter update attempts (each involving a proposal, likelihood calculation, and an accept/reject decision) for many, if not all, of the parameters in the model.</li>
  <li>Below is an example script for the GTR+G+I model:</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">################################################################################
#
# RevBayes Example: Bayesian inference of phylogeny using a GTR+Gamma+Inv
#                   substitution model on a single gene.
#
# authors: Sebastian Hoehna, Michael Landis, and Tracy A. Heath
#
################################################################################
</span>

<span class="c1">### Read in sequence data for the gene
</span><span class="n">data</span> <span class="o">=</span> <span class="n">readDiscreteCharacterData</span><span class="p">(</span><span class="s">"data/primates_and_galeopterus_cytb.nex"</span><span class="p">)</span>

<span class="c1"># Get some useful variables from the data. We need these later on.
</span><span class="n">num_taxa</span> <span class="o">&lt;-</span> <span class="n">data</span><span class="p">.</span><span class="n">ntaxa</span><span class="p">()</span>
<span class="n">num_branches</span> <span class="o">&lt;-</span> <span class="mi">2</span> <span class="o">*</span> <span class="n">num_taxa</span> <span class="o">-</span> <span class="mi">3</span>
<span class="n">taxa</span> <span class="o">&lt;-</span> <span class="n">data</span><span class="p">.</span><span class="n">taxa</span><span class="p">()</span>


<span class="n">moves</span>    <span class="o">=</span> <span class="n">VectorMoves</span><span class="p">()</span>
<span class="n">monitors</span> <span class="o">=</span> <span class="n">VectorMonitors</span><span class="p">()</span>


<span class="c1">######################
# Substitution Model #
######################
</span>
<span class="c1"># specify the stationary frequency parameters
</span><span class="n">pi_prior</span> <span class="o">&lt;-</span> <span class="n">v</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span> 
<span class="n">pi</span> <span class="o">~</span> <span class="n">dnDirichlet</span><span class="p">(</span><span class="n">pi_prior</span><span class="p">)</span>
<span class="n">moves</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mvBetaSimplex</span><span class="p">(</span><span class="n">pi</span><span class="p">,</span> <span class="n">weight</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span> <span class="p">)</span>
<span class="n">moves</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mvDirichletSimplex</span><span class="p">(</span><span class="n">pi</span><span class="p">,</span> <span class="n">weight</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="p">)</span>


<span class="c1"># specify the exchangeability rate parameters
</span><span class="n">er_prior</span> <span class="o">&lt;-</span> <span class="n">v</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span>
<span class="n">er</span> <span class="o">~</span> <span class="n">dnDirichlet</span><span class="p">(</span><span class="n">er_prior</span><span class="p">)</span>
<span class="n">moves</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mvBetaSimplex</span><span class="p">(</span><span class="n">er</span><span class="p">,</span> <span class="n">weight</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="p">)</span>
<span class="n">moves</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mvDirichletSimplex</span><span class="p">(</span><span class="n">er</span><span class="p">,</span> <span class="n">weight</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="p">)</span>


<span class="c1"># create a deterministic variable for the rate matrix, GTR
</span><span class="n">Q</span> <span class="p">:</span><span class="o">=</span> <span class="n">fnGTR</span><span class="p">(</span><span class="n">er</span><span class="p">,</span><span class="n">pi</span><span class="p">)</span> 


<span class="c1">#############################
# Among Site Rate Variation #
#############################
</span>
<span class="c1"># among site rate variation, +Gamma4
</span><span class="n">alpha</span> <span class="o">~</span> <span class="n">dnUniform</span><span class="p">(</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mi">10</span> <span class="p">)</span>
<span class="n">sr</span> <span class="p">:</span><span class="o">=</span> <span class="n">fnDiscretizeGamma</span><span class="p">(</span> <span class="n">alpha</span><span class="p">,</span> <span class="n">alpha</span><span class="p">,</span> <span class="mi">4</span> <span class="p">)</span>
<span class="n">moves</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mvScale</span><span class="p">(</span><span class="n">alpha</span><span class="p">,</span> <span class="n">weight</span><span class="o">=</span><span class="mf">2.0</span><span class="p">)</span> <span class="p">)</span>


<span class="c1"># the probability of a site being invariable, +I
</span><span class="n">p_inv</span> <span class="o">~</span> <span class="n">dnBeta</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span>
<span class="n">moves</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mvSlide</span><span class="p">(</span><span class="n">p_inv</span><span class="p">)</span> <span class="p">)</span>

<span class="c1">##############
# Tree model #
##############
</span>
<span class="n">out_group</span> <span class="o">=</span> <span class="n">clade</span><span class="p">(</span><span class="s">"Galeopterus_variegatus"</span><span class="p">)</span>
<span class="c1"># Prior distribution on the tree topology
</span><span class="n">topology</span> <span class="o">~</span> <span class="n">dnUniformTopology</span><span class="p">(</span><span class="n">taxa</span><span class="p">,</span> <span class="n">outgroup</span><span class="o">=</span><span class="n">out_group</span><span class="p">)</span>
<span class="n">moves</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mvNNI</span><span class="p">(</span><span class="n">topology</span><span class="p">,</span> <span class="n">weight</span><span class="o">=</span><span class="n">num_taxa</span><span class="o">/</span><span class="mf">2.0</span><span class="p">)</span> <span class="p">)</span>
<span class="n">moves</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mvSPR</span><span class="p">(</span><span class="n">topology</span><span class="p">,</span> <span class="n">weight</span><span class="o">=</span><span class="n">num_taxa</span><span class="o">/</span><span class="mf">10.0</span><span class="p">)</span> <span class="p">)</span>

<span class="c1"># Branch length prior
</span><span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="ow">in</span> <span class="mi">1</span><span class="p">:</span><span class="n">num_branches</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">bl</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">~</span> <span class="n">dnExponential</span><span class="p">(</span><span class="mf">10.0</span><span class="p">)</span>
    <span class="n">moves</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mvScale</span><span class="p">(</span><span class="n">bl</span><span class="p">[</span><span class="n">i</span><span class="p">])</span> <span class="p">)</span>
<span class="p">}</span>

<span class="n">TL</span> <span class="p">:</span><span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">bl</span><span class="p">)</span>

<span class="n">psi</span> <span class="p">:</span><span class="o">=</span> <span class="n">treeAssembly</span><span class="p">(</span><span class="n">topology</span><span class="p">,</span> <span class="n">bl</span><span class="p">)</span>




<span class="c1">###################
# PhyloCTMC Model #
###################
</span>
<span class="c1"># the sequence evolution model
</span><span class="n">seq</span> <span class="o">~</span> <span class="n">dnPhyloCTMC</span><span class="p">(</span><span class="n">tree</span><span class="o">=</span><span class="n">psi</span><span class="p">,</span> <span class="n">Q</span><span class="o">=</span><span class="n">Q</span><span class="p">,</span> <span class="n">siteRates</span><span class="o">=</span><span class="n">sr</span><span class="p">,</span> <span class="nb">type</span> <span class="o">=</span> <span class="s">"DNA"</span><span class="p">)</span>
<span class="n">seq</span> <span class="o">~</span> <span class="n">dnPhyloCTMC</span><span class="p">(</span><span class="n">tree</span><span class="o">=</span><span class="n">psi</span><span class="p">,</span> <span class="n">Q</span><span class="o">=</span><span class="n">Q</span><span class="p">,</span> <span class="n">siteRates</span><span class="o">=</span><span class="n">sr</span><span class="p">,</span> <span class="n">pInv</span><span class="o">=</span><span class="n">p_inv</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">"DNA"</span><span class="p">)</span>

<span class="c1"># attach the data
</span><span class="n">seq</span><span class="p">.</span><span class="n">clamp</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>


<span class="c1">############
# Analysis #
############
</span>
<span class="n">mymodel</span> <span class="o">=</span> <span class="n">model</span><span class="p">(</span><span class="n">psi</span><span class="p">)</span>

<span class="c1"># add monitors
</span><span class="n">monitors</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mnScreen</span><span class="p">(</span><span class="n">printgen</span><span class="o">=</span><span class="mi">100</span><span class="p">,</span> <span class="n">alpha</span><span class="p">,</span> <span class="n">p_inv</span><span class="p">,</span> <span class="n">TL</span><span class="p">)</span> <span class="p">)</span>
<span class="n">monitors</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mnFile</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s">"output/primates_cytb_GTRGI.trees"</span><span class="p">,</span> <span class="n">printgen</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span> <span class="n">psi</span><span class="p">)</span> <span class="p">)</span>
<span class="n">monitors</span><span class="p">.</span><span class="n">append</span><span class="p">(</span> <span class="n">mnModel</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s">"output/primates_cytb_GTRGI.log"</span><span class="p">,</span> <span class="n">printgen</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span> <span class="p">)</span>

<span class="c1"># run the analysis
</span><span class="n">mymcmc</span> <span class="o">=</span> <span class="n">mcmc</span><span class="p">(</span><span class="n">mymodel</span><span class="p">,</span> <span class="n">moves</span><span class="p">,</span> <span class="n">monitors</span><span class="p">)</span>
<span class="n">mymcmc</span><span class="p">.</span><span class="n">run</span><span class="p">(</span><span class="n">generations</span><span class="o">=</span><span class="mi">20000</span><span class="p">)</span>


<span class="c1"># summarize output
</span><span class="n">treetrace</span> <span class="o">=</span> <span class="n">readTreeTrace</span><span class="p">(</span><span class="s">"output/primates_cytb_GTRGI.trees"</span><span class="p">,</span> <span class="n">treetype</span><span class="o">=</span><span class="s">"non-clock"</span><span class="p">)</span>
<span class="c1"># and then get the MAP tree
</span><span class="n">map_tree</span> <span class="o">=</span> <span class="n">mapTree</span><span class="p">(</span><span class="n">treetrace</span><span class="p">,</span><span class="s">"output/primates_cytb_GTRGI_MAP.tre"</span><span class="p">)</span>


<span class="c1"># you may want to quit RevBayes now
</span><span class="n">q</span><span class="p">()</span>
</code></pre></div></div>

<ul>
  <li>https://revbayes.github.io/tutorials/ctmc/</li>
</ul>

<h2 id="bayesian-divergence-time-estimation---tracy-heath">Bayesian Divergence time estimation - Tracy Heath</h2>

<ul>
  <li>The global molecular clock - Assume that the rate of evolutionary change is constant over time, for all lineages.</li>
  <li>However, rates of evolution vary across lineages and over time.</li>
  <li>Sequence data alone provide branch lengths, in the unit of expected substitutions per site. The rate and time are not identifiable by sequence data alone.</li>
  <li>Tree-time priors (e.g., Yule, Birth-Death) for molecular phylogenies are only informative on a relative time scale.</li>
  <li>$f(R, A, \Psi, \theta_R, \theta_A, \theta_s \vert  D) = \frac{f(D \vert  R, A, \theta_s) f(R \vert  \theta_R) f(A, \Psi \vert  \theta_A) f(\theta_s)}{f(D)}$
    <ul>
      <li>The parameters involved are:
        <ul>
          <li><strong>$R$</strong>: A vector representing the evolutionary <strong>rates on each branch</strong> of the tree.</li>
          <li><strong>$A$</strong>: A vector representing the <strong>ages of the internal nodes</strong> in the tree (divergence times).</li>
          <li><strong>$\Psi$ (Psi)</strong>: The <strong>tree topology</strong> (the branching pattern).</li>
          <li><strong>$\theta_R$</strong>: Hyperparameters for the model of how branch rates ($R$) evolve or are distributed (e.g., parameters of a relaxed clock model).</li>
          <li><strong>$\theta_A$</strong>: Hyperparameters for the tree prior, which models how topologies ($\Psi$) and node ages ($A$) arise (e.g., parameters of a birth-death process like speciation/extinction rates).</li>
          <li><strong>$\theta_s$</strong>: Parameters of the substitution model describing how sequences change (e.g., GTR rates, base frequencies, gamma shape parameter for among-site rate variation).</li>
          <li><strong>$D$</strong>: The observed <strong>character data</strong> (e.g., DNA or protein sequence alignment).</li>
        </ul>
      </li>
      <li><strong>$f(D \vert  R, A, \theta_s)$ - The Likelihood:</strong>
        <ul>
          <li>This is the probability (or probability density) of observing the sequence data $D$, given a specific tree (defined by topology $\Psi$ and node ages $A$, which together yield branch durations), the rates of evolution along each branch ($R$), and the substitution model parameters ($\theta_s$).</li>
          <li>Branch lengths in units of expected substitutions per site (which the likelihood calculation uses) are obtained by multiplying the rate on a branch ($R_i$) by the duration of that branch (derived from $A$ and $\Psi$).</li>
        </ul>
      </li>
      <li><strong>$f(R \vert  \theta_R)$ - The Prior on Branch Rates:</strong></li>
      <li><strong>$f(A, \Psi \vert  \theta_A)$ - The Joint Prior on Node Ages and Topology (The “Tree Prior”):</strong></li>
      <li><strong>$f(\theta_s)$ - The Prior on Substitution Model Parameters:</strong></li>
    </ul>
  </li>
  <li><strong>Independent/Uncorrelated Rates</strong>: Lineage-specific rates are uncorrelated when the rate assigned to each branch is <strong>independently drawn</strong> from an underlying distribution (you can do it in a for loop for every <strong>branch</strong>).</li>
  <li><strong>Autocorrelated Rates</strong>: closely related lineages have similar rates. The rate at a <strong>node</strong> is drawn from a distribution with a mean equal to the parent rate.
    <ul>
      <li>Note that the $\mu$ in log-normal distribution is the <strong>mean</strong> of the log-transformed rates, <strong>not</strong> the mean of the rates themselves.</li>
      <li>The correlation between parameters in this model makes it hard for MCMC to explore the parameter space.</li>
    </ul>
  </li>
  <li>Tree priors:
    <ul>
      <li>The Birth-Death Process: $\lambda$ is the speciation rate, $\mu$ is the extinction rate.</li>
      <li>The Yule Process: $\lambda$ is the speciation rate, $\mu$ is 0.</li>
      <li>We also have the origin time $\phi$, and the sampling fraction $\rho$.</li>
    </ul>
  </li>
  <li>Conceptual debate in fossil calibration: Calibrations as Priors vs. Calibrations as Data (Likelihoods):
    <ul>
      <li><strong>Node Calibrations as Priors</strong>: One approach is to directly treat these calibration densities as defining the prior distribution for the age of the calibrated node(s). The overall tree prior (e.g., from a birth-death process) is then conditioned on these specified node ages
        <ul>
          <li>Commonly, a <strong>parametric probability distribution</strong> (e.g., Uniform, Lognormal, Gamma, Exponential) is placed on the age of an internal node. This distribution is typically offset by the age of the oldest fossil confidently assigned to that clade, effectively setting a minimum age for that node.</li>
          <li>While minimum age bounds from fossils are common, reliable maximum age bounds are often difficult to establish.</li>
          <li>Problems with multiple calibrations as priors: Rannala (2016) showed this conditional prior approach can lead to “counterintuitive topologically inconsistent realized priors” (the effective prior on tree shapes and other node ages can be strange). Dos Reis (2016) also demonstrated that this can be computationally intractable with many calibrations.</li>
        </ul>
      </li>
      <li><strong>Node Calibrations as Likelihoods (Fossil Data Likelihood)</strong>: An alternative view is to treat the fossil information (e.g., fossil age $F$) as data. The probability of observing this fossil data is then expressed as a likelihood function conditional on the age of the relevant node ($t$) in the tree, $f(F\vert t,parameters)$. This approach is argued to be conceptually simpler and more easily manageable with multiple fossil calibrations.</li>
      <li><strong>Common Misinterpretation</strong>: Even if the mathematical implementation of a calibration effectively treats the fossil as data (i.e., a likelihood component), it is often misinterpreted by users as directly setting the prior distribution for the node’s age. The mathematical form for $f(t\vert F)$ (a prior on node age $t$ given fossil $F$) and $f(F\vert t)$ (likelihood of fossil $F$ given node age $t$) can be identical for certain distributions (like a shifted exponential), contributing to this confusion.</li>
    </ul>
  </li>
  <li>Improving Fossil Calibration:
    <ul>
      <li>The goal is to use all available fossil information in a more cohesive way.</li>
      <li>This is achieved by recognizing that fossils are not just isolated time points but are products of the same underlying diversification (speciation, extinction, and fossilization) process that generated the extant taxa.</li>
    </ul>
  </li>
  <li>The Fossilized Birth-Death (FBD) Process (by Stadler 2010)
    <ul>
      <li>The FBD process is a generative model that describes the birth of new lineages (speciation, rate $λ$), the death of lineages (extinction, rate $μ$), and the recovery of fossils (fossil sampling or recovery rate, $ψ$) through time.</li>
      <li>It allows all relevant fossils to contribute to the analysis, not just those used to set minimum bounds on specific nodes.</li>
      <li>It explicitly models the processes of speciation, extinction, and fossilization.</li>
    </ul>
  </li>
  <li><a href="https://www.cambridge.org/core/journals/paleobiology/article/from-fossils-to-phylogenies-exploring-the-integration-of-paleontological-data-into-bayesian-phylogenetic-inference/BF7DB160A01BDD5183252BFB89A9699F">From fossils to phylogenies: exploring the integration of paleontological data into Bayesian phylogenetic inference</a></li>
  <li>FBD was used in a detailed penguin phylogeny with geological time, highlighting known fossils, significant paleoclimatic events, and the estimated divergence times of crown penguins, illustrating the rich evolutionary narrative that can be reconstructed (Thomas et al. Proc. Roy Soc. B 2020; Cole et al, Nature Comm. 2022; .Ksepka et al. J. Paleontology 2023)</li>
</ul>

<h2 id="tutorial-estimating-a-time-calibrated-phylogeny-of-fossil-and-extant-taxa-using-morphological-data">Tutorial: Estimating a Time-Calibrated Phylogeny of Fossil and Extant Taxa using Morphological Data</h2>

<ul>
  <li>https://revbayes.github.io/tutorials/fbd_simple/</li>
</ul>

<h1 id="day-4">Day 4</h1>

<h2 id="deep-phylogenomics---laura-eme">Deep phylogenomics - Laura Eme</h2>

<ul>
  <li>Protein models of evolution
    <ul>
      <li>Empirical models
        <ul>
          <li>Based on alignment data.</li>
          <li>Typically 20*20 matrix assuming stationarity and reversibility.</li>
          <li>Dayhoff, JTT, WAG, LG etc.</li>
          <li>One can also use AIC/BIC based methods (e.g. ModelFinder) to compare empirical models.</li>
          <li>FreeRate model (+R): more parameters than (+G). Does not follow a parametric distribution. Not all categories will have the same number of sites.</li>
          <li>Model misspecification (single-matrix models) often means systematic error (LBA).</li>
        </ul>
      </li>
      <li>Fully parameterized time-reversible model
        <ul>
          <li>GTR: estiamte 189 rate parameters from your data.</li>
        </ul>
      </li>
      <li>Mixture model
        <ul>
          <li>As reflected in Wang et al. (2008) BMC Evolutionary Biology 8: 331, the simulated data does not match the real data well, suggesting that JTT+F+G is not enough.</li>
          <li>Standard protein substitution models: single Q matrix</li>
          <li>Mixture models: combine several amino-acid replacement matrices</li>
          <li>Can mixtured among sites, or among branches</li>
          <li>Standard LG+gamma: Q matrix is the same.</li>
          <li>LG4M: each gamma rate category gets its own Q matrix</li>
          <li>LG4X: each rate category gets its own Q matrix BUT rates and weights are left out of the gamma distribution assumption</li>
          <li>CAT: Infinite mixture model, Bayesian framework only.</li>
          <li>C10, C20, …, C60: approximations of the CAT model for ML.</li>
          <li>Complex mixture models are often hard to compute and fail to converge (by multiple chains). <strong>PMSF approximation</strong> can be useful (available in IQtree).</li>
          <li>Heterotachy: changing rates of evolution at sites in different parts of the tree .
            <ul>
              <li>Covarion models</li>
              <li>Rate-shift models</li>
              <li>Mixture of branch-length models (GHOST in IQtree)</li>
            </ul>
          </li>
          <li>Functional shifts (functional divergence)
            <ul>
              <li>FD sites violate homogeneity assumption and artefactually increase branch-length (LBA).</li>
              <li>Try the FunDi mixture model.</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Reconstructing ‘deep’ phylogenies (large-scale species trees)
    <ul>
      <li>Single gene trees are not enough to resolve ‘ancient relationships’
        <ul>
          <li>“Ancient” signal erased by more recent substitutions</li>
        </ul>
      </li>
      <li>Improving phylogenetic signal, one way is to use multiple genes.
        <ul>
          <li>Supermatrices: combining genes together</li>
          <li>Supertrees</li>
          <li>Reconciliation methods</li>
        </ul>
      </li>
      <li>Minimazing potential artefacts
        <ul>
          <li>Cross validation was used to test two different topologies within Obazoa are supported by different phylogenetic models: The fitted parameter values from traning set are then used to compute the likelihood of the test set: how well the test set is ‘predicted’ by the model?</li>
          <li>Try to eliminate ‘noisiest’ data
            <ul>
              <li>Fast-evolving site removal: Check <em>Brown et al. 2013 PRSB</em>, they gradually <strong>remove a proportion of the fastest evolving sites</strong> (determined by the $\Gamma$ model), then they observe the topology changes, suggesting misspecified simple model (e.g. LG) gave problematic topology.</li>
              <li>Fast-evolving gene removal</li>
              <li>Fast-evolving taxon removal</li>
              <li>Recoding</li>
            </ul>
          </li>
          <li>GFmix model: tackle compositional bias in a protein model.</li>
          <li>Eme is an expert on deep evolution (a LOT of Nature papers). How does LECA looks like? How do Eukaryotes relate to Asgards?</li>
          <li>Recoding: instead of studying all 20 aa, recode them to e.g. 4 category.</li>
          <li>Testing for long branch attraction: you can test different models for whether they yield even propotion of differnt topologies under simulation.</li>
          <li>TODO: Check the reserach context on viruses evolution, viruses tree of life, the narrow down to flu related or coronaviruses.</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h2 id="the-coalescent-inference-using-trees-of-individuals---peter-beerli">The Coalescent: Inference using trees of ‘individuals’ - Peter Beerli</h2>

<ul>
  <li>Linking population genetics (population) and phylogenetics (trees)
    <ul>
      <li>Wright-Fisher model
        <ul>
          <li>The number of generations for two individuals to coalesce it a Geometric distribution with expected value $2N$.</li>
        </ul>
      </li>
      <li>Canning mdoel</li>
      <li>Moran model</li>
      <li>Kingman’s coalescent
        <ul>
          <li>When the population size (N) is large, the discrete-generation Wright-Fisher process can be approximated by a continuous-time process.</li>
          <li><strong>Scaled Coalescence Rate ($\lambda_k$) for $k$ lineages:</strong> When time is scaled appropriately (e.g., in units of $2N$ generations for diploids, or by $\Theta=4N\mu$), the rate at which <em>any</em> pair of $k$ lineages coalesces is:
$\lambda_k = \binom{k}{2} \frac{1}{2N} = \frac{k(k-1)}{4N}$ (the other $k−2$ lineages continue into the past without coalescing in that same infinitesimal time step or generation where the first coalescence occurred.)</li>
          <li>Exponential waiting time with rate $\lambda_k$ for the next coalescent event.</li>
          <li><strong>Probability of a Specific Genealogy ($G$) given population size $N$:</strong> Assuming each coalescence event is independent, the probability of a given genealogy (a specific tree topology and set of coalescent times $u_j$ for each interval where there were $k_j$ lineages) is the product of the probabilities of each interval:
\(P(G\vert N) = \prod_{j \text{ (intervals)}} e^{-u_j \frac{k_j(k_j-1)}{4N}} \frac{k_j(k_j-1)}{4N} \times \frac{2}{k_j(k_j-1)}\)
This simplifies to:
\(P(G\vert N, \text{sample size } n) = \prod_{k=2}^{n} \exp\left(-u_k \frac{k(k-1)}{4N}\right) \frac{2}{4N}\)
where $u_k$ is the duration of the interval when there were $k$ lineages.</li>
        </ul>
      </li>
      <li>The time to the most recent common ancestor (TMRCA) has a large variance (He demonstrated this with a simulation, even under a same population size, tree shapes can be very different).</li>
      <li>The sample size should be much smaller than the population size</li>
    </ul>
  </li>
  <li>A simulator: https://phyleauxsim.github.io/coalescent/</li>
  <li>Genetic data and the coalescent
    <ul>
      <li>Mutation introduces new alleles into a population at rate $µ$.</li>
      <li>$4N\mu$ can be estimated genetic variability $S$ (Summary statistics).</li>
      <li>Using genetic variability alone therefore does not allow to disentangle $N$ and $µ$. With multiple dated samples and known generation time we can estimate N and $µ$ independently.</li>
      <li><strong>Watterson’s Estimator ($\theta_W$):</strong> Uses the number of variable sites ($S$) in a sample of $n$ individuals from a single locus: $\theta_W = \frac{S}{\sum_{i=1}^{n-1} \frac{1}{i}}$ This estimator uses a mutation rate <em>per locus</em></li>
    </ul>
  </li>
  <li>Bayesian Inference using the Coalescent
    <ul>
      <li>Goal: Calculate $p(\text{Model Parameters } \vert  \text{Data } D)$, e.g., $p(\Theta \vert  D)$.</li>
      <li>Uses Bayes’ rule: $p(\Theta \vert  D) = \frac{p(\Theta) p(D \vert  \Theta)}{p(D)}$.</li>
      <li><strong>Felsenstein-like Equation for Likelihood (integrating over genealogies):</strong> The likelihood of the parameters $\Theta$ given the data $D$ involves integrating over all possible genealogies $G$:
  $p(D \vert  \Theta) = \int_G p(G \vert  \Theta) p(D \vert  G) dG$
  where:
        <ul>
          <li>$p(G \vert  \Theta)$: Probability density of a genealogy $G$ given parameters $\Theta$ (from the coalescent model).</li>
          <li>$p(D \vert  G)$: Probability density of the data $D$ given genealogy $G$ (from the mutation model, this is the standard phylogenetic tree likelihood).</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h2 id="extensions-of-the-basic-coalescent---peter-beerli">Extensions of the basic coalescent - Peter Beerli</h2>

<h3 id="recap">Recap</h3>

<ul>
  <li>The probability of a specific genealogy $G$ (topology and coalescent times $u_j$ for intervals with $k_j$ lineages) given the mutation-scaled effective population size $\Theta = 4N_e\mu$ (for diploids) is:
  $P(G\vert \Theta) = \prod_{j \text{ (intervals)}} e^{-u_j \frac{k_j(k_j-1)}{\Theta}} \frac{2}{\Theta}$
    <ul>
      <li>This formula involves:
        <ul>
          <li>Calculating the probability of waiting time $u_j$ until a coalescence: $e^{-u_j \frac{k_j(k_j-1)}{\Theta}}$ (survival probability).</li>
          <li>Calculating the probability density of the specific coalescence event happening: $\frac{k_j(k_j-1)}{\Theta}$ (rate of coalescence for $k_j$ lineages) multiplied by the probability of a specific pair coalescing (which is $2/(k_j(k_j-1))$, simplifying the rate term for the interval to $2/\Theta$).</li>
        </ul>
      </li>
      <li>This allows calculating the probability density of a genealogy given $\Theta$.</li>
    </ul>
  </li>
</ul>

<h3 id="extensions-of-the-coalescent">Extensions of the Coalescent</h3>

<ul>
  <li>The basic coalescent assumes a single, constant-sized, randomly mating population. Extensions address more realistic scenarios:</li>
  <li><strong>Exponential Growth Model:</strong> If population size changes exponentially, $N(t) = N_0 e^{-gt}$ (where $N_0$ is current size, $t$ is time into the past, and $g$ is growth rate towards the present). The probability of a genealogy becomes:
$P(G\vert \Theta_0, g) = \prod_{j \text{ (intervals)}} e^{-(t_j - t_{j-1}) \frac{k(k-1)}{\Theta_0 e^{-gt_j}}} \frac{2}{\Theta_0 e^{-gt_j}}$ (Here, $t_j$ is the time at the end of the interval with $k$ lineages, and $\Theta_0$ is the current mutation-scaled population size).</li>
  <li><strong>Skyline Plots (Random Fluctuations):</strong> Methods like Bayesian Skyline (BEAST), Skyride, Skyfish (BEAST, RevBayes) can estimate population size changes over time.</li>
  <li><strong>Bottlenecks:</strong> Estimating bottlenecks depends on their severity, duration, and the amount of data (sample size, number of loci), it is HARD.</li>
  <li><strong>Migration Among Populations (Structured Coalescent):</strong>
    <ul>
      <li>For multiple populations, the overall rate of events (coalescence or migration) changes. For two populations (1 and 2) with $k_1$ lineages in pop 1 and $k_2$ in pop 2, the total rate of any event is: 
\(\text{Total Rate} = \underbrace{\frac{k_1(k_1-1)}{\Theta_1}}_{\text{coalescence in pop1}} + \underbrace{\frac{k_2(k_2-1)}{\Theta_2}}_{\text{coalescence in pop2}} + \underbrace{k_1 M_{21}}_{\text{migration 1 } \leftarrow \text{ 2}} + \underbrace{k_2 M_{12}}_{\text{migration 2 } \leftarrow \text{ 1}}\)
where $M_{ij}$ is the scaled migration rate from population $j$ to $i$ (e.g., $M_{21} = 4N_1m_{21}$ if $\Theta_1=4N_1\mu$).</li>
    </ul>
  </li>
  <li><strong>Population Splitting (Divergence Models):</strong>
    <ul>
      <li>Used to estimate divergence times ($\tau$), ancestral population sizes, and migration rates between diverging populations (e.g., Isolation with Migration - IM models).</li>
      <li>Tracing lineages backward: a lineage in population A today had an ancestor in an ancestral population B. The timing of this “population label switch” can be modeled using hazard functions (e.g., based on a Normal distribution for the divergence time).</li>
      <li>The resulting genealogies incorporate coalescence, migration, and population splitting events.</li>
      <li>More loci generally improve the precision of divergence time estimates.</li>
    </ul>
  </li>
</ul>

<h3 id="robustness-and-assumptions-of-the-coalescent">Robustness and Assumptions of the Coalescent</h3>

<ul>
  <li><strong>Sample Size ($n \ll N_e$):</strong> Kingman’s n-coalescent assumes at most two lineages merge per generation (no multiple mergers). This is a good approximation if $n \ll N_e$ (e.g., $n &lt; \sqrt{4N_e}$ for diploids). It’s fairly robust even if this is moderately violated, as multiple mergers become very rare with large $N_e$.</li>
  <li><strong>TMRCA Estimation:</strong> The Time to Most Recent Common Ancestor (TMRCA) is often robust to sample size; even small samples can yield similar TMRCA estimates to large samples. Adding more independent loci is often more beneficial than adding more individuals per locus beyond a certain point (e.g., &gt;8 individuals ).</li>
  <li><strong>Long-Term Averages:</strong> Coalescent parameter estimates represent averages over long evolutionary timescales.</li>
  <li><strong>Recombination:</strong> Standard coalescent typically assumes no intra-locus recombination. Recombination means different segments of a locus can have different genealogical histories. Ignoring recombination when it’s present can bias estimates of $\Theta$ (often upwards) and migration rates (often downwards).</li>
</ul>

<h3 id="mutation-models-and-genetic-data-in-coalescent-inference">Mutation Models and Genetic Data in Coalescent Inference</h3>

<ul>
  <li><strong>Confounding $N_e$ and $\mu$:</strong> Genetic diversity (e.g., number of segregating sites $S$) is primarily a function of the product $N_e\mu$ (scaled as $\Theta$). It’s hard to estimate $N_e$ and $\mu$ separately from genetic data alone without external information (like dated samples or known mutation rates per generation).</li>
  <li><strong>Methods of Inference:</strong>
    <ul>
      <li><strong>Watterson’s Estimator ($\theta_W$):</strong> $\theta_W = \frac{S}{\sum_{i=1}^{n-1} (1/i)}$ (uses mutation rate per locus).</li>
      <li><strong>Bayesian Inference:</strong> Calculates $p(\Theta \vert  D) \propto p(\Theta) \int_G p(G\vert \Theta)p(D\vert G)dG$. The integral sums/averages over all possible genealogies ($G$) and is usually computed via MCMC.</li>
    </ul>
  </li>
  <li><strong>Types of Mutation Models for $p(D\vert G)$:</strong>
    <ul>
      <li><strong>Infinite Sites Model:</strong> Assumes every new mutation occurs at a brand new site (no multiple hits). Leads to SNP data (bi-allelic markers). Often used with Site Frequency Spectra (SFS).</li>
      <li><strong>Finite Sites Models (e.g., JC69, HKY, GTR):</strong> Allow multiple hits, back mutations. Used for aligned DNA sequences.</li>
    </ul>
  </li>
  <li><strong>Site Frequency Spectrum (SFS):</strong>
    <ul>
      <li>The distribution of allele frequencies in a sample. Many recent population genomic methods use the SFS, often assuming an infinite sites model.</li>
      <li><strong>Challenges with SFS:</strong>
        <ul>
          <li>Accommodating real data to the infinite sites model (defining ancestral alleles, handling multi-allelic sites, errors).</li>
          <li>SNP ascertainment bias: How SNPs are discovered can bias the SFS if not corrected.</li>
          <li>May be problematic for species with high diversity / large $N_e$ where the infinite sites assumption is often violated (e.g., many tri-allelic sites observed in <em>Anopheles</em>).</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="https://academic.oup.com/g3journal/article/12/4/jkac040/6528849?login=true">Population divergence time estimation using individual lineage label switching</a></li>
  <li>A potential mistake in <a href="https://pubmed.ncbi.nlm.nih.gov/29186111/">The Anopheles gambiae 1000 Genomes Consortium: Genetic diversity of the African malaria vector Anopheles gambiae. Nature, 552(7683):96–100, Dec 2017</a>, they report very high rate for positions with $&gt;2$ mutations.</li>
</ul>

<h2 id="genomic-data-for-evolutionary-inference---emily-jane-mctavish">Genomic data for evolutionary inference - Emily Jane McTavish</h2>

<p>The talk emphasizes that while the quantity of sequence data is rapidly increasing, outstripping analytical capabilities (a point made by Jeff Thorne as early as 1991), many choices and potential pitfalls exist:</p>

<h3 id="orthology-vs-paralogy">Orthology vs. Paralogy</h3>

<ul>
  <li>Distinguishing orthologs (genes diverged by speciation) from paralogs (genes diverged by duplication) is critical.</li>
  <li>Including unrecognized paralogs can lead to incorrect phylogenetic inferences, as demonstrated by an example of turtle phylogeny where a small number of paralogous alignments had an extraordinary influence.</li>
  <li>Newer “orthology-free” methods like ROADIES aim to infer species trees directly from raw genome assemblies by sampling genes, performing pairwise alignments, and iteratively estimating gene and species trees (dubious).</li>
</ul>

<h3 id="speed-vs-accuracy-of-phylogenetic-inference-methods">Speed vs. Accuracy of Phylogenetic Inference Methods</h3>
<ul>
  <li>For very large datasets (1000+ sequences), different ML tree inference software offer trade-offs:
    <ul>
      <li><strong>RAxML/ExaML:</strong> Very efficient, especially with multiple runs.</li>
      <li><strong>IQ-TREE:</strong> Also fast and relatively accurate.</li>
      <li><strong>FastTree:</strong> Very fast but may have trade-offs with accuracy.</li>
      <li>Fasttree joke: It is fast, and it is a tree.</li>
    </ul>
  </li>
  <li>The presentation notes that “quick and dirty or black box methods” used for large datasets might lead to worse answers if not carefully considered.</li>
  <li>Newer methods like CASTER (a site-based quartet method) are very fast but their performance on complex, real-world problems needs further evaluation.</li>
  <li>Comments on <a href="https://www.science.org/doi/10.1126/science.adk9688">CASTER: Direct species tree inference from whole-genome alignments</a>: If you have to use “quick and dirty” or black box methods in order to be able to analyze large data sets - more data may result in WORSE answers.</li>
</ul>

<h3 id="is-the-species-tree-always-what-you-want">Is the Species Tree Always What You Want?</h3>
<ul>
  <li>Different genes can have different evolutionary histories (gene trees) due to processes like incomplete lineage sorting or introgression.</li>
  <li>If interested in a trait controlled by one or a few genes, the species tree may not accurately describe the evolutionary history of those specific genes.</li>
  <li>Holistic genome approaches, like considering ancient gene linkages, can offer insights into deep evolutionary questions, such as the sister group to all other animals.</li>
</ul>

<h3 id="data-processing-choices-and-ascertainment-bias">Data Processing Choices and Ascertainment Bias</h3>
<ul>
  <li><strong>Ascertainment bias</strong> is a bias in parameter estimation or testing caused by non-random sampling of data. It is ubiquitous and can arise from how data is collected or filtered (e.g., sampling across the tree of life, volunteer surveys, studying undergraduates).</li>
  <li><strong>Missing Data in RADseq:</strong> Factors like mutations at restriction sites, clustering parameters, or low coverage can cause allele drop-out. While random missing data might not be highly problematic, phylogenetically-biased missing data can mislead inference, affecting topology, branch lengths, and support values. Simply excluding sites with high missing data can bias rate estimation downwards by preferentially removing high-rate loci. There are no universal “rules-of-thumb” for handling this due to complex interactions. Investigating a range of filtering parameters is advised. The Penstemon RADseq case study shows that missing data can be phylogenetically biased, with many loci found only in one of the major clades, suggesting that analyzing clades <strong>separately</strong> or using different filtering parameters might be necessary.</li>
  <li><strong>Sequencing Error:</strong> Can be problematic when true variation is rare, as errors (often singletons) can overestimate tip branch lengths. While error correction methods exist and genotype likelihoods could help, these are not always implemented in standard phylogenetic likelihood models. High coverage likely reduces the impact of sequencing error.
    <ul>
      <li>TODO: Can sequencing quality data used and implemented in phylogenetic likelihood models?</li>
    </ul>
  </li>
  <li><strong>Reference Genome Choice:</strong> Mapping reads to a reference can speed up consensus sequence generation but can also introduce bias. Variant calling can be biased towards the reference base in polymorphic regions, and branch lengths can change based on reference choice. Error rates can be correlated with distance to the reference, with errors biased towards the reference base. Reference choice can even affect topology. While sequence calls may change based on the reference, overall phylogenetic conclusions might sometimes remain unaffected.
    <ul>
      <li>Base call errors match the reference base 97% of the time, so the choice of reference genome can have a large impact on the phylogeny.</li>
      <li>A useful tutorial on Reference Bias: https://github.com/snacktavish/TreeUpdatingComparison/blob/master/TreeUpdating.md</li>
    </ul>
  </li>
  <li><a href="https://inria.hal.science/PGE/page/table-of-contents">Free textbook: Phylogenetics in the Genomic Era</a></li>
</ul>

<h2 id="open-tree-of-life-project">Open Tree of Life project</h2>

<h3 id="the-need-for-a-comprehensive-tree-of-life">The Need for a Comprehensive Tree of Life</h3>

<ul>
  <li>New and improved evolutionary trees are constantly published, but even large-scale efforts often miss a significant fraction of known biodiversity (e.g., a recent plant phylogeny covering 8,000 species still missed 40% of plants).</li>
  <li>Taxonomy is often used as a proxy for evolutionary history, but it can be a coarse or even misleading representation.</li>
  <li>Researchers use taxonomy because comprehensive phylogenies are often not available for all species of interest, keep changing, or are hard to access.</li>
</ul>

<h3 id="features-and-functionality">Features and Functionality</h3>

<ul>
  <li><strong>Taxonomic Integration:</strong> Users can view the lineage of any taxon within the Open Tree Taxonomy (OTT). New taxa from uploaded trees can be added and will be incorporated into future synthetic trees, with opportunities for feedback to source taxonomies.</li>
  <li><strong>Synthetic Tree:</strong> A continuously updated tree that synthesizes information from the curated phylogenies and the taxonomic backbone. It visualizes phylogenetic information and areas of conflict.</li>
  <li><strong>Date Estimates (DATELife):</strong>
    <ul>
      <li>The main synthetic tree currently does not have inherent branch lengths because combining diverse data types (DNA, morphology, taxonomy) makes direct branch length synthesis non-obvious.</li>
      <li>However, the DATELife project (Sanchez-Reyes, McTavish, O’Meara, 2024) allows for the translation of date estimates from input chronograms (dated trees) onto the Open Tree synthetic topology or a user-provided tree.</li>
      <li>It works by matching taxa, finding congruent nodes between source chronograms and the target topology, and using median pairwise node ages to date the target tree.</li>
    </ul>
  </li>
</ul>

<h3 id="why-use-open-tree">Why Use Open Tree?</h3>

<ul>
  <li><strong>Large-scale diversity assessment:</strong> Facilitates projects like PhyloNext for analyzing phylogenetic diversity of GBIF-mediated data.</li>
  <li><strong>Convenience:</strong> Easily get accurate relationships and citations for arbitrary sets of species (e.g., finding the closest relative with a reference genome).</li>
  <li><strong>Custom Synthesis:</strong> Users can generate custom synthetic trees for their specific taxa of interest, potentially with personalized phylogeny rankings and choice of root.</li>
  <li><strong>Bird Tree Example:</strong> A synthesis phylogeny of all birds (McTavish et al., 2025) covering 87% of species, built from 321 published trees, is available <a href="https://www.pnas.org/doi/abs/10.1073/pnas.2409658122">A complete and dynamic tree of birds</a>.</li>
</ul>

<h1 id="day-5">Day 5</h1>

<h2 id="cpp-session-in-the-morning---john-huelsenbeck">Cpp session in the morning - John Huelsenbeck</h2>

<ul>
  <li>Yesterday we talked about pointers and references, and how to construct functions that take pointers and references as arguments. You can also dereference pointers to access the data they point to.</li>
  <li>The evolution of PRNG algorithms, Von Neumann etc.
    <ul>
      <li>A USB device called TrueRNG3 on Amazon, which is a hardware random number generator that uses quantum noise to generate random numbers.</li>
    </ul>
  </li>
  <li>Making arrays/vectors: the <code class="language-plaintext highlighter-rouge">[]</code> operator is just dereferencing a pointer.</li>
</ul>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;iomanip&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">*</span> <span class="n">argv</span><span class="p">[]</span> <span class="p">)</span> <span class="p">{</span>
	
	<span class="kt">int</span> <span class="n">x</span><span class="p">[</span><span class="mi">10</span><span class="p">];</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">x</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">i</span> <span class="o">*</span> <span class="mi">10</span><span class="p">;</span>
		<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">setw</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="o">&lt;&lt;</span> <span class="n">x</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">&lt;&lt;</span> <span class="s">" "</span> <span class="o">&lt;&lt;</span> <span class="o">&amp;</span><span class="n">x</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">&lt;&lt;</span> <span class="s">"</span><span class="se">\n</span><span class="s">"</span><span class="p">;</span>
	<span class="p">}</span>

	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">"</span><span class="se">\n</span><span class="s">"</span><span class="p">;</span>

	<span class="kt">int</span><span class="o">*</span> <span class="n">p</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">x</span><span class="p">[</span><span class="mi">3</span><span class="p">];</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">"p = "</span> <span class="o">&lt;&lt;</span> <span class="n">p</span> <span class="o">&lt;&lt;</span> <span class="s">"</span><span class="se">\n</span><span class="s">"</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">"p's dereferenced value: "</span> <span class="o">&lt;&lt;</span> <span class="o">*</span><span class="n">p</span> <span class="o">&lt;&lt;</span> <span class="s">"</span><span class="se">\n</span><span class="s">"</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">"p[0] = "</span> <span class="o">&lt;&lt;</span> <span class="n">p</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">&lt;&lt;</span> <span class="s">"</span><span class="se">\n</span><span class="s">"</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">"p[1] = "</span> <span class="o">&lt;&lt;</span> <span class="n">p</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">&lt;&lt;</span> <span class="s">"</span><span class="se">\n</span><span class="s">"</span><span class="p">;</span> <span class="err">#</span> <span class="n">you</span> <span class="n">can</span> <span class="n">actually</span> <span class="n">put</span> <span class="n">a</span> <span class="n">negative</span> <span class="n">index</span> <span class="n">here</span><span class="p">,</span> <span class="n">causing</span> <span class="n">out</span><span class="o">-</span><span class="n">of</span><span class="o">-</span><span class="n">bounds</span> <span class="n">access</span>

	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="bayesian-model-comparison-with-migrate---peter-beerli">Bayesian Model Comparison with MIGRATE - Peter Beerli</h2>

<h3 id="inference-of-parameters">Inference of parameters</h3>

<ul>
  <li>If the model of prime interest is on population dynamics (e.g., geographic structure, colonization, recurrent gene flow, past population splitting, …), the mutation model and genealogies (trees) become nuisance (we may simply integrate them).</li>
  <li>The primary goal in population genetics is often to infer parameters related to geographic structure, colonization, gene flow, population splitting, etc.</li>
  <li>Genetic data (sequence differences) are used as a proxy because detailed historical records are usually unavailable. This necessitates additional models, like mutation models and genealogical models (e.g., the coalescent).</li>
  <li>Inferring the posterior probability of population model parameters ($\theta$) given the data ($D$) using Bayes’ theorem, often employing MCMC:
  $P(\theta\vert D) = \frac{P(\theta)P(D\vert \theta)}{P(D)} = \frac{P(\theta)\int_{G}P(G\vert \theta)P(D\vert G,\mu)dG}{\int_{\theta}P(\theta)\int_{G}P(G\vert \theta)P(D\vert G,\mu)dGd\theta}$
  (where $G$ is genealogy, $\mu$ is mutation model parameters).</li>
  <li>Beyond just reporting posteriors, we can statistically compare different demographic models.</li>
</ul>

<h3 id="structured-vs-non-structured-populations">Structured vs. Non-structured Populations</h3>
<ul>
  <li><strong>Non-structured (single population):</strong> Free interbreeding. Variability accumulates approximately by $N \times \mu$. Highly variable populations may persist longer.</li>
  <li><strong>Structured population:</strong> Interbreeding restricted to subpopulations. Variability in a subpopulation is gained via $N_{subpop} \times (m+\mu)$ (where $m$ is immigration rate). High immigration makes it behave like a single population. Structured systems can be more resistant to extinction from threats like parasites due to slowed transmission.</li>
</ul>

<h3 id="bayesian-model-comparison">Bayesian Model Comparison</h3>
<ul>
  <li><strong>Bayesian Odds Ratios:</strong> The posterior odds ratio for two models ($M_1$ vs. $M_2$) given data ($X$) is: $\frac{P(M_1\vert X)}{P(M_2\vert X)} = \frac{P(M_1)}{P(M_2)} \times \frac{P(X\vert M_1)}{P(X\vert M_2)}$ This is (Prior Odds) $\times$ (Bayes Factor).</li>
  <li><strong>Bayes Factor (BF):</strong> $BF = \frac{P(X\vert M_1)}{P(X\vert M_2)}$ This is the ratio of the <strong>marginal likelihoods of the data under each model</strong>. The <strong>log Bayes Factor (LBF)</strong> is $LBF = 2 \ln(BF)$. Interpretation of LBF magnitude:
    <ul>
      <li>$0 &lt; \vert LBF\vert  &lt; 2$: No real difference</li>
      <li>$2 &lt; \vert LBF\vert  &lt; 6$: Positive evidence</li>
      <li>$6 &lt; \vert LBF\vert  &lt; 10$: Strong evidence</li>
      <li>$\vert LBF\vert  &gt; 10$: Very strong evidence</li>
    </ul>
  </li>
  <li>The marginal likelihood $P(X\vert M_i)$ is the denominator $P(X)$ in the standard Bayesian posterior calculation for <strong>parameters</strong> within model $M_i$, integrated over the entire parameter space of that model.</li>
</ul>

<h3 id="marginal-likelihood-calculation">Marginal Likelihood Calculation</h3>
<ul>
  <li>Calculating marginal likelihoods is often complicated in MCMC applications.</li>
  <li>The harmonic mean estimator is unreliable.</li>
  <li>Accurate methods include:
    <ul>
      <li>Thermodynamic integration (used by MIGRATE)</li>
      <li>Stepping-stone integration</li>
      <li>Inflated Density Ratio</li>
    </ul>
  </li>
</ul>

<h2 id="migrate-tutorial---peter-beerli">MIGRATE Tutorial - Peter Beerli</h2>

<ul>
  <li><a href="https://peterbeerli.com/migrate-html5/about.html">MIGRATE homepage</a></li>
  <li>He actually developped a specific file format for MIGRATE.</li>
  <li>We learnt how to specify structured models and population split/migration models in MIGRATE.</li>
  <li>The model with the highest marginal likelihood (or model probability) is the best-supported model by the data.</li>
  <li>An example with simulated Zika virus data illustrates model comparison for population splitting and migration scenarios.</li>
  <li>Bayesian model selection using marginal likelihoods allows comparison of <strong>non-nested models</strong>.</li>
  <li>Complex biogeographic or demographic models can be compared easily.</li>
  <li>
    <blockquote>
      <p>specify a migration matrix for a 5-population system where population 1 and 5 are on a mainland, population 2 is an island close to 1, population 4 is close to 5, and population 3 is far out in the sea but closest to 2. ‘Close’ means reachable by rafting, and once on an island, it will be difficult to get off again.</p>
    </blockquote>
  </li>
</ul>

<p>The migration matrix should be:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    1 2 3 4 5
  1 x 0 0 0 x
  2 x x 0 0 0
  3 0 x x 0 0
  4 0 0 0 x b
  5 x 0 0 0 x
</code></pre></div></div>
<ul>
  <li>https://molevolworkshop.github.io/faculty/beerli/migrate-tutorial-html/MIGRATEtutorial2023.html</li>
  <li>I found that in <a href="https://academic.oup.com/bioinformatics/article/30/16/2272/2748160">Tim’s MultiTypeTree paper</a>, actually used migrate-n as a benchmark.</li>
</ul>

<h2 id="multilocus-phylogeography-and-phylogenetics---scott-edwards">Multilocus phylogeography and phylogenetics - Scott Edwards</h2>

<p><strong>Part I: Reticulation and the Emerging Continuum</strong></p>

<ul>
  <li>Incomplete Lineage Sorting (ILS) / Deep Coalescence</li>
  <li><a href="https://www.nature.com/articles/nature07331">Genes mirror geography within Europe</a></li>
  <li>Multilocus Models in Phylogeography: population genetic parameters like population size ($\theta = 4N\mu$), divergence time ($\tau = \mu t$), and gene flow ($M = m/\mu$).</li>
  <li>Whole-genome Phylogeography: using whole-genome resequencing data to investigate population structure, effective migration surfaces (EEMS), and introgression using ABBA-BABA tests (Dsuite).</li>
</ul>

<p><strong>Part II: PhyloG2P - Macroevolution and the Origin of Phenotypic Traits</strong></p>

<ul>
  <li><strong>Genomic Signatures of Trait Associations:</strong>
    <ul>
      <li>Deletion/inactivation or acceleration of conserved noncoding elements (CNEEs). The neutral theory (Motoo Kimura) predicts that functionally important regions will have lower substitution rates than less important ones; thus, acceleration can suggest a change, loss, or relaxation of function.</li>
    </ul>
  </li>
  <li><strong>PhyloAcc Software Family:</strong>
    <ul>
      <li>This software connects genomic and trait variation via phylogenies.</li>
      <li><strong>PhyloAcc:</strong> Models rates on branches as background ($r_0=1$), conserved ($r_1 &lt; 1$), or accelerated ($r_2 &gt; 1$) based on a hidden state $Z_s$ for element $i$ on branch $s$. It uses a transition matrix for $Z_s$ with parameters $\alpha$ (probability of gain of conserved state) and $\beta$ (probability of loss of conserved state).</li>
      <li><strong>PhyloAcc-GT (binary traits):</strong> Extends PhyloAcc to account for gene tree variation when detecting accelerations.</li>
      <li><strong>PhyloAcc-C (continuous traits):</strong> Models molecular rates ($r_0, r_1, r_2$) and phenotypic rates ($\nu$, which is $\sigma^2$ scaled by $\beta_2$ or $\beta_3$) jointly, allowing estimation of the association ($log(\beta_3/\beta_2)$) between molecular acceleration and phenotypic change. An example links molecular accelerations in a CNEE with changes in longevity in mammals.</li>
      <li>CNEEs linked to longevity were found near genes with diverse functions.</li>
    </ul>
  </li>
  <li><strong>Case Studies (Birds):</strong>
    <ul>
      <li><strong>Tarsus Length in Birds:</strong> Four groups (penguins, kingfishers, bulbuls, swallows) show shifts to shorter tarsus length. PhyloAcc identified ~14,000 elements accelerated in short-tarsus lineages, many in ATAC-seq peaks, near genes involved in limb development pathways.</li>
      <li><strong>Convergent Evolution of Flightlessness in Palaeognathae:</strong> This section highlights the long-standing debate about whether phenotypic evolution is driven more by changes in genes or gene regulation (King &amp; Wilson 1975). It shows the phylogeny of birds including palaeognaths. Whole-genome alignments (e.g., 42 bird species using ProgressiveCactus) and analysis of different noncoding markers (UCEs, introns, CNEEs) are used. Coalescent analyses (MP-EST) using thousands of loci (CNEEs, introns, UCEs) helped resolve the position of rheas and suggested an ancient rapid radiation, potentially in the anomaly zone where the most common gene tree might not match the species tree. The study identified convergently accelerated CNEEs in ratite (flightless bird) lineages, particularly near developmental genes. ATAC-seq data further showed CNEEs in flight-related tissues active in early chick development. The combined information suggests candidate enhancers for flightlessness.</li>
    </ul>
  </li>
</ul>

<h2 id="pangenomes-for-ecology-and-evolution---scott-edwards">Pangenomes for Ecology and Evolution - Scott Edwards</h2>

<p><strong>1. Introduction to Pangenomes:</strong></p>
<ul>
  <li><strong>Moving Beyond Reference-Based Genomics:</strong> Traditional genomics often relies on mapping reads to a single reference genome. Pangenomics aims to capture the entire set of genes and genomic regions found in a group of individuals or species.</li>
  <li>A pangenome consists of:
    <ul>
      <li><strong>Core genome:</strong> Genes present in all individuals/strains.</li>
      <li><strong>Accessory/Dispensable genome:</strong> Genes present in only some individuals/strains.</li>
    </ul>
  </li>
</ul>

<p><strong>2. Pangenomes in Avian Genomics - Case Study: Scrub Jays</strong></p>

<ul>
  <li><strong>Context: Avian Genomes:</strong> Birds generally have small, streamlined genomes compared to other amniotes like mammals or other reptiles. However, avian genome assembly quality is improving with new sequencing technologies: Pacbio HiFi.</li>
  <li><strong>Population Size Variation:</strong> PSMC and bpp analyses show a ~60-fold range in effective population size ($N_e$) across the scrub-jay species, with Island Scrub Jays having the smallest $N_e$ and Woodhouse’s having the largest.</li>
  <li><strong>Repeat Content:</strong> RepeatMasker analysis indicates over 25% repeats and transposable elements in scrub-jay genomes. There’s interspecific variation in repeat content, especially LTR elements and satellites. Male birds (ZZ) show higher counts of a specific 18-kb satellite unit.</li>
  <li><strong>Genome Size Variation:</strong> Island Scrub Jay assemblies are ~100 Mb smaller than Woodhouse’s Scrub Jay. Genomescope estimates of maximum genome size vary across individuals and species.</li>
  <li><strong>Telomeres:</strong> Telomeres are mentioned as barometers of age and stress, with chronic malaria shown to accelerate telomere degradation in wild birds (Ashgar et al. 2015). A recent study (Brown et al. 2024) suggests that species with <strong>smaller</strong> $N_e$ (like the Island Scrub Jay) are predicted to have shorter telomeres and show changes in the genomic proportion of telomeric sequence.</li>
</ul>

<p><strong>3. Pangenome Graphs and Structural Variation (SV)</strong></p>

<ul>
  <li><strong>Pangenome Graphs:</strong> These graphs capture structural variation (SVs) within and between species.
    <ul>
      <li>Graph “depth” (how many haplotypes cover a region) can reveal different genomic features:
        <ul>
          <li>Medium depth: Normal regions.</li>
          <li>Low depth: SNPs or small indels.</li>
          <li>High depth: Large SVs, satellites, repeats.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>SVs and Population Size:</strong>
    <ul>
      <li>The number of SVs scales with population size.</li>
      <li>The Nearly Neutral Theory of molecular evolution (Tomoko Ohta) is invoked, suggesting that the efficacy of selection depends on $N_e s$ (effective population size × selection coefficient).</li>
      <li>In smaller populations (like the Island Scrub Jay), slightly deleterious mutations (including SVs) can drift to higher frequencies or become fixed more easily.</li>
      <li>Data suggests SVs are, on average, more deleterious than SNPs. Longer SVs appear to rise to higher frequencies in the small Island Scrub Jay population.</li>
    </ul>
  </li>
  <li><strong>Inversions:</strong> Inversions are common and their numbers also track population size. Pangenome and reference-based methods can identify numerous inversions, and these inversions show enhanced differentiation ($F_{ST}$) between species.</li>
  <li><strong>Copy Number Variants (CNVs) and Gene Deletions:</strong> Abundant CNVs and gene deletions are found, with patterns varying across species. Gene CNVs show a surprising pattern, with the Island Scrub Jay (smallest $N_e$) having fewer deletions but more increases in copy number compared to the larger mainland populations. These CNVs have functional consequences on gene expression (TPM - transcripts per million).</li>
</ul>

<h3 id="further-reading">Further Reading</h3>
<ul>
  <li><a href="https://academic.oup.com/mbe/article/36/5/1086/5372678">Bayesian Detection of Convergent Rate Changes of Conserved Noncoding Elements on Phylogenetic Trees</a></li>
  <li>Linking sequence evolution and continuous trait data, <a href="https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1011995">Gemmell et al. 2024. PLoS Comp. Biol. (4): e1011995</a>.</li>
  <li>TODO: The phenotypic traits for birds and avian flu evolution. Avonet database, Bayou. Can we link (serodata variations)/(DMS predictions) to accelerated rates?</li>
</ul>

<h1 id="day-7">Day 7</h1>

<h2 id="the-neutral-and-nearly-neutral-theories-of-molecular-evolution---joseph-p-bielawski">The neutral and nearly neutral theories of molecular evolution - Joseph P. Bielawski</h2>

<ul>
  <li>The fundamental evolutionary “forces” are mutation, genetic drift, and natural selection.</li>
  <li>Conceptual Models for Genetic Variation:
    <ul>
      <li><strong>Neo-Darwinism:</strong> Natural selection is the dominant force shaping genetic variation.</li>
      <li><strong>Neutral Theory (Motoo Kimura):</strong> Genetic drift is the dominant force for most observed molecular variation and evolution.</li>
      <li><strong>Nearly Neutral Theory (Tomoko Ohta):</strong> The interaction between genetic drift and selection is crucial, especially for mutations with small fitness effects.</li>
    </ul>
  </li>
  <li>
    <p><strong>Substitution:</strong> The outcome of a fixation process, representing a change in the “state” of the population at a particular genetic locus. <strong>Mutations</strong> can either be fixed or lost from a population.</p>
  </li>
  <li>Neutral Theory of Molecular Evolution (Kimura 1968)
    <ul>
      <li><strong>Rate of Substitution ($k$):</strong> Under neutrality, the rate of nucleotide substitution ($k$) at mutation-drift equilibrium is equal to the rate of new mutations ($\mu$) per gene (or site) per generation.
        <ul>
          <li>$k = (\text{new mutations}) \times (\text{probability of fixation})$</li>
          <li>Number of new mutations in a diploid population = $2N\mu$.</li>
          <li>Probability of fixation for a new <em>neutral</em> mutant = $1/(2N)$.</li>
          <li>Therefore, $k = 2N\mu \times \frac{1}{2N} = \mu$.</li>
        </ul>
      </li>
      <li><strong>Independence from Population Size:</strong> A key prediction is that the rate of neutral molecular evolution ($k$) is independent of population size ($N$). This is because in small populations, fewer new mutants arise but each has a higher chance of fixation by drift. In large populations, more mutants arise but each has a lower chance of fixation by drift.</li>
      <li><strong>Molecular Clock:</strong> The constant neutral rate ($k=\mu$) implies a “molecular clock,” meaning sequences should diverge at a roughly constant rate over time.</li>
      <li><strong>Functional Constraint:</strong> The evolutionary rate is inversely related to functional constraint.
        <ul>
          <li>Highly functional regions have more sites where mutations are deleterious.</li>
          <li><strong>Lower-rate genes/regions:</strong> More sites are functional, so more mutations are deleterious and removed by selection. The remaining (neutral) mutations contribute to $k=\mu$.</li>
          <li><strong>High-rate genes/regions:</strong> More sites are neutral (less functional constraint), so a larger fraction of mutations behave neutrally and can be fixed by drift, leading to $k=\mu$.</li>
        </ul>
      </li>
      <li><strong>Distribution of Fitness Effects (DFE) under Neutral Theory:</strong>
        <ul>
          <li>Lethal and strongly deleterious mutations are rapidly removed by selection and ignored by Kimura.</li>
          <li>Beneficial mutations are considered very rare and also ignored by Kimura.</li>
          <li>Neutral mutations ($s=0$, where $s$ is the selection coefficient) are considered the vast majority of mutations contributing to polymorphism and species divergence.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Nearly Neutral Theory (Ohta):
    <ul>
      <li><strong>Interaction of Drift and Selection:</strong> This theory emphasizes the importance of mutations with small selection coefficients (nearly neutral mutations) where both genetic drift and weak selection interact to determine their fate.</li>
      <li><strong>Population Size Matters:</strong>
        <ul>
          <li>The “neutral zone” (where mutations behave as effectively neutral) is defined by roughly $-1/(2N_e) &lt; s &lt; +1/(2N_e)$ (where $N_e$ is effective population size).</li>
          <li><strong>Small populations:</strong> Have a larger “neutral space.” More mutations (including slightly deleterious ones) behave as effectively neutral and evolve by drift. Selection is less effective.</li>
          <li><strong>Large populations:</strong> Have a smaller “neutral space.” Slightly deleterious mutations are more effectively eliminated by selection. Slightly beneficial mutations are fixed more frequently than by drift alone (though fixation is not certain).</li>
        </ul>
      </li>
      <li><strong>Molecular Clock Unlikely:</strong> Because the rate of evolution now depends on $N_e$ (which can change), a strict molecular clock is less likely under this theory.</li>
      <li><strong>DFE under Nearly Neutral Theory:</strong>
        <ul>
          <li>Includes a spectrum of slightly deleterious and slightly beneficial mutations, in addition to strictly neutral ones.</li>
        </ul>
      </li>
      <li><strong>Selective Implications / Dynamics:</strong>
        <ul>
          <li><strong>Rate slows as population becomes adapted:</strong> On a concave (saturating) fitness curve, mutations have larger fitness effects when fitness is low and smaller effects when fitness is high (closer to the optimum). This means selection is initially strong but becomes less effective as the population approaches an equilibrium.</li>
          <li><strong>Population approaches an equilibrium:</strong> The phenotype may reach a steady state where mutation pressure (more ways for mutations to decrease fitness) balances selection.</li>
          <li><strong>Detailed Balance:</strong> At equilibrium, the evolutionary process can reach a state of “detailed balance” where, for nearly neutral mutations, the rate of beneficial substitutions equals the rate of deleterious substitutions of the same absolute effect.</li>
          <li><strong>Equilibrium phenotype is NOT necessarily the most fit:</strong> The “marginal stability” of natural proteins might not be an adaptive optimum but rather a balance. Natural selection plays a role in preventing “mutational meltdown” by purging highly deleterious mutations.</li>
        </ul>
      </li>
      <li>Sometimes called “steady state models” or “balance mutation models”.</li>
      <li>Recommended reading for balance mutation models:
        <ul>
          <li><a href="https://www.pnas.org/doi/10.1073/pnas.0501865102">Sella G, Hirsh AE. The application of statistical physics to evolutionary biology. Proceedings of the National Academy of Sciences. 2005. 102(27):9541-9546</a>.</li>
          <li><a href="https://academic.oup.com/mbe/article/34/2/391/2528246?login=false">Jones CT, Youssef N, Susko E, Bielawski JP. Shifting balance on a static mutation–selection landscape: a novel scenario of positive selection. Molecular biology and evolution. 2016. 34(2):391-407</a>.</li>
        </ul>
      </li>
      <li>Recommended reading on stability-mediated epistasis and protein evolution:
        <ul>
          <li><a href="https://onlinelibrary.wiley.com/doi/10.1002/prot.22964">Goldstein RA. The evolution and evolutionary consequences of marginal thermostability in proteins. Proteins: Structure, Function, and Bioinformatics. 2011. 79(5):1396-1407</a>.</li>
          <li><a href="https://www.pnas.org/doi/10.1073/pnas.1120084109">Pollock DD, Thiltgen G, Goldstein RA. Amino acid coevolution induces an evolutionary Stokes shift. Proceedings of the National Academy of Sciences. 2012. 109(21):E1352-9</a>.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Index of Selection Intensity for Proteins ($d_N/d_S$ or $\omega$):
    <ul>
      <li><strong>Rationale:</strong> Proteins have a “built-in ruler” for their own neutral rate – the <strong>synonymous substitution rate ($K_S$ or $d_S$)</strong>.
        <ul>
          <li>Synonymous mutations do not change the amino acid sequence and are assumed to be largely selectively neutral (rate = neutral rate with respect to protein evolution).</li>
          <li>Non-synonymous mutations ($K_N$ or $d_N$) change the amino acid and can be deleterious, neutral, or beneficial; their rate depends on selection intensity.</li>
        </ul>
      </li>
      <li><strong>The $d_N/d_S$ ratio ($\omega$):</strong> This ratio is an index of selection intensity acting on the protein.
        <ul>
          <li>$d_N/d_S &lt; 1$: Purifying (negative) selection (most non-synonymous changes are deleterious and removed). Examples: histones.</li>
          <li>$d_N/d_S = 1$: Neutral evolution (non-synonymous changes are as likely to fix as synonymous ones). Examples: pseudogenes.</li>
          <li>$d_N/d_S &gt; 1$: Diversifying (positive) selection (non-synonymous changes are favored and fix at a higher rate than synonymous ones). Examples: MHC, Lysin.</li>
        </ul>
      </li>
      <li>This allows classification of sites or genes:
        <ul>
          <li>Selectively constrained: $d_N/d_S &lt; 1$.</li>
          <li>Strictly neutral: $d_N/d_S = 1$.</li>
          <li>Adaptive evolution: $d_N/d_S &gt; 1$.</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h2 id="codon-substitution-models--analysis-of-natural-selection---joseph-p-bielawski">Codon Substitution Models &amp; Analysis of Natural Selection - Joseph P. Bielawski</h2>

<ul>
  <li>
    <p>Recommended reading: <a href="http://awarnach.mathstat.dal.ca/~joeb/PAML_lab/resources/Jones_etal_2019_Chapter13.pdf">Jones C.T., Susko E., Bielawski J.P., 2019. Looking for Darwin in genomic sequences: validity and success depends on the relationship between model and data. In Evolutionary Genomics: Statistical and Computational Methods. Maria Anisimova (ed.) 2nd edition, Human press.</a></p>
  </li>
  <li>Mechanistic Codon Models (Population Time-Scale) models (e.g., MutSel models) are rooted in population genetics principles, considering mutation ($\mu_{ij}$), genetic drift (effective population size $N_e$), and selection ($s_{ij}$, the selection coefficient for a change from codon $i$ to $j$ at site $h$).
    <ul>
      <li>$S_{ij} = \Delta f_{ij}$ (difference in fitness between codon $j$ and $i$).</li>
      <li>The rate of substitution $A_{ij}^h$ from codon $i$ to $j$ at site $h$ is $\mu_{ij}N \times \frac{1}{N} = \mu_{ij}$ if $s_{ij}^h = 0$ (neutral), and $\mu_{ij}N \times \frac{s_{ij}^h}{1-e^{-Ns_{ij}^h}}$ otherwise (note that $y=\frac{s_{ij}^h}{1-e^{-Ns_{ij}^h}}$ approaches $\frac{1}{N}$ as $s_{ij} \to 0$; $y\to s_{ij}$ as $s_{ij} \to \infty$; $y \to 0$ as $s_{ij} \to -\infty$).</li>
      <li>Usually too complex to fit such model to real data.</li>
    </ul>
  </li>
  <li>Phenomenological Codon Models (Macroevolutionary Time-Scale) models (often called “$d_N/d_S$” or “$\omega$” models, e.g., GY94) typically do not explicitly model population genetic processes but describe the overall pattern of codon substitution over longer evolutionary timescales.
    <ul>
      <li>They use a few key phenomenological parameters:
        <ul>
          <li>$\kappa$: transition/transversion rate ratio.</li>
          <li>$\pi_j$: equilibrium frequency of codon $j$.</li>
          <li>$\omega = d_N/d_S$: the ratio of non-synonymous to synonymous substitution rates. This is the primary parameter of interest for detecting selection.</li>
        </ul>
      </li>
      <li>The instantaneous rate matrix $Q$ (typically $61 \times 61$ for sense codons) is defined using these <strong>few</strong> parameters. For example, the rate from codon $i$ to $j$ ($Q_{ij}$) might be:
        <ul>
          <li>0 if $i$ and $j$ differ by &gt;1 nucleotide.</li>
          <li>$\pi_j$ for synonymous transversions.</li>
          <li>$\kappa \pi_j$ for synonymous transitions.</li>
          <li>$\omega \pi_j$ for non-synonymous transversions.</li>
          <li>$\omega \kappa \pi_j$ for non-synonymous transitions.</li>
        </ul>
      </li>
      <li>These models assume $\omega$ is constant across all contexts (i.e., the effect of a non-synonymous change is scaled by the same $\omega$ regardless of the specific amino acids involved).</li>
      <li>Transition probabilities over time $P(t)$ are calculated as $P(v) = e^{Qv}$ (where $v$ is branch length).</li>
      <li>Site likelihoods $L_h$ are computed by summing over all possible ancestral codon states, and the total likelihood $L$ is the product of site likelihoods (or sum of log-likelihoods $l$).</li>
    </ul>
  </li>
  <li>Bridging Timescales: The MutSel Framework:
    <ul>
      <li>The “MutSel framework” (Mutation-Selection models) attempts to bridge the population genetic (mechanistic) and macroevolutionary (phenomenological) scales.</li>
      <li><strong>Two ways to reconcile:</strong>
        <ol>
          <li><strong>Map fitness to equilibrium codon frequencies (Sella and Hirsh 2005):</strong> Site-specific fitness coefficients $f^h$ for each codon determine the expected stationary codon frequencies $\pi^h$ at that site.</li>
          <li><strong>Expected index of selection intensity (Jones et al. 2016):</strong> The site-specific $d_N^h/d_S^h$ can be calculated from the MutSel rate matrix by comparing the expected rate of evolution with selection to the expected rate by drift alone. The $d_N/d_S = \omega$ of phenomenological models (like M0) is an analogue of this $dN/dS$ under the MutSel framework.</li>
        </ol>
      </li>
    </ul>
  </li>
  <li>Three Positive Selection Scenarios for how $\omega &gt; 1$ (often interpreted as positive selection) can arise:
    <ul>
      <li><strong>Scenario 1: Frequency-Dependent Selection</strong>
        <ul>
          <li>Arises from antagonistic co-evolution (host-pathogen, sexual conflict, molecular interactions). For example in host-pathogen arms races, where a common host genotype is targeted by pathogens, making rare host genotypes more fit.</li>
          <li>The fitness landscape is <em>dynamic</em>: the fitness of an amino acid changes depending on the context (e.g., frequency of other alleles or interacting partners).</li>
          <li>Under some interpretations of phenomenological codon models (like the “omega models”), the fitness values associated with amino acids at a site can effectively swap when a substitution occurs. This means that a change in the genetic state (a substitution) alters the fitness landscape for subsequent mutations.  Phenomenological codon models (like M0) implicitly assume a form of frequency-dependent selection when $\omega &gt; 1$.</li>
        </ul>
      </li>
      <li><strong>Scenario 2: Episodic Adaptation (Adaptive Peak Shift)</strong>
        <ul>
          <li>Occurs due to exploitation of a new niche, lateral gene transfer, or gene duplication, leading to a shift in the fitness landscape.</li>
          <li>The fitness peak itself moves. Initially, the population is sub-optimal in the new environment, and selection drives it towards the new peak (a non-stationary process).</li>
          <li>The MutSel-ES (Episodic Selection) model tries to capture this.</li>
          <li>Conclusion: Episodic models “work” because $\omega &gt; 1$ can be a consequence of the system moving towards a new fitness peak; they are sensitive to this non-stationary behavior. The estimated $\omega$ can be biased over increasing branch lengths.</li>
        </ul>
      </li>
      <li><strong>Scenario 3: Non-Adaptive Shifting Balance (Movement around a Stationary Peak)</strong>
        <ul>
          <li>The fitness landscape (peak) is <em>static</em>, but mutation and drift can move a population off the fitness peak to less fit states.</li>
          <li>Selection then acts to “repair” these shifts, pushing the population back towards the peak. This involves positive selection without necessarily leading to adaptation beyond maintaining the current function.</li>
          <li>The $d_N^h/d_S^h$ ratio can vary depending on the current amino acid at the site. Even with purifying selection acting most of the time to maintain a site near its fitness peak, <strong>occasional</strong> shifts away from the peak followed by selective “repair” can lead to observed $d_N/d_S &gt; 1$ for certain amino acid states when they are rare (i.e., when the site is “in the tail” of its fitness landscape).</li>
          <li>Conclusion: Positive selection ($d_N/d_S &gt; 1$) can operate even on a stationary fitness peak due to this shifting balance process, mimicking an adaptive peak shift in terms of $\omega$ values.</li>
          <li><strong>Heterotachy:</strong> This process, where $d_N/d_S$ at a site can change depending on the incumbent amino acid (effectively switching between low $\omega_1$ “near the peak” and high $\omega_2$ “in the tail”), is a form of heterotachy (rate-switching).</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Common Types of Phenomenological Codon Models:
    <ul>
      <li><strong>M0 Model (Goldman &amp; Yang 1994; Muse &amp; Gaut 1994):</strong> Assumes one $\omega$ for all sites and all branches.</li>
      <li><strong>Branch Models:</strong> Allow $\omega$ to vary among different branches of the tree (useful for detecting episodic adaptation on specific lineages).</li>
      <li><strong>Site Models:</strong> Allow $\omega$ to vary among codon sites within the alignment (useful for detecting sites under selection across the tree).
        <ul>
          <li>E.g., M3 (discrete model) allows sites to fall into several pre-defined $\omega$ categories (e.g., $\omega_0=0.01, \omega_1=1.0, \omega_2=2.0$) with certain proportions.</li>
          <li>Powerful approach for antagonistic co-evolution, where different sites may be under different selective pressures.</li>
        </ul>
      </li>
      <li><strong>Branch-Site Models:</strong> Combine features, allowing $\omega$ to vary among sites and also differently on pre-specified “foreground” branches versus “background” branches.
        <ul>
          <li>Can detect positive selection affecting only a few sites on specific lineages.</li>
          <li>However, branch-site models cannot distinguish between episodic adaptive evolution for a novel function and non-adaptive shifting balance on a fixed peak without external information.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>
    <p>double &amp; triple nucleotide changes is confounded with heterotachy:<a href="https://academic.oup.com/mbe/article/35/6/1473/4955390">Phenomenological Load on Model Parameters Can Lead to False Biological Conclusions</a></p>
  </li>
  <li>Phenotype-Genotype Codon Models (PhyloG2P)
    <ul>
      <li>This section introduces an approach to link genomic evolution to phenotypic changes, leveraging phylogenies (“Phylogenetics is the New Genetics”).</li>
      <li>Phylogenetic comparative methods can be applied to genomic data.</li>
      <li><strong>Phenotype + Genotype Models:</strong> Several models are cited that explicitly link phenotypic trait evolution with rates or patterns of molecular (DNA or codon) evolution.</li>
      <li><strong>Jones et al. (2020) Phenotype-Genotype (P-G) Codon Model:</strong>
        <ul>
          <li>Builds on the idea of heterotachy and covarion models for $d_N/d_S$ (where sites can switch between evolutionary regimes, e.g., $\omega_1$ low “near peak” and $\omega_2$ high “in tail”).</li>
          <li>A null model assumes $d_N/d_S$ evolution is independent of phenotype, while the P-G model allows gene evolution (specifically $d_N/d_S$ state) to depend on phenotypic changes.</li>
          <li>This allows for detecting adaptive molecular evolution linked to phenotypic shifts, possibly without requiring $d_N/d_S &gt; 1$ globally.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>An important recommended reading shared privately from Bielawski: <a href="https://academic.oup.com/mbe/article/42/4/msaf068/8092905">A New Comparative Framework for Estimating Selection on Synonymous Substitutions</a></li>
</ul>

<h2 id="adaptive-protein-evolution-introduction---belinda-chang">Adaptive protein evolution: Introduction - Belinda Chang</h2>

<ul>
  <li><strong>Experimental Methods for Studying Proteins:</strong>
    <ul>
      <li><strong>In vitro protein expression</strong> (using bacteria, yeast, insect, or mammalian cells) is crucial for obtaining large amounts of protein for functional and structural studies, and allows for site-directed mutagenesis to test evolutionary hypotheses.</li>
      <li><strong>Structure determination methods:</strong>
        <ul>
          <li>X-ray crystallography (can have issues with flexibility, crystallization conditions).</li>
          <li>NMR spectroscopy (good for solution-state and flexible proteins, but limited to smaller proteins).</li>
          <li>Cryo-electron microscopy (high resolution for larger complexes in a native-like state).</li>
        </ul>
      </li>
      <li><strong>Protein structure prediction:</strong> Homology modeling (e.g., MODELLER, Rosetta, SWISS-MODEL) and machine learning approaches (e.g., AlphaFold) are used, especially when experimental structures are unavailable or to predict structures <em>ab initio</em>. The “twilight zone” refers to sequence identity ranges where homology modeling becomes less reliable.</li>
    </ul>
  </li>
  <li><strong>Ancestral Protein Reconstruction (APR) Process (Thornton, 2004):</strong>
    <ol>
      <li>Infer a phylogenetic tree and evolutionary model from aligned extant sequences.</li>
      <li>Reconstruct the ancestral protein sequence at a node of interest using ML or Bayesian methods (often a single point estimate with the highest probability).</li>
      <li>Synthesize the gene for the ancestral protein (e.g., by stepwise PCR from oligonucleotides).</li>
      <li>Subclone the gene, transform cells, and express the ancestral protein.</li>
      <li>Purify and characterize its function (e.g., enzyme activity, ligand binding).</li>
    </ol>
  </li>
  <li><strong>Considerations and Assessing Robustness:</strong>
    <ul>
      <li>Most studies use a single, highest-probability ancestral sequence.</li>
      <li>Potential issues: violations of model assumptions (e.g., shifts in equilibrium frequencies), uncertainty in tree topology, statistical bias towards states with high equilibrium frequencies (which might bias towards more stable proteins).</li>
      <li>To assess robustness: consider alternate topologies/models, sample alternative ancestors from the posterior distribution, or sample “near-ancestor” sequences.</li>
      <li>Uncertainty in the reconstructed genotype does not always mean uncertainty in the phenotype (function). Experimental data is needed.</li>
    </ul>
  </li>
  <li><strong>Example: Uricase Evolution in Primates (Kratzer et al., 2014):</strong>
    <ul>
      <li>Uricase metabolizes uric acid; its loss in humans and some other primates is linked to diseases like gout.</li>
      <li>APR was used to resurrect ancient primate uricases to determine when and how function was lost.</li>
      <li>The study traced a gradual decline in uricase activity through primate evolution, with inactivating mutations identified at specific codons.</li>
      <li>This addresses questions like “Thrifty genes vs. drifty genes” for the loss of function.</li>
    </ul>
  </li>
  <li><strong>Example: Paleoenvironments (EF-Tu thermostability) (Gaucher et al., 2008):</strong>
    <ul>
      <li>Resurrected Elongation Factor Tu (EF-Tu) proteins from ancestral bacteria and archaea were used to infer ancient environmental temperatures.</li>
      <li>The thermostability ($T_m$) of modern EF-Tu correlates with the organism’s growth temperature.</li>
      <li>By measuring the $T_m$ of resurrected ancestral EF-Tu proteins (expressed in <em>E. coli</em>), researchers inferred that early bacterial ancestors were likely thermophilic (living at 60-80°C). The posterior distribution of ancestral $T_m$ values can be obtained by sampling from the posterior distribution of ancestral sequences.</li>
    </ul>
  </li>
  <li>Rhodopsin Evolution and Nocturnality in Early Mammals:
    <ul>
      <li>This section discusses investigating the hypothesis that early mammals lived in a nocturnal niche, which might have led to adaptive changes in rod photoreceptors (rhodopsin) for dim-light vision.</li>
      <li><strong>Methodology:</strong>
        <ul>
          <li>Ancestral rhodopsin sequences (Amniote, Mammalian, Therian) were reconstructed and expressed <em>in vitro</em>.</li>
          <li>Spectroscopic assays measured rhodopsin spectral tuning ($\lambda_{MAX}$) and the lifetime of the activated state ($t_{1/2}$), which relates to signal shut-off kinetics.</li>
        </ul>
      </li>
      <li><strong>Findings (Bickelmann et al., 2015):</strong> An increased lifetime ($t_{1/2}$) of activated rhodopsin was found in reconstructed mammalian and therian ancestors compared to the general amniote ancestor, suggesting adaptations for enhanced sensitivity in dim light.</li>
    </ul>
  </li>
  <li>Glutamate Receptors (GPCRs)：
    <ul>
      <li>Briefly introduces metabotropic glutamate receptors (mGluRs) and other G protein-coupled receptors (GPCRs) involved in synaptic neurotransmission.</li>
      <li>Shows an example of reconstructed ancestral amino-acid-binding GPCRs (Kuang et al., 2006) to study the evolution of ligand binding and potency of different agonists.</li>
    </ul>
  </li>
  <li>Coral Pigments (GFP-like proteins)：
    <ul>
      <li>Illustrates using APR to study the evolution of fluorescent proteins in corals (e.g., great star coral, Ugalde et al., 2004). By reconstructing ancestral proteins, researchers can trace the spectral shifts (e.g., from green to red) and understand the molecular basis of color diversification.</li>
    </ul>
  </li>
</ul>

<h2 id="adaptive-protein-evolution-detecting-changes-in-selection---belinda-chang">Adaptive protein evolution: Detecting changes in selection - Belinda Chang</h2>

<ul>
  <li>Examples of Positive Selection Studies:
    <ul>
      <li><strong>Host-viral arms races:</strong>
        <ul>
          <li>Primate TRIM5$\alpha$, Protein Kinase R (PKR).</li>
          <li>Potato virus Y.</li>
          <li>Neutrophil-mediated responses.</li>
        </ul>
      </li>
      <li><strong>Sperm-egg recognition:</strong> Abalone lysin.</li>
      <li><strong>Sensory proteins:</strong> Visual pigments in various vertebrates.</li>
      <li><strong>Transcription factors in development:</strong> Stem cell pluripotency.</li>
    </ul>
  </li>
  <li>Case Study: Primate Protein Kinase R (PKR) vs. Viral K3L:
    <ul>
      <li>PKR is an antiviral protein; viral proteins like K3L try to mimic its substrate (eIF2$\alpha$) to evade it.</li>
      <li>Phylogenetic analysis shows PKR evolving rapidly ($dN/dS &gt; 1$) in primates, while eIF2$\alpha$ is highly conserved. Viral K3L also shows evidence of rapid evolution ($dN/dS &gt; 1$).</li>
      <li>Sites under positive selection in PKR are identified, particularly in the kinase domain, including regions that interact with viral antagonists or eIF2$\alpha$.</li>
      <li>Experimental work (yeast growth assays) demonstrated that specific, positively selected residues (e.g., F394L in gibbon PKR) are crucial for resistance to viral K3L, confirming an adaptive arms race.</li>
    </ul>
  </li>
  <li><strong>Beyond Random Sites Models - Clade Models (e.g., CmC by Bielawski &amp; Yang 2004):</strong>
    <ul>
      <li>These models allow the form and strength of selection ($\omega$) to vary across both the phylogeny (different clades/lineages) and among sites within the protein.</li>
      <li><strong>Clade Model C (CmC)</strong>, for example, allows sites to be in categories like:
        <ol>
          <li>Always under purifying selection ($0 &lt; \omega_0 &lt; 1$) across the tree.</li>
          <li>Always evolving neutrally ($\omega_1 = 1$) across the tree.</li>
          <li>Evolving under <strong>divergent selection</strong> ($\omega_2 \neq \omega_3$) between pre-specified foreground and background clades.</li>
        </ol>
      </li>
      <li>An improved null model (M2a_rel by Weadick &amp; Chang 2012) is mentioned for testing divergent selection, where the third site class estimates a single $\omega$ across all branches.</li>
    </ul>
  </li>
  <li><strong>Case Study: Neotropical Cichlid Rhodopsin (Hauser et al. 2017):</strong>
    <ul>
      <li><strong>Hypothesis:</strong> Adaptation of rhodopsin (visual pigment) during the invasion of different light environments in Central and South America by cichlid fish.</li>
      <li>Clade models were used to test for divergent selection in rhodopsin associated with geography (Central vs. South America) and ecology (lacustrine vs. riverine).</li>
      <li>Strong evidence was found for accelerated rhodopsin divergence ($\omega = 14.0$ for 3.4% of sites) in the Central American cichlid lineage compared to the background South American lineage ($\omega = 4.5$).</li>
      <li>Site 83 was identified as under positive selection and showed independent N83D substitutions in Central American lineages.</li>
      <li><strong>Experimental follow-up:</strong> <em>In vitro</em> expression and spectroscopic assays of rhodopsin variants showed that the N83D mutation (found in Central American fish) significantly altered rhodopsin function (faster retinal release kinetics, $t_{1/2}$), suggesting adaptation to increased light levels in clearer Central American streams.</li>
    </ul>
  </li>
  <li>Future Directions: High-Throughput Functional Studies：
    <ul>
      <li><strong>Deep Scanning Mutagenesis:</strong> Experimental approaches to create and test large libraries of protein variants.</li>
      <li><strong>Example: High-throughput rhodopsin variant libraries:</strong>
        <ul>
          <li>Random mutagenesis of a rhodopsin gene.</li>
          <li>Transformation into yeast, followed by selection or screening based on function (e.g., light-dependent signaling pathway activation linked to GFP expression).</li>
          <li>Sequencing to identify which mutations lead to gain, loss, or neutral changes in function.</li>
          <li>This allows mapping of fitness landscapes and understanding the effects of many mutations simultaneously.</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h2 id="tutorial"><a href="http://awarnach.mathstat.dal.ca/~joeb/PAML_lab/lab.html">Tutorial</a></h2>
<ul>
  <li>Likelihood ratio test between models using PAML.</li>
</ul>

<h1 id="day-8">Day 8</h1>

<h2 id="species-tree-estimation---laura-kubatko">Species Tree Estimation - Laura Kubatko</h2>

<ul>
  <li>https://lkubatko.shinyapps.io/GeneTreeProbs/</li>
</ul>

<p>Here is a summary of the key concepts and methods from the lecture on Species Tree Inference, formatted as a set of course notes for future reference.</p>

<h3 id="course-notes-species-tree-inference"><strong>Course Notes: Species Tree Inference</strong></h3>

<h4 id="1-core-concepts-phylogenetics-and-population-genetics"><strong>1. Core Concepts: Phylogenetics and Population Genetics</strong></h4>

<ul>
  <li><strong>Phylogenetics:</strong> Uses genetic variation <em>between</em> different species or populations to infer their evolutionary relationships.</li>
  <li><strong>Population Genetics:</strong> Studies genetic variation <em>within</em> a single population.</li>
  <li><strong>Coalescence Theory:</strong> The theoretical bridge that links these two fields. It models how gene lineages merge (coalesce) as you look back in time.</li>
</ul>

<h4 id="2-the-coalescent-model-the-engine-of-inference"><strong>2. The Coalescent Model: The Engine of Inference</strong></h4>

<p>The coalescent process describes what happens to gene lineages within a single population as we trace them backward in time.</p>

<ul>
  <li><strong>The Coalescent Event:</strong> The point at which two gene lineages merge into a common ancestor.</li>
  <li><strong>Waiting Time:</strong> The time until a coalescence event occurs follows an <strong>exponential distribution</strong>.</li>
  <li><strong>Rate of Coalescence (\(\lambda\)):</strong> The speed at which lineages coalesce depends on two key factors:
    <ol>
      <li><strong>Number of lineages (\(k\)):</strong> More lineages lead to faster coalescence.</li>
      <li><strong>Effective population size (\(N\)):</strong> Larger populations lead to slower coalescence (it’s harder for lineages to find each other).</li>
    </ol>
  </li>
  <li><strong>The Rate Formula:</strong> The rate of coalescence for \(k\)lineages is\(\lambda = \frac{\binom{k}{2}}{2N}\).</li>
</ul>

<h4 id="3-the-multispecies-coalescent-msc-gene-trees-vs-species-trees"><strong>3. The Multispecies Coalescent (MSC): Gene Trees vs. Species Trees</strong></h4>

<p>The MSC applies the coalescent model to a phylogenetic context, where populations are linked together in a species tree.</p>

<ul>
  <li><strong>Species Tree:</strong> A phylogeny showing how species split from one another over time.</li>
  <li><strong>Gene Tree:</strong> The evolutionary history of a single gene, which evolves <em>within</em> the branches of the species tree.</li>
  <li><strong>Coalescent History:</strong> A specific mapping of the coalescent events for a gene onto the branches (ancestral populations) of the species tree.
    <ul>
      <li>Even when a gene tree’s shape matches the species tree, there can be multiple valid histories. For an asymmetric 4-taxon tree, there are 5 such histories.</li>
      <li>The total probability of a gene tree is the sum of the probabilities of all its possible histories.</li>
    </ul>
  </li>
  <li><strong>Incomplete Lineage Sorting (ILS):</strong>
    <ul>
      <li>Gene trees do not always match the species tree.</li>
      <li>This discordance often arises when coalescence fails to occur in the ancestral population immediately preceding a speciation event. The lineages sort independently in the deeper ancestral population, sometimes leading to a conflicting topology.</li>
      <li><strong>Key takeaway:</strong> Shorter time intervals between speciation events lead to more disagreement between gene and species trees.</li>
    </ul>
  </li>
</ul>

<h4 id="4-the-problem-with-concatenation"><strong>4. The Problem with Concatenation</strong></h4>

<p>A common but flawed approach is to combine all gene sequences into one large dataset (“concatenation”) and build a single tree. This is problematic for three main reasons:</p>

<ol>
  <li><strong>Statistical Inconsistency:</strong> Concatenation can strongly support the wrong species tree, especially in the presence of high ILS.</li>
  <li><strong>Inflated Support Values:</strong> Bootstrap or posterior probability values for nodes become artificially high (e.g., 100%), giving false confidence in the relationships.</li>
  <li><strong>Overestimated Speciation Times:</strong> The resulting branch lengths are often significant overestimates of the true speciation times.</li>
</ol>

<h4 id="5-methods-for-species-tree-inference-under-the-msc"><strong>5. Methods for Species Tree Inference under the MSC</strong></h4>

<p>Given the issues with concatenation, methods specifically designed to handle the MSC are necessary. They fall into three main categories:</p>

<p><strong>A. Summary / Two-Step Methods</strong>
These methods first estimate individual gene trees and then summarize them to find the species tree.</p>

<ul>
  <li><strong>ASTRAL:</strong> A popular summary method with a clear three-step process:
    <ol>
      <li><strong>Estimate Gene Trees:</strong> Create a phylogenetic tree for each gene/locus independently.</li>
      <li><strong>Extract Quartets:</strong> From the set of gene trees, extract all possible four-taxon relationships (quartets).</li>
      <li><strong>Find the Best Species Tree:</strong> Find the species tree topology that “agrees” with the maximum number of quartets from the gene trees.</li>
    </ol>
  </li>
  <li><strong>Key Features:</strong> ASTRAL is statistically consistent (if gene trees are correct) and computationally efficient. It can also estimate branch lengths and provides local posterior probabilities as a measure of node support.</li>
</ul>

<p><strong>B. Bayesian Co-estimation Methods</strong>
These methods avoid estimating gene trees in a separate step and instead co-estimate the gene trees and the species tree simultaneously in a single, fully model-based framework.</p>

<ul>
  <li><strong>Software Examples:</strong> StarBEAST, BPP.</li>
  <li><strong>Strengths:</strong> They are fully model-based and provide estimates for all model parameters (like population size) along with posterior probabilities for uncertainty.</li>
  <li><strong>Challenges:</strong> They are computationally very intensive, do not scale well to genome-sized data, and assessing convergence of the analysis can be difficult.</li>
</ul>

<p><strong>C. Site-Based Methods</strong>
These methods bypass the estimation of gene trees entirely and compute the likelihood of the species tree directly from the DNA sequence alignment.</p>

<ul>
  <li><strong>SVDQuartets:</strong>
    <ul>
      <li><strong>Basic Idea:</strong> For any four taxa, site patterns from the DNA are arranged into a “flattening matrix”.</li>
      <li><strong>Inference:</strong> Under the MSC, the matrix corresponding to the <em>true</em> species tree relationship will have a reduced mathematical rank (rank 10). The matrices for the two incorrect trees will have a full rank. The method finds the tree topology whose matrix is closest to rank 10.</li>
      <li><strong>Features:</strong> It is statistically consistent and scales well to large datasets.</li>
    </ul>
  </li>
  <li><strong>Composite Likelihood (CL):</strong>
    <ul>
      <li><strong>Idea:</strong> Decompose a large species tree into all possible 4-taxon subsets. Calculate the exact likelihood for each small subset and then multiply them together to get a composite likelihood for the full tree.</li>
      <li><strong>Features:</strong> This approach is computationally tractable while remaining model-based and having a strong theoretical foundation in statistics.</li>
    </ul>
  </li>
</ul>

<h4 id="6-lessons-from-empirical-data"><strong>6. Lessons from Empirical Data</strong></h4>

<ul>
  <li><strong>Sistrurus Rattlesnakes:</strong> Analysis of 19 genes showed that while most methods agreed on the major relationships, there was uncertainty in the fine-scale branching pattern. Concatenated analysis gave a highly supported tree but with severely biased (overestimated) speciation times.</li>
  <li><strong>Canid Phylogeny:</strong> A concatenated analysis of dog and wolf relatives produced very high support values. However, species tree methods like StarBEAST and SVDQuartets revealed much lower (and likely more realistic) support for many of the same nodes, highlighting the overconfidence of concatenation.</li>
</ul>

<h2 id="phylogenetic-comparative-models-mkn-models---rosana-zenil-ferguson">Phylogenetic comparative models, MKn models - Rosana Zenil-Ferguson</h2>

<ul>
  <li>The Q matrix have to sum to zero by each row, it is because the derivative of the probability row sum (1) at time $t$ is zero.</li>
  <li>Hypothesis testing - Bayesian framework: calculating the difference between the posterior probabilities of two parameter, is cheaper, than do a model selection using Bayes factor.</li>
  <li><a href="https://academic.oup.com/sysbio/article/64/1/127/2847997">The Unsolved Challenge to Phylogenetic Correlation Tests for Categorical Characters</a></li>
  <li><a href="https://academic.oup.com/sysbio/article/67/6/1091/4985805">Rethinking phylogenetic comparative methods</a></li>
</ul>

<h2 id="state-dependent-diversification-models---rosana-zenil-ferguson">State-dependent diversification models - Rosana Zenil-Ferguson</h2>

<ul>
  <li><a href="https://doi.org/10.1111/j.0014-3820.2006.tb00517.x">CONFOUNDING ASYMMETRIES IN EVOLUTIONARY DIVERSIFICATION AND CHARACTER CHANGE</a></li>
  <li><a href="https://m.youtube.com/watch?v=rgtjowkiH3k">BiSSE author video</a></li>
  <li><a href="https://bmcecolevol.biomedcentral.com/articles/10.1186/1471-2148-13-38">Exploring power and parameter estimation of the BiSSE method for analyzing species diversification</a></li>
</ul>

<h1 id="day-9">Day 9</h1>

<h2 id="molecular-evolution-gene-trees-and-species-trees---anne-d-yoder">Molecular evolution: gene trees and species trees - Anne D. Yoder</h2>

<ul>
  <li>Highly recommended paper: <a href="https://academic.oup.com/sysbio/article/46/3/523/1651369">Gene Trees in Species Trees</a></li>
</ul>

<h2 id="phylogenetic-networks-to-study-reticulate-evolution---claudia-solís-lemus">Phylogenetic networks to study reticulate evolution - Claudia Solís-Lemus</h2>

<ul>
  <li>A modified newick notation for networks, with the third colon indicating the parenthetical information about the reticulation events.</li>
  <li><a href="https://link.springer.com/article/10.1007/s00285-022-01746-y">Classes of explicit phylogenetic networks and their biological and mathematical significance</a></li>
  <li>Figure 7 of <a href="https://academic.oup.com/sysbio/article/65/5/843/2223565">Inconsistency of Species Tree Methods under Gene Flow</a></li>
  <li><a href="https://www.pnas.org/doi/abs/10.1073/pnas.1918304117">Bayesian inference of reassortment networks reveals fitness benefits of reassortment in human influenza viruses</a></li>
  <li><a href="https://www.biorxiv.org/content/10.1101/2024.11.15.623781v1.full.pdf+html">Revealing reassortment in influenza A viruses with TreeSort</a></li>
  <li>It happens when there is a vertical transmission between and ancestor and a descendant, this may suggest that you did not sample a extant species which is a descendant of the ancestor.</li>
  <li><a href="https://academic.oup.com/sysbio/article/67/5/800/4985806">Brownian Motion + weighted average in hybrid</a></li>
  <li>RF-Net2</li>
  <li>Phylo-network-rs?</li>
  <li>Conotribution to the Julia package?</li>
</ul>

<h2 id="evolutionary-applications-of-genomic-data---l-lacey-knowles">Evolutionary applications of genomic data - L. Lacey Knowles</h2>

<ul>
  <li>
    <p>He et al. 2017. Inferring the geographic origin of a range expansion: latitudinal and longitudinal coordinates inferred from genomic data in an ABC framework with the program X-ORIGIN. Mol. Ecol. 26:6908-6920. DOI: 10.1111/mec.14380</p>
  </li>
  <li>Interaction between host immune response and viral evolution within host. Finer scale to the NC paper, logitutinal data, long read sequencing, host immune measurement, host RNA-seq.</li>
  <li>
    <p>Spatial evolution within host - differnt organs? / continous space evolution of the virus.</p>
  </li>
  <li>Population level immunity and viral evolution.</li>
  <li>Climate change and viral evolution.</li>
  <li>Co-evolution of host and virus, bats and coronaviruses?</li>
</ul>]]></content><author><name>Haogao Gu</name><email>work@guhaogao.com</email></author><category term="Course notes" /><category term="Phylogenetics" /><category term="Molecular evolution" /><summary type="html"><![CDATA[Course materials are available at here.]]></summary></entry><entry><title type="html">Paper digest: Selection on synonymous sites: the unwanted transcript hypothesis (Nat Rev Genet, 2024)</title><link href="https://guhaogao.com/posts/2025-03-06/synonymous_mut_mechanism" rel="alternate" type="text/html" title="Paper digest: Selection on synonymous sites: the unwanted transcript hypothesis (Nat Rev Genet, 2024)" /><published>2025-03-06T00:00:00+08:00</published><updated>2025-03-06T00:00:00+08:00</updated><id>https://guhaogao.com/posts/2025-03-06/synoymous_mut_mechanism</id><content type="html" xml:base="https://guhaogao.com/posts/2025-03-06/synonymous_mut_mechanism"><![CDATA[<p>The paper titled <a href="https://doi.org/10.1038/s41576-023-00686-7">Selection on synonymous sites: the unwanted transcript hypothesis</a> by Laurence D. Hurst et al. discussion current understanding why synonymous mutations are not neutral. The part related to CpG dinucleotides is particularly interesting.</p>

<h2 id="the-unwanted-transcript-hypothesis">The unwanted transcript hypothesis</h2>
<h3 id="widespread-spurious-transcripts">Widespread spurious transcripts</h3>

<ul>
  <li>In the human genome, transcription factor binding sites are everywhere, nearly all the DNA of the human genome is transcribed.</li>
  <li>More than half of human DNA is derived from transposable elements, 83% of lncRNAs have exonized transposable elements.</li>
  <li>The transcription machinery is not perfect, slicing is error-prone.</li>
  <li>As a result, spurious/unwanted transcripts are heavily produced.</li>
</ul>

<h3 id="costly-spurious-transcripts">Costly spurious transcripts</h3>

<ul>
  <li>Translation are energetically demanding, and the translation machinery is limited.</li>
  <li>Expression of some unwanted transcripts are directly toxic, some can interfere with the expression of other genes.</li>
</ul>

<h2 id="the-solution">The solution</h2>

<ul>
  <li>First to curtail their creation, e.g., gene methylation in humans to reduce rates of spurious intragene transcriptional initiation from cryptic promoters.</li>
  <li>Second, to have QC mechanisms to degrade (e.g., by ribonucleases (RNases)) or physical isolation
(e.g., preventing nuclear export) unwanted transcripts.</li>
  <li>Details in <a href="https://media.springernature.com/full/springer-static/image/art%3A10.1038%2Fs41576-023-00686-7/MediaObjects/41576_2023_686_Fig1_HTML.png">Figure 1</a>.</li>
</ul>

<h3 id="selection-on-codon-usage">Selection on codon usage</h3>

<ul>
  <li>CpG -&gt; metCpG -&gt; metTpG: methylated CpG is hypermutable (10-fold higher mutation rates).</li>
  <li>GC -&gt; AT mutation bias: Even in the absence of methylation, GC→AT transitions are more often than the reverse. Non-coding regions, which aren’t under strong selective pressure, will accumulate more A/T bases.</li>
  <li>Check the <a href="https://media.springernature.com/lw1200/springer-static/image/art%3A10.1038%2Fs41576-023-00686-7/MediaObjects/41576_2023_686_Fig2_HTML.png">Figure 2</a> for the dinucleotide frequencies in the human genome.</li>
  <li>Because of the above two reasons, the genomic sequences are generally AT-rich and CG-poor.</li>
  <li>However, the coding region sequences have higher GC content.
    <ul>
      <li>Some of these amino acids are metabolically cheaper to produce, or avoid undesirable stops. As a result, many functional genes maintain high GC content, particularly at synonymous codon positions (e.g., GC3).</li>
      <li>GC-Biased Gene Conversion (gBGC) can elevate GC content in gene-rich regions by favoring GC over AT during DNA recombination. This effect can preserve or amplify high-GC “signals” in coding regions, distinguishing them from the AT-rich parts of the genome.</li>
    </ul>
  </li>
  <li>Selection on synonymous sites: GC-rich is preferred in coding regions, and AT-rich sequences as recognized suspicious.</li>
  <li>CpG is a notable exception to the GC-rich rule. CpG are hypermutable, so in coding regions, it is bad. Cells tend to prefer <strong>GC‐rich, CpG‐poor</strong> transcripts, especially those with multiple small exons—features that mark them as native. Viruses with high-GC content often violate this rule. Transcripts that deviate from this pattern, such as **AT‐rich, single‐exon, or high‐CpG **RNAs, are more likely to be considered non‐native and subject to suppression or degradation.</li>
</ul>

<h2 id="what-can-the-hypothesis-explain">What can the hypothesis explain?</h2>

<ol>
  <li>High‐GC Content Promotes Expression
    <ul>
      <li>Genes enriched in GC, especially at synonymous sites (like the third codon position), are recognized as native and pass quality control checks, enhancing their transcription and nuclear export.</li>
      <li>This explains why intronless but GC‐rich genes (including many retrogenes) achieve robust expression and why GC‐rich codons can boost protein output in transgene studies.</li>
    </ul>
  </li>
  <li>Avoidance of High‐AT and High‐CpG
    <ul>
      <li>AT‐rich or CpG‐rich transcripts are flagged as suspicious.</li>
      <li>Mechanisms like CpG methylation and the HUSH complex selectively silence or degrade such transcripts, effectively minimizing unwanted RNAs (from viruses or transposable elements) and preventing large‐exon, single‐exon, or A‐rich mRNAs from being expressed unless they have specific adaptive features.</li>
    </ul>
  </li>
  <li>Splicing Fidelity at Synonymous Sites
    <ul>
      <li>Humans show strong selection to preserve exonic splice enhancers (ESEs) at synonymous positions near exon boundaries to ensure accurate splicing, preventing the creation of aberrant splice variants.</li>
      <li>Conversely, synonymous mutations that create cryptic splice sites or disrupt known splicing signals are strongly disfavored.</li>
    </ul>
  </li>
  <li>Quality Control Through Multiple Filters
    <ul>
      <li>Steps such as nuclear export (handled by the NXF1 or TREX complexes), cytoplasmic processing bodies, and stress granules filter RNAs based on features like GC content, exon length, or A‐rich sequences.</li>
      <li>Additional checks (e.g., nonsense‐mediated decay, codon‐optimality–mediated decay) can degrade suspicious or faulty transcripts even if they reach the cytoplasm and engage ribosomes.</li>
    </ul>
  </li>
  <li>Broader Parallels with Viral Evasion
    <ul>
      <li>Viruses often reduce CpG content or use other strategies to avoid being flagged and degraded.</li>
      <li>Similar suppression mechanisms operate against incoming nucleic acids (e.g., in endosomes) and endogenous foreign‐like sequences, reinforcing the idea that GC/AT balance and the presence of introns serve as universal “fingerprints” of native versus unwanted RNA.</li>
    </ul>
  </li>
</ol>

<h2 id="what-can-it-not-explain">What can it not explain?</h2>
<ol>
  <li>CpG Islands vs. CpG Suppression
    <ul>
      <li>Although mammalian cells often silence CpG-rich regions (for instance, via methylation or binding proteins such as ZAP), they also maintain <strong>CpG islands</strong>—regions dense in CpG dinucleotides that remain unmethylated and help activate transcription.</li>
      <li>Why the cell doesn’t simply methylate <strong>all</strong> CpG sites, and how it balances both promoting and suppressing CpG-rich regions, remains somewhat paradoxical.</li>
    </ul>
  </li>
  <li>Exceptions Like L1 Transposable Elements
    <ul>
      <li>Most successful transposable elements are GC-rich, which fits the hypothesis. However, <strong>L1 elements</strong> are GC-poor but still manage to evade numerous quality control filters.</li>
      <li>Part of the explanation is that L1’s ORF1 is shorter than the length threshold targeted by HUSH, but a deeper understanding of why L1 still transposes despite multiple suppression mechanisms is incomplete.</li>
    </ul>
  </li>
  <li>No Quality Control Filter Is Perfect
    <ul>
      <li>Some features—like intronless transcripts or those with high A content—are flagged as suspicious, yet there are essential genes (like histones) or transcripts in early embryogenesis that bypass or temporarily evade these checks.</li>
      <li>The hypothesis acknowledges that perfect suppression would eliminate even some beneficial transcripts, so “leaky” expression is unavoidable.</li>
    </ul>
  </li>
  <li>Context-Specific Selection on Synonymous Sites
    <ul>
      <li>Not all selection on synonymous codons revolves around blocking unwanted transcripts. Some mutations, for example, influence RNA structures like <strong>G-quadruplexes</strong>, or regulate binding by <strong>miRNAs</strong>. These do not neatly fit under the “unwanted transcript” explanation.</li>
    </ul>
  </li>
</ol>]]></content><author><name>Haogao Gu</name><email>work@guhaogao.com</email></author><category term="Paper digest" /><category term="Molecular evolution" /><summary type="html"><![CDATA[The paper titled Selection on synonymous sites: the unwanted transcript hypothesis by Laurence D. Hurst et al. discussion current understanding why synonymous mutations are not neutral. The part related to CpG dinucleotides is particularly interesting.]]></summary></entry><entry><title type="html">Book notes: Molecular Evolution: A Statistical Approach by Ziheng Yang</title><link href="https://guhaogao.com/posts/2025-01-18/mol_evo_stat_appr" rel="alternate" type="text/html" title="Book notes: Molecular Evolution: A Statistical Approach by Ziheng Yang" /><published>2025-01-18T00:00:00+08:00</published><updated>2025-03-12T00:00:00+08:00</updated><id>https://guhaogao.com/posts/2025-01-18/Mol_evo_stat_appr</id><content type="html" xml:base="https://guhaogao.com/posts/2025-01-18/mol_evo_stat_appr"><![CDATA[<p>We decide to read the book <a href="http://abacus.gene.ucl.ac.uk/MESA/"><em>Molecular Evolution: A Statistical Approach</em></a> by Ziheng Yang, to gether on a weekly basis. Contents in this summary involve AI-generated text.</p>

<h1 id="1-models-of-nucleotide-substitution">1. Models of nucleotide substitution</h1>

<ul>
  <li>We define $p$ distance as thr proportion of sites that differ between two sequences.</li>
  <li>The true evolutionary distance $d$ is the expected number of substitutions per site between two sequences.</li>
  <li>CTMC (Continuous Time Markov Chain): four nucleotides are <em>states</em> of the chain, it will reach to <em>steady state</em> with a <em>stationary distribution</em>, via a <em>substitution rate matrix</em>.</li>
</ul>

<h2 id="markov-models-of-nucleotide-substitution-and-distance-estimation">Markov models of nucleotide substitution and distance estimation</h2>

<h3 id="the-jc69-model">The JC69 model</h3>

<ul>
  <li>Jukes-Cantor 1969 model.</li>
  <li>The substitution rate matrix $Q$ is
\(Q = \begin{pmatrix}
-3\lambda &amp; \lambda &amp; \lambda &amp; \lambda \\
\lambda &amp; -3\lambda &amp; \lambda &amp; \lambda \\
\lambda &amp; \lambda &amp; -3\lambda &amp; \lambda \\
\lambda &amp; \lambda &amp; \lambda &amp; -3\lambda
\end{pmatrix}\)</li>
  <li>The matrix of transition probability: $P(t) = e^{Qt}$. This is using Kolmogorov forward/backward? equation, where $\frac{dP(t)}{dt} = QP(t)$.</li>
  <li>We then use Taylor expansion to get $P(t) = I + Qt + \frac{Q^2t^2}{2!} + \cdots$.
    <ul>
      <li><a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr">Essense of calculus</a> by 3Blue1Brown.
        <ul>
          <li><a href="https://www.youtube.com/watch?v=3d6DsjIBzJ4">Taylor polynomial</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Chapman–Kolmogorov equation: $P_ij(t+s) = \sum_k P_ik(t)P_kj(s)$. This account for the multiple (hidden) states between $i$ and $j$.</li>
  <li>As $d=3\lambda t$, then $p(d) = 3p_1(t)=\frac{3}{4}-\frac{3}{4}e^{-4\lambda t}=\frac{3}{4}-\frac{3}{4}e^{-4d/3}$, then $\hat{d}=-\frac{3}{4}log(1-\frac{4}{3}\hat{p})$.</li>
</ul>

<h3 id="the-k80-model">The K80 model</h3>

<ul>
  <li>Kimura 1980 model.</li>
  <li>Transitions: pyrimidine (T $\leftrightarrow$ C), purine (A $\leftrightarrow$ G).</li>
  <li>Transversion: (T, C $\leftrightarrow$ A, G).</li>
  <li>$d = (\alpha + 2\beta)t$.</li>
  <li>$\kappa = \frac{\alpha}{\beta}$.</li>
  <li>$E(S) = p_1(t)$.</li>
  <li>$E(V) = 2p_2(t)$.</li>
  <li>$\hat{d} = -\frac{1}{2} \log(1 - 2S - V) - \frac{1}{4} \log(1 - 2V)$.</li>
</ul>

<h3 id="hky85-f84-tn93-etc">HKY85, F84, TN93, etc.</h3>

<h4 id="tn93">TN93</h4>

<ul>
  <li>Tamura-Nei 1993 model.</li>
  <li>7 parameters and 6 free parameters.</li>
  <li>$\pi_Y = \pi_T + \pi_C$ and $\pi_R = \pi_A + \pi_G$.</li>
  <li>$P(t)$ can be solved using spectral decomposition of $Q$.
    <ul>
      <li>$Q = U \Lambda U^{-1}$.</li>
      <li>$\Lambda = \text{diag}\lbrace \lambda_1, \lambda_2, \lambda_3, \lambda_4 \rbrace$.</li>
      <li>$P(t) = U e^{\Lambda t} U^{-1} = U \text{diag}\lbrace e^{\lambda_1 t}, e^{\lambda_2 t}, e^{\lambda_3 t}, e^{\lambda_4 t} \rbrace U^{-1}$.</li>
      <li><a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab">Essense of linear algebra</a> by 3Blue1Brown.
        <ul>
          <li><a href="https://www.youtube.com/watch?v=PFDu9oVAE-g">Eigenvectors and eigenvalues</a> with prerequisites:
            <ul>
              <li><a href="https://www.youtube.com/watch?v=kYB8IZa5AuE">Linear transformations</a></li>
              <li><a href="https://www.youtube.com/watch?v=XkY2DOUCWMU">Matrix multiplication</a></li>
              <li><a href="https://www.youtube.com/watch?v=Ip3X9LOh2dk">Determinants</a></li>
              <li><a href="youtube.com/watch?v=uQhTuRlWMxw">Linear systems</a></li>
              <li><a href="https://www.youtube.com/watch?v=P2LTAUO1TdA">Change of basis</a>, Jennifer is a French as indicated in 3:21 of this video :D</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
  <li>$\lambda = -\sum_i \pi_i q_{ii} = 2\pi_T \pi_C \alpha_1 + 2\pi_A \pi_G \alpha_2 + 2\pi_Y \pi_R \beta$.</li>
  <li>$d = \lambda t$.</li>
  <li>Using $E(S_1), E(S_2), E(V)$ to estimate $\alpha_1, \alpha_2, \beta$.</li>
  <li>$\hat{d}$ can be represented as a function of nucleotide frequencies and $E(S_1), E(S_2), E(V)$.</li>
</ul>

<h4 id="hky85-and-f84">HKY85 and F84</h4>

<ul>
  <li>
    <p>6 parameters and 5 free parameters.</p>
  </li>
  <li>Hasegawa-Kishino-Yano 1985 model.
    <ul>
      <li>Interesting fact: it should be called HKY84, misnamed in <em>Yang 1994</em>.</li>
      <li>Setting $\alpha_1 = \alpha_2 = \alpha$ or $\kappa_1 = \kappa_2 = \kappa$ in TN93 model.</li>
    </ul>
  </li>
  <li>Felsenstein 1984 model.
    <ul>
      <li>Setting $\alpha_1 = (1+\kappa/\pi_Y)\beta$ and $\alpha_2 = (1+\kappa/\pi_R)\beta$ in TN93 model.</li>
      <li>It is easier to derive a distance formula for F84 than for HKY85.</li>
    </ul>
  </li>
  <li>Felsenstein 1981 model.
    <ul>
      <li>Setting $\alpha_1 = \alpha_2 = \beta$ in TN93 model.</li>
      <li>A distance formula was derived by <em>Tajima and Nei (1982)</em>.
        <ul>
          <li>On a side note, <em>Tajima and Nei (1984)</em> is a classic paper on nucleotide diversity.</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h3 id="the-transitiontransversion-rate-ratio">The transition/transversion rate ratio</h3>

<ul>
  <li>Three definitions:
    <ul>
      <li>$E(S)/E(V) = p_1(t)/2p_2(t)$ under the K80 model (the uncorrected method).</li>
      <li>$\kappa = \alpha/\beta$ under the K80 model (corrected).</li>
      <li>$R = \alpha/2\beta$ under the K80 model (corredted). It’s called <em>average transition/transversion ratio</em>. More generally, $R = \frac{\pi_T q_{TC} + \pi_C q_{CT} + \pi_A q_{AG} + \pi_G q_{GA}}{\pi_T q_{TA} + \pi_T q_{TG} + \pi_C q_{CA} + \pi_C q_{CG} + \pi_A q_{AT} + \pi_A q_{AC} + \pi_G q_{GT} + \pi_G q_{GC}}$ under UNREST.</li>
    </ul>
  </li>
</ul>

<h2 id="variable-substitution-rates-among-sites">Variable substitution rates among sites</h2>

<ul>
  <li>Assuming the rate $r$ for any site is drawn from a gamma distribution.</li>
  <li>Models with <em>Gamma distance</em> denoted by a suffix ‘$+\Gamma$’.</li>
  <li>Gamma distribution have two parameters: shape $\alpha$ and scale $\beta$. The mean is $\alpha/\beta$, and the variance is $\alpha/\beta^2$. You can also consider them as number of Poisson process events of $\alpha$ with rate $1/\beta$.</li>
  <li>Note that the gamma distribution here sets $\alpha = \beta$ so that the mean equals to $1$.</li>
  <li>If a site has a rate $r$, the distance between sequences becomes $d = r t$.</li>
  <li>$p(d\cdot r)$ can be calculated by integrating the gamma distribution.</li>
  <li>For JC69 model, $p = \int_0^\infty \left( \frac{3}{4} - \frac{3}{4} e^{-4d \cdot r / 3} \right) g(r) \, dr 
= \frac{3}{4} - \frac{3}{4} \left( 1 + \frac{4d}{3\beta} \right)^{-\alpha}$.</li>
  <li>Similarly, one can derive a gamma distance under virtually every model for which a one-rate distance formula is available.</li>
  <li>It is well known that ignoring rate variation among sites leads to underestimation of both the sequence distance and the transition/transversion rate ratio.</li>
</ul>

<h2 id="maximum-likelihood-estimation-of-distance">Maximum likelihood estimation of distance</h2>

<ul>
  <li>The likelihood function is $L(\theta; X) = f(X\vert\theta)$.</li>
  <li>MLE is the value of $\theta$ that maximizes the likelihood function.</li>
  <li>Probability vs. Likelihood:
    <ul>
      <li>Likelihood $\ne$ Probability: Likelihood does not sum to 1, unlike probability.</li>
      <li>Interpretation: Probability is understood by area under the curve, while likelihood is compared at specific points.</li>
      <li>Reparametrization: Likelihood is invariant under monotonic transformations, so MLEs remain unchanged.</li>
      <li>Nonlinear Effects: Nonlinear transformations alter probability density shapes, potentially changing modality.</li>
    </ul>
  </li>
</ul>

<h3 id="the-jc69-model-1">The JC69 model</h3>

<ul>
  <li>The single parameter is the distance $d = 3\lambda t$. The data are two aligned sequences, each $n$ sites long, with $x$ differences.</li>
  <li>$p = 3p_1(t) = \frac{3}{4} - \frac{3}{4} e^{-4d/3}$.</li>
  <li>The likelihood function is $L(d; X) = {n\choose x}p^x(1-p)^{n-x}$.</li>
  <li>After reparametrization: $L(d; X) = (\frac{1}{4}p_1)^x (\frac{1}{4}p_0)^{n-x}$. (I think $\frac{1}{4}$ can be further dropped.)</li>
  <li>Two approaches to estimate confidence intervals:
    <ul>
      <li>Normal approximation: $\hat{d} \pm 1.96 \sqrt{var({d})}$.</li>
      <li>Likelihood interval, based on likelihood ratio test: $\frac{1}{2}\chi^2_{1, 5\%} = 3.841/2 = 1.921$.</li>
    </ul>
  </li>
</ul>

<h3 id="the-k80-model-1">The K80 model</h3>

<ul>
  <li>$L(d, \kappa; n_S, n_V) = \left( \frac{p_0}{4} \right)^{(n - n_S - n_V)} \times \left( \frac{p_1}{4} \right)^{n_S}  \times \left( \frac{p_2}{4} \right)^{n_V}.$</li>
  <li>$\frac{1}{2}\chi^2_{2, 5\%} = 5.991/2 = 2.995$.</li>
</ul>

<h3 id="likelihood-ratio-test-of-substitution-models">Likelihood ratio test of substitution models</h3>

<ul>
  <li>For model comparison, if two models are <strong>nested</strong>, then the likelihood ratio test can be used.</li>
</ul>

<h3 id="profile-and-integrated-likelihood">Profile and integrated likelihood</h3>

<ul>
  <li>The above approaches, estimating one parameter while ignoring the other, are called <em>relative likelihood</em>, <em>pseudo likelihood</em> or <em>estimated likelihood</em>.</li>
  <li>A more respective approach is <em>profile likelihood</em>.
    <ul>
      <li>$\ell(d) = \ell(d, \hat{\kappa}_d)$, where $\hat{\kappa}_d$ is the MLE of $\kappa$ for the given $d$.</li>
      <li>This is a pragmatic approach that most often leads to reasonable answers.</li>
    </ul>
  </li>
  <li><em>Integrated likelihood</em> or <em>marginal likelihood</em> is the likelihood of the data given the model, averaged over the parameter space.
    <ul>
      <li>It is possible to use a improper prior, such as a uniform distribution, to calculate the marginal likelihood.</li>
      <li>Integrated likelihood is always smaller than the profile likelihood.</li>
    </ul>
  </li>
</ul>

<h2 id="markov-chains-and-distance-estimation-under-general-models">Markov chains and distance estimation under general models</h2>

<h3 id="distance-under-the-unrestricted-unrest-model">Distance under the unrestricted (UNREST) model</h3>

<ul>
  <li>Unlike the <strong>GTR model</strong>, UNREST does not assume time-reversibility.</li>
  <li>Here we consider a strand-symmetry model, where $q_{TC} = q_{AG}$.</li>
  <li>Equilibrium nucleotide frequencies ${\pi_T, \pi_C, \pi_A, \pi_G}$ perhaps by coincidence, can be estimated analytically.</li>
</ul>

<ol>
  <li><strong>Identifiability Issues and Distance Calculation</strong>
    <ul>
      <li>The <strong>model can, in theory, identify the root</strong> of a two-sequence tree.</li>
      <li>However, <strong>estimating both $t_1$ and $t_2$ separately</strong> leads to <strong>high correlation</strong> between estimates.</li>
      <li>The model has <strong>13 parameters</strong>:
        <ul>
          <li><strong>11 rate parameters</strong> in $Q$.</li>
          <li><strong>2 branch lengths</strong> $t_1, t_2$.</li>
        </ul>
      </li>
      <li><strong>Challenges:</strong>
        <ul>
          <li>No analytical solution for MLEs.</li>
          <li>Complex eigenvalues make numerical estimation difficult.</li>
          <li>Many datasets do not provide enough information to estimate so many parameters.</li>
        </ul>
      </li>
      <li><em>*Conclusion:</em>-
        <ul>
          <li>Although $t_1$ and $t_2$ are <strong>identifiable</strong>, their estimates are <strong>highly correlated</strong>.</li>
          <li>The UNREST model <strong>is not recommended for distance calculations</strong>.</li>
        </ul>
      </li>
    </ul>
  </li>
</ol>

<h3 id="distance-under-the-general-time-reversible-model">Distance under the general time-reversible model</h3>
<ol>
  <li><strong>Time-Reversibility in Markov Chains</strong>
    <ul>
      <li>A Markov chain is <strong>time-reversible</strong> if:
\(\pi_i q_{ij} = \pi_j q_{ji}, \quad \text{for all } i \neq j.\)
This condition is known as <strong>detailed balance</strong>.</li>
      <li><strong>Reversibility is a mathematical convenience</strong>, not necessarily a biological property.</li>
      <li>Models such as <strong>JC69, K80, F84, HKY85, and TN93</strong> are all <strong>time-reversible</strong>.</li>
    </ul>
  </li>
  <li><strong>Rate Matrix for GTR Model</strong>
    <ul>
      <li>The <strong>GTR (General Time-Reversible) model</strong> is defined using the rate matrix:
\(Q = 
\begin{bmatrix}
\cdot &amp; a\pi_C &amp; b\pi_A &amp; c\pi_G \\
a\pi_T &amp; \cdot &amp; d\pi_A &amp; e\pi_G \\
b\pi_T &amp; d\pi_C &amp; \cdot &amp; f\pi_G \\
c\pi_T &amp; e\pi_C &amp; f\pi_A &amp; \cdot
\end{bmatrix}\)
        <ul>
          <li>It has <strong>nine free parameters</strong> (six substitution rates + three equilibrium frequencies).</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Simplification of Likelihood Computation</strong>
    <ul>
      <li>Reversibility simplifies likelihood computation:
\(f_{ij}(t_1, t_2) = \sum_k \pi_k p_{ki}(t_1) p_{kj}(t_2) = \pi_i p_{ij}(t_1 + t_2).\)
        <ul>
          <li>The second equality follows from <strong>reversibility</strong>.</li>
          <li>The third equality follows from the <strong>Chapman-Kolmogorov theorem</strong>.</li>
          <li>This allows estimation of <strong>total branch length</strong> instead of individual times.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Log-Likelihood Formulation</strong>
    <ul>
      <li>The log-likelihood function is:
\(\ell(t, a, b, c, d, e, f, \pi_T, \pi_C, \pi_A) = \sum_i \sum_j n_{ij} \log(\pi_i p_{ij}(t)).\)</li>
      <li>After scaling, the <strong>distance</strong> is defined as:
\(d = -t \sum_i \pi_i q_{ii} = t.\)</li>
    </ul>
  </li>
</ol>

<ul>
  <li>Note that <strong>distance formulae are not MLEs</strong>.
    <ul>
      <li>Observed base frequencies are not MLEs of the base frequency parameters.</li>
      <li>All 16 site patterns have distinct probabilities in the likelihood function but are collapsed in distance formulae (e.g., TT, CC, AA, GG).</li>
      <li>Despite this simplification, distance formulae still approximate MLEs well.</li>
    </ul>
  </li>
  <li>Pairwise comparisons <strong>sum up branch lengths</strong> but may <strong>overestimate distances</strong>.</li>
  <li>Likelihood-based methods (<strong>ML, Bayesian</strong>) provide <strong>better phylogenetic estimates</strong>.</li>
</ul>

<h1 id="2-models-of-amino-acid-substitution-and-codon-substitution">2. Models of amino acid substitution and codon substitution</h1>

<h2 id="models-of-amino-acid-replacement">Models of amino acid replacement</h2>

<h3 id="empirical-models">Empirical models</h3>

<ul>
  <li>Empirical models:
    <ul>
      <li>The rates of substitution are estimated directly from observed sequence variations, without explicitly considering the biological processes that drive these substitutions.</li>
      <li>They are statistical and data-driven, without needing detailed knowledge of the underlying biological mechanisms.</li>
    </ul>
  </li>
  <li>Mechanistic models:
    <ul>
      <li>They are based on the underlying biological processes that drive sequence evolution.</li>
      <li>They offer more interpretative power, helping to understand the biological mechanisms and evolutionary forces that shape protein sequences.</li>
    </ul>
  </li>
  <li>Empirical models of amino acid substitution are <strong><em>all</em></strong> constructed by estimating the relative substitution rates between amino acids under the GTR model.</li>
  <li>Under GTR, $\pi_i q_{ij} = \pi_j q_{ji}$ and $\pi_i p_{ij}(t) = \pi_j p_{ji}(t)$, with $i,j \in {1,2,\ldots,20}$.</li>
  <li>$q_{ij}$ or $s_{ij}$ are the amino acid <em>exchangeabilities</em>.</li>
  <li>Dayhoff (1978) and JTT (1992): fixed estimates.</li>
  <li>Dayhoff+F, JTT+F, add 19 free parameters by replacing the $\pi_i$
in the empirical matrices by the frequencies estimated from the data.</li>
  <li>WAG (2001), LG (2008) etc. use maximum likelihood to estimate the exchangeabilities.</li>
  <li>BLOSUM (1992) focus on more conserved regions in protein families.</li>
  <li>BLOSUM62 is often considered roughly equivalent to PAM250.</li>
  <li>Some features in the estimated exchangeabilities are in fact as expected from the physico-chemical properties of amino acids. Also the larger number of substitution events needed to change between two amino acids, the lower the exchangeability. Evidence by comparing the exchangeabilities in normal proteins and mitochondrial proteins (codon table is different).</li>
</ul>

<h3 id="mechanistic-models">Mechanistic models</h3>

<ul>
  <li>Yang et al. (1998) implemented a few mechanistic models, taking account of e.g. different mutation rates between nucleotides, translation of the codon triplet into amino acid, and acceptance or rejection of the amino acid due to selective pressure on the protein.</li>
  <li>The improvement was not extraordinary, perhaps reflecting our poor understanding of which of the many chemical properties are most important and how they affect amino acid substitution rates</li>
</ul>

<h3 id="among-site-heterogeneity">Among-site heterogeneity</h3>

<ul>
  <li>Dayhoff+$\Gamma$, JTT+$\Gamma$, etc. are similar to the nucleotide models with among-site rate variation. $rQ$ is the rate matrix for a site.</li>
  <li>Recall that in the Gamma model, we delibrately set $\alpha = \beta$ so that the mean is 1. The higher the $\alpha$, the more concentrated the distribution is around the mean.</li>
  <li>Site-specific amino acid frequency parameters is also possible. For each (group of) site, this reflects how likely different amino acids are to appear (different patterns). However, this approach adds many parameters, making it challenging for maximum likelihood (ML) analysis.</li>
</ul>

<h2 id="estimation-of-distance-between-two-protein-sequences">Estimation of distance between two protein sequences</h2>

<h3 id="the-poisson-model">The Poisson model</h3>

<ul>
  <li>The number of substitutions over time $t$ can be a Poisson-disributed random variable under rate $\lambda$.</li>
  <li>Similar to JC69 model, the expected number of substitutions is $d = 19\lambda t$.</li>
  <li>Similarly, the expected distance is $\hat{d} = -\frac{19}{20}\log(1-\frac{20}{19}\hat{p})$. If $p &gt; \frac{19}{20}$, then $\hat{d} = \infty$.</li>
</ul>

<h3 id="empirical-models-1">Empirical models</h3>

<ul>
  <li>We deliberately set $-\sum_i \pi_i q_{ii} = 1$ so that $d = 1 \times t$, the mean distance is 1.</li>
  <li>Under GTR, the log-likelihood function is $\ell(t) = \sum_i \sum_j n_{ij} \log(\pi_i p_{ij}(t))$.</li>
  <li>We can also use $p$ distance, $p = 1 - \sum_i \pi_i p_{ii}(t)$, but this will lose information, nevertheless, should approximate the MLE well.</li>
</ul>

<h3 id="gamma-distance">Gamma distance</h3>

<ul>
  <li>Under something similar to JC69, adding a gamma distribution to the rate of substitution, we have $\hat{d} = \frac{19}{20} \alpha [(1 - \frac{20}{19}\hat{p})^{-\frac{1}{\alpha}} - 1]$. This is obtained by integration of the gamma distribution over the formula for $p$ distance (see formula 1.35).</li>
  <li>For empirical models, use ML to estimate the distance.</li>
</ul>

<h2 id="models-of-codon-substitution">Models of codon substitution</h2>

<h3 id="the-basic-model">The basic model</h3>

<ul>
  <li>The instantaneous rate matrix $Q$ is a $61 \times 61$ matrix.</li>
  <li>
\[q_{IJ} = \begin{cases}
  0, &amp; \text{if I and J differ at two or three codon positions,} \\
  \pi_J, &amp; \text{if I and J differ by a synonymous transversion,} \\
  \kappa\pi_J, &amp; \text{if I and J differ by a synonymous transition,} \\
  \omega\pi_J, &amp; \text{if I and J differ by a nonsynonymous transversion,} \\
  \omega\kappa\pi_J, &amp; \text{if I and J differ by a nonsynonymous transition.}
  \end{cases}\]
  </li>
  <li>$\omega$ is the nonsynonymous/synonymous rate ratio. If $\omega &gt; 1$, it indicates positive selection, if $\omega &lt; 1$, it indicates purifying selection.</li>
  <li>Fequal model: $\pi_i = 1/61$.</li>
  <li>F1x4 model, F3x4 model, and F61 model: $\pi_i$ are estimated from the data.</li>
  <li>The rate matrix $Q$ time-reversible as it meets the detailed balance condition.</li>
</ul>

<h3 id="variations-and-extensions">Variations and extensions</h3>

<ul>
  <li>The Muse-Gaut model (1994) is a generalization of the basic model.
    <ul>
      <li>Simialr to F3x4 with omega?</li>
    </ul>
  </li>
  <li>The mutation-selection (FMutSel) model.
    <ul>
      <li>mutation bias: $\mu_{ij} = a_{ij} \pi^*_j$.</li>
      <li>selection: $S_{IJ} = f_J - f_I$.</li>
      <li>The probability of fixation of the mutation is $P_{IJ} = \frac{2S_{IJ}}{1 - e^{-2NS_{IJ}}}$.</li>
    </ul>
  </li>
  <li>The $\omega$ ratio does not have to be a single parameter, it can be modelled by physico-chemical properties, e.g. $\omega_{IJ} = ae^{-bd_{IJ}}$, where $d_{IJ}$ is the chemical distance between amino acids.</li>
  <li>Or you can model $\omega$ by a few pre-specified categories of nonsynonymous substitutions.</li>
  <li>Allowing double or triple mutations should be more realistic. It is common to observe ‘synonymous’ differences between the two sets of serine codons (TCN and AGY) which cannot exchange by a single nucleotide mutation. Some people argue this is because separate lines of descent rather than multiple mutations.</li>
</ul>

<h2 id="estimation-of-d_s-and-d_n">Estimation of $d_S$ and $d_N$</h2>

<ul>
  <li>Recall that the evolutionary distance $d$ focuses on the entire sequence, now we want to separate the distance by synonymous and nonsynonymous mutations, then we get $d_S$ and $d_N$.</li>
  <li>Definitions: The number of synonymous/nonsynonymous substitutions per synonymous/nonsynonymous site.</li>
  <li>Methods: Counting and ML.</li>
</ul>

<h3 id="counting-methods">Counting methods</h3>

<ul>
  <li>Three steps:
    <ol>
      <li>Count the number of synonymous and nonsynonymous sites.</li>
      <li>Count the number of synonymous and nonsynonymous differences.</li>
      <li>Calculate the proportions of differences and correct for multiple hits.</li>
    </ol>
  </li>
  <li>A basic model is Nei and Gojobori (1986) (NG86), which used equal weights for all codon positions.</li>
</ul>

<h4 id="counting-sites-s-and-n">Counting sites ($S$ and $N$)</h4>

<ul>
  <li>Introducing NG86 model, then relax the model with unequal transition and transversion rates and
unequal codon usage. Different methods often produce very different estimates.</li>
  <li>There are three sites in a codon, and nine immediate neighbors.</li>
  <li>To calculate the synonymous and nonsynonymous sites, we need to multiply the synonymous/nonsynonymous probabilities (from the nine neighbors) by 3 sites. (Check Table 2.5)</li>
</ul>

<h4 id="counting-differences-s_d-and-n_d">Counting differences ($S_d$ and $N_d$)</h4>

<ul>
  <li>If two codons only differ by one nucleotide, then it is trivial to count the synonymous and nonsynonymous differences. (Check Table 2.6)</li>
  <li>If two codons differ by two or three nucleotides, there exist two or six possible paths to reach the codon, respectively.</li>
  <li>Weighting the paths needs knowledge.</li>
</ul>

<h4 id="correcting-for-multiple-hits">Correcting for multiple hits</h4>

<ul>
  <li>We now have the $p$ distance, $p_S = S_d/S$ and $p_N = N_d/N$.</li>
  <li>The Jukes-Cantor correction is $d_S = -\frac{3}{4}\log(1 - \frac{4}{3}p_S)$ and $d_N = -\frac{3}{4}\log(1 - \frac{4}{3}p_N)$.</li>
  <li>This is logically flawed (Lewontin 1989), as JC69 assumes equal rates of substitution for all three other nucleotides, but when focusing on synonymous/nonsynonymous sites only, each nucleotide does not have <em>three</em> other nucleotides to change into.</li>
</ul>

<h4 id="transitiontransversion-rate-difference-and-codon-usage">Transition–transversion rate difference and codon usage</h4>

<ul>
  <li>From codon table, we see transitions at the third codon positions are more likely to be synonymous than transversions are. Therefore, a higher transition/transversion rate can lead to more synonymous substitutions, not necessarily due to selection. Ignoring this can lead to underestimation of $S$ (not $S_d$) and overestimation of $N$, and overestimation of $d_S$ and underestimation of $d_N$.</li>
  <li>The below methods classified codon positions into <em>nondegenerate, two-fold degenerate, and four-fold degenerate sites</em>, based on the number of synonymous substitutions possible. Note that some of the codons in fact do not fall into these categories, different methods may have different ways to deal with them.</li>
  <li>LWL85 Method (Li, Wu, and Luo, 1985):
    <ul>
      <li>Counts two-fold degenerate sites as 1/3 synonymous and 2/3 nonsynonymous under the assumption of equal mutation rates.</li>
      <li>The distances are calculated using the total numbers of sites in different degeneracy classes and the estimated transition and transversion counts.</li>
    </ul>
  </li>
  <li>LPB93 Method (Li, Pamilo, and Bianchi, 1993):
    <ul>
      <li>Adjusts for transition–transversion rate bias (which was ignored by 1/3 and 2/3 approximation in LWL85).</li>
      <li>Uses the transition distance at four-fold sites to estimate $d_S$​ and an averaged transversion distance at nondegenerate sites for $d_N$.</li>
      <li>Assuming that the transition rate is the same at the two-fold and four-fold sites; the transversion rate is the same at the nondegenerate and two-fold sites.</li>
    </ul>
  </li>
  <li>LWL85m Method:
    <ul>
      <li>A refinement of LWL85 that replaces the 1/3 assumption with an estimated proportion ($\rho$) of two-fold degenerate sites that are synonymous.</li>
      <li>Uses the ratio of transition and transversion distances at four-fold sites to estimate $\kappa$ (transition/transversion rate ratio).</li>
    </ul>
  </li>
  <li>Alternative Approaches:
    <ul>
      <li>Ina (1995) proposed not partitioning sites by codon degeneracy but instead weighting transitions and transversions based on neighboring codons (See Table 2.5).</li>
      <li>Consideration of <em>unequal codon frequencies</em> was introduced by Yang and Nielsen (2000), as previous models assumed equal codon frequencies, which is unrealistic.</li>
    </ul>
  </li>
  <li>Example 2.2 is useful for understanding the above calculations.</li>
  <li>In Table 2.8, we see S are larger in LWL85m and Ina95, as they accounted for underestimation of S by considering ts/tv ratio, but <strong>ironically</strong>, they led to even more biased results, because they did not consider codon usage bias at the same time.</li>
</ul>

<h3 id="maximum-likelihood-methods">Maximum likelihood methods</h3>

<ul>
  <li>Under the <a href="#the-basic-model">basic model for codon substitution</a>, which is a GTR again.</li>
  <li>Parameters estimated:
    <ul>
      <li>$t$ (sequence divergence time or distance),</li>
      <li>$\kappa$ (transition/transversion rate ratio),</li>
      <li>$\omega$ (nonsynonymous/synonymous rate ratio),</li>
      <li>Codon frequencies (either fixed or estimated from the data), can be Fequal, F1x4, F3x4, or F61.</li>
    </ul>
  </li>
  <li>$d_S$ and $d_N$ are then computed based on these ML estimates.</li>
  <li>Refer to Table 2.8, the Fequal with $\kappa=1$ is similar to NG86, and Fequal with $\kappa$ estimated is similar to LWL85, LPB93 and Ina95.</li>
  <li>Note that incorporating the transition–transversion rate difference has had much greater effect on the numbers of sites ($S$ and $N$) than on the numbers of substitutions ($S_d$ and $N_d$).</li>
</ul>

<h3 id="comparing-methods">Comparing methods</h3>

<ul>
  <li>Estimation Bias and Model Effects:
    <ol>
      <li>Ignoring Transition–Transversion Rate Differences:
        <ul>
          <li>Leads to underestimation of synonymous sites ($S$) and overestimation of nonsynonymous sites ($N$).</li>
          <li>Results in overestimation of $d_S$ and underestimation of $\omega = d_N/d_S$.</li>
        </ul>
      </li>
      <li>Ignoring Unequal Codon Usage:
        <ul>
          <li>Has the opposite effect compared to ignoring transition–transversion rates.</li>
          <li>Leads to overestimation of $S$ and underestimation of $d_S$, which in turn overestimates $ω$.</li>
          <li>Codon frequency biases can sometimes override the effects of transition–transversion biases.</li>
          <li>The NG86 method, which ignores both transition–transversion differences and codon usage, sometimes produces more reliable estimates than models that only accommodate transition–transversion biases but ignore codon usage.</li>
        </ul>
      </li>
      <li>Effect of Model Assumptions on Similar Sequences:
        <ul>
          <li>When sequences are highly similar, different methods can produce very different estimates.</li>
          <li>Unlike nucleotide models, where distance estimates converge at low sequence divergences, codon-based models remain highly sensitive to assumptions.</li>
        </ul>
      </li>
      <li>Importance of Model Assumptions:
        <ul>
          <li>At low or moderate sequence divergences, different (counting or ML) methods produce similar results if they share the same assumptions.</li>
          <li>However, different counting/likelihood methods produce highly variable results because of differnt assumptions (e.g., $\kappa = 1?$ and codon bias).</li>
        </ul>
      </li>
    </ol>
  </li>
  <li>Advantages of the Likelihood Method Over Counting Methods:
    <ol>
      <li>Conceptual simplicity
        <ul>
          <li>Counting methods struggle with different transition/transversion rates and <strong>unequal codon frequencies</strong>.</li>
          <li>Some counting methods <strong>attempt to estimate $\kappa$</strong>, but this is challenging.</li>
          <li>Counting methods rely on <strong>nucleotide-based corrections for multiple hits</strong>, which can be logically flawed (mentioned under formula 2.15).</li>
          <li>Likelihood methods <strong>incorporate these complexities naturally</strong> without requiring correction formulas.</li>
          <li>No need for <strong>manual classification of synonymous vs. nonsynonymous substitutions</strong>, as these are <strong>inferred probabilistically</strong>.</li>
        </ul>
      </li>
      <li>Easier to Incorporate Realistic Codon Models
        <ul>
          <li>Likelihood methods can <strong>incorporate sophisticated codon substitution models</strong>.</li>
          <li>Example: <strong>GTR-style mutation models</strong> or <strong>HKY85-type models</strong> can be used in likelihood calculations.</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h3 id="more-distances-and-interpretation-of-the-d_nd_s-ratio">More distances and interpretation of the $d_N/d_S$ ratio</h3>

<h4 id="more-distances-based-on-the-codon-model">More distances based on the codon model</h4>
<ul>
  <li>Additional Distance Measures in the Codon Model
    <ul>
      <li>Since we can get the expected number of substitutions from <strong>codon $i$ to codon $j$</strong> over time $t$ is given by $\pi_i q_{ij} t$.</li>
      <li>We can calculate many other distances, not limited to $d_N$ and $d_S$, based on:
        <ul>
          <li>Transition vs. transversion substitutions.</li>
          <li>Codon position-specific changes (first, second, third codon positions).</li>
          <li>Conservative or radical amino acid changes, etc.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Distances at Different Codon Positions
    <ul>
      <li>Distances at the first, second, and third codon positions can be calculated separately:
        <ul>
          <li>$d_{1A}, d_{2A}, d_{3A}$ → <strong>After</strong> selection on the protein.</li>
          <li>$d_{1B}, d_{2B}, d_{3B}$ → <strong>Before</strong> selection on the protein (fixing $\omega = 1$).</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Distance $d_4$ (Four-Fold Degenerate Sites)
    <ul>
      <li><strong>$d_4$</strong> represents substitutions at <strong>four-fold degenerate sites</strong> in the third codon position.</li>
      <li>Used as an <strong>approximation of the neutral mutation rate</strong>.</li>
    </ul>
  </li>
</ul>

<h3 id="estimation-of-d_s-and-d_n-in-comparative-genomics">Estimation of $d_S$ and $d_N$ in comparative genomics</h3>

<ul>
  <li>Time Scale Matters
    <ul>
      <li>Estimating $d_S$ and $d_N$ requires a balance—sequences should be <strong>neither too similar nor too divergent</strong>.</li>
      <li>If species are <strong>too distantly related</strong>, <strong>synonymous substitutions may reach saturation</strong>, making $d_S$ unreliable.</li>
      <li>Estimates of $d_S &gt; 3$ should be treated with caution, as high divergence leads to indistinguishable evolutionary distances.</li>
    </ul>
  </li>
  <li>Solutions for High Divergence
    <ul>
      <li>A <strong>phylogenetic approach</strong> can break long evolutionary distances into <strong>shorter branches</strong> by including multiple species.</li>
    </ul>
  </li>
  <li>Issues with Low Divergence
    <ul>
      <li>When sequences are <strong>too similar</strong> (e.g., within the same species or bacterial strains), <strong>$d_N/d_S$ estimates become unreliable</strong>.</li>
      <li><strong>Observed bias:</strong> $d_N/d_S$ tends to <strong>decrease with increasing divergence</strong>, possibly due to <strong>MLE biases</strong> and <strong>correlations between parameter estimates</strong>.</li>
      <li>In <strong>within-population comparisons</strong>, <strong>deleterious nonsynonymous mutations</strong> may persist longer before being removed by selection, inflating $d_N/d_S$ at short timescales.</li>
    </ul>
  </li>
</ul>

<h1 id="3-phylogenetic-reconstruction-overview">3. Phylogenetic reconstruction: overview</h1>

<h2 id="31-tree-concepts">3.1 Tree concepts</h2>

<h3 id="terminology">Terminology</h3>

<ul>
  <li>Nodes (vertices) and branches (edges).</li>
  <li>Molecular clock: the rate of evolution is constant over time; Midpoint rooting: the root is placed at the midpoint of the longest path between two tips.</li>
  <li>Newick format: <code class="language-plaintext highlighter-rouge">(A:0.1,B:0.2,(C:0.3,D:0.4):0.5)</code>; Nexus format: <code class="language-plaintext highlighter-rouge">#NEXUS; BEGIN TREES; TREE tree1 = (A:0.1,B:0.2,(C:0.3,D:0.4):0.5); END</code>;</li>
  <li>Bifurcating and multifurcating trees; fully resolved and polytomous trees.</li>
  <li>The total number of possible topologies of a n-tip rooted tree: $\frac{(2n-3)!}{2^{n-2}(n-2)!}$ (this is not hard to derive).</li>
  <li><em>Labelled histories</em> (ranked trees): also considering the order of parallel internal nodes. We use coalescent process to calculate the total number of possible labelled histories for a n-tip tree: $\frac{n!(n-1)!}{2^{n-1}}$.</li>
  <li><em>Partition distance</em>, also called <em>Robinson-Foulds distance</em>, is the number of bipartitions that are present in one tree but not in the other. It is a measure of the <strong>topological difference</strong> between two trees.</li>
  <li>The <em>Kuhner-Felsenstein distance</em> (1994) is a generalization of the Robinson-Foulds distance that considers branch lengths, by summing the absolute differences in branch lengths for each bipartition.</li>
  <li>Strict-consensus tree and majority-rule consensus tree.</li>
  <li>Monophyly and two types of non-monophyly: paraphyly (contains an ancestor but only some of its descendants) and polyphyly (contains various organisms with no recent common ancestor).</li>
  <li>Gene tree and species tree can mismatch under a <strong>relaxed</strong> molecular clock, if the evolutionary rate varies among lineages. As the distance does not reflect the <strong>relatedness</strong> of the species.</li>
  <li>The mismatch can also happen even under a <strong>fixed</strong> molecular clock, if the ancestral polymorphism is high and cause incomplete lineage sorting; and if with gene duplication and loss, or lateral (horizontal) gene transfer (LGT).</li>
</ul>

<h3 id="classification-of-tree-reconstruction-methods">Classification of tree reconstruction methods</h3>
<ul>
  <li><em>Distance-based</em> methods (e.g., Neighbor-Joining) convert sequences into a matrix of pairwise distances, then cluster the taxa to form a tree.</li>
  <li><em>Character-based</em> methods (e.g., Maximum Parsimony, Maximum Likelihood, Bayesian) work directly with the alignment, examining each nucleotide or amino acid position.</li>
  <li><strong>Model-based</strong> methods (like Maximum Likelihood and Bayesian approaches) explicitly use substitution models to account for how sequences evolve. <strong>Parsimony</strong> methods do not specify a detailed evolutionary model but instead look for the tree requiring the fewest changes. <strong>Distance-based</strong> methods often assume simpler models to correct raw pairwise distances.</li>
</ul>

<h2 id="32-exhaustive-and-heuristic-tree-search-for-optimality-based-methods">3.2 Exhaustive and Heuristic Tree Search (for Optimality-Based Methods)</h2>

<h3 id="321-exhaustive-tree-search">3.2.1 Exhaustive Tree Search</h3>
<ul>
  <li>Calculate score for <em>every</em> possible tree. Guaranteed to find the best tree.</li>
  <li>Feasible only for small datasets (e.g., &lt; 10-12 taxa) due to the vast number of trees.</li>
  <li>Branch-and-bound can speed up exhaustive search for parsimony but not significantly for likelihood.</li>
</ul>

<h3 id="322-heuristic-tree-search">3.2.2 Heuristic Tree Search</h3>
<p>Used when exhaustive search is impossible. Not guaranteed to find the optimal tree.</p>
<ul>
  <li><strong>Hierarchical Cluster Algorithms:</strong>
    <ul>
      <li><strong>Stepwise/Sequential Addition (Agglomerative):</strong> Add taxa one by one to a growing tree, choosing the best local placement at each step (Fig. 3.13). Order of addition matters; random addition orders run multiple times are common.</li>
      <li><strong>Star Decomposition (Divisive):</strong> Start with a star tree. Iteratively join the pair of taxa that gives the best improvement to the tree score, reducing the central polytomy until fully resolved (Fig. 3.14).</li>
    </ul>
  </li>
  <li><strong>Tree Rearrangement / Branch Swapping (Hill-Climbing) (3.2.3):</strong>
    <ul>
      <li>Start with an initial tree (random, NJ, or from cluster methods).</li>
      <li>Generate “neighbor” trees by local perturbations.</li>
      <li>Move to the neighbor with the best score. Repeat until no improvement.</li>
      <li><strong>Types of Swaps (increasing neighborhood size and computational cost):</strong>
        <ul>
          <li><strong>Nearest Neighbor Interchange (NNI):</strong> Swaps subtrees around an internal branch (Fig. 3.15). Each internal branch gives 2 NNI neighbors. Total $2(n-3)$ neighbors.</li>
          <li><strong>Subtree Pruning and Regrafting (SPR):</strong> Prune a subtree and reattach it to any other branch in the remaining tree (Fig. 3.16a).</li>
          <li><strong>Tree Bisection and Reconnection (TBR):</strong> Break an internal branch to get two subtrees. Reconnect them by joining any branch from one to any branch of the other (Fig. 3.16b). Generates more neighbors than SPR.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Local Peaks in Tree Space (3.2.4):</strong> Heuristic searches can get stuck in local optima (a tree better than its immediate neighbors, but not globally best) (Fig. 3.17, 3.18). Larger tree space for more taxa makes this a bigger problem.</li>
</ul>

<h3 id="325-stochastic-tree-search">3.2.5 Stochastic Tree Search</h3>
<p>Algorithms that can escape local optima by allowing occasional “downhill” moves.</p>
<ul>
  <li><strong>Simulated Annealing:</strong> Modifies objective function early on (“heating”) to allow more exploration, gradually “cools” to greedy uphill search.</li>
  <li><strong>Genetic Algorithm:</strong> Maintains a “population” of trees, uses “mutation” and “recombination” to generate new trees, “fitness” (optimality score) determines survival.</li>
  <li><strong>Bayesian MCMC:</strong> Statistical approach producing point estimates and uncertainty measures. Allows downhill moves based on probabilities.</li>
</ul>

<h2 id="33-distance-matrix-methods">3.3 Distance Matrix Methods</h2>

<p>Two steps: 1. Calculate pairwise distances. 2. Reconstruct tree from distance matrix.</p>

<h3 id="331-least-squares-ls-method">3.3.1 Least-Squares (LS) Method</h3>
<ul>
  <li>Estimates branch lengths to minimize sum of squared differences between observed ($d_{ij}$) and tree-path (${\delta}<em>{ij}$) distances: $S = \sum</em>{i&lt;j} (d_{ij} - {\delta}_{ij})^2$. (Eq 3.5)</li>
  <li>The tree with the minimum $S$ is the LS tree.</li>
  <li><strong>Ordinary Least Squares (OLS):</strong> Assumes errors in $d_{ij}$ are independent and have equal variance. Usually incorrect (larger distances have larger variance; shared branches induce correlations).</li>
  <li><strong>Weighted Least Squares (WLS):</strong> Weights terms by $w_{ij} = 1/\text{var}(d_{ij})$ or $w_{ij} = 1/d_{ij}^2$ (Fitch &amp; Margoliash). Generally better than OLS.</li>
  <li><strong>Generalized Least Squares (GLS):</strong> Accounts for correlations (covariances) as well. Computationally intensive, rarely used.</li>
  <li>Branch lengths can be constrained to be non-negative (more realistic but computationally harder).</li>
</ul>

<h3 id="332-minimum-evolution-me-method">3.3.2 Minimum Evolution (ME) Method</h3>
<ul>
  <li>Selects the tree with the minimum “tree length” (sum of all branch lengths). Branch lengths often estimated by LS.</li>
  <li>Plausible heuristic: true tree likely involves minimal total evolution.</li>
  <li>Many variations based on how branch lengths are estimated (OLS, WLS, GLS) and how tree length is defined (e.g., sum of all, only positive, or absolute values of branch lengths). (Table 3.5)</li>
</ul>

<h3 id="333-neighbour-joining-nj-method-saitou--nei-1987">3.3.3 Neighbour-Joining (NJ) Method (Saitou &amp; Nei, 1987)</h3>
<ul>
  <li>Divisive cluster algorithm; does not assume clock; produces unrooted trees. Fast and widely used.</li>
  <li>Starts with a star tree. Iteratively joins a pair of nodes $(i,j)$ that minimizes:
$Q_{ij} = (r-2)d_{ij} - \sum_{k \neq i,j} (d_{ik} + d_{jk})$ (where $r$ is current number of nodes). (Eq 3.8)</li>
  <li>The joined pair is replaced by a new internal node, distances updated, process repeats.</li>
  <li><strong>Justification:</strong> NJ is an ME method, but it minimizes a specific tree length definition by Pauplin (2000) (Eq 3.13), not the OLS tree length. This “balanced ME” criterion often performs better than OLS-based ME.</li>
  <li><strong>BIONJ, WEIGHBOR:</strong> Modifications incorporating variance/covariance of distances, can improve accuracy.</li>
</ul>

<h2 id="34-maximum-parsimony-mp">3.4 Maximum Parsimony (MP)</h2>

<h3 id="341-brief-history">3.4.1 Brief History</h3>
<p>Originated from minimizing changes for discrete morphological data, later applied to molecular data.</p>

<h3 id="342-counting-minimum-changes">3.4.2 Counting Minimum Changes</h3>
<ul>
  <li><strong>Site Length:</strong> Minimum changes at one site on a given tree.</li>
  <li><strong>Tree Length/Score:</strong> Sum of site lengths over all sites.</li>
  <li><strong>Most Parsimonious Tree:</strong> The tree with the smallest tree length.</li>
  <li><strong>Ancestral Reconstruction:</strong> Assigning states to internal nodes. The one yielding minimum changes is the Most Parsimonious Reconstruction (MPR). Fitch (1971b) and Hartigan (1973) algorithms find this.</li>
  <li><strong>Informative Sites for Parsimony:</strong> Must have at least two character states, each appearing at least twice (e.g., xxyy, xyxy, xyyx for 4 taxa). Constant and singleton sites are uninformative. <em>This concept is specific to parsimony.</em></li>
</ul>

<h3 id="343-weighted-parsimony-and-dynamic-programming-sankoff-1975">3.4.3 Weighted Parsimony and Dynamic Programming (Sankoff, 1975)</h3>
<ul>
  <li>Assigns different costs (weights) to different types of changes (e.g., transitions vs. transversions).</li>
  <li><strong>Sankoff’s Algorithm:</strong> A dynamic programming approach.
    <ul>
      <li>For each node $i$ and each possible state $x$ at that node, calculate $S_i(x)$: minimum cost for the subtree defined by node $i$ (including its ancestral branch), given state $x$ at its parent.</li>
      <li>Proceeds from tips towards the root.</li>
      <li>For a tip $i$: $S_i(x)$ is simply the cost of change from parent state $x$ to observed tip state.</li>
      <li>For an internal node $i$ with parent state $x$ and daughter nodes $j, k$:
$S_i(x) = \min_y [c(x,y) + S_j(y) + S_k(y)]$ (Eq 3.14), where $y$ is the state at node $i$.</li>
      <li>The minimum cost for the whole tree is found at the root (Eq 3.15).</li>
      <li>A second “down pass” (traceback) identifies the states at internal nodes that achieve this minimum cost. (Fig 3.24)</li>
    </ul>
  </li>
</ul>

<h3 id="344-probabilities-of-ancestral-states">3.4.4 Probabilities of Ancestral States</h3>
<p>Parsimony reconstructs ancestral states but doesn’t give probabilities. This requires a model of evolution (discussed in likelihood chapter).</p>

<h3 id="345-long-branch-attraction-lba">3.4.5 Long-Branch Attraction (LBA)</h3>
<ul>
  <li>Parsimony’s major inconsistency problem (Felsenstein, 1978b).</li>
  <li>If the true tree has two long branches separated by a short internal branch (Fig 3.25a), parsimony tends to incorrectly group the two long branches (Fig 3.25b).</li>
  <li>Due to parsimony’s failure to correct for multiple (parallel/convergent) changes on long branches.</li>
</ul>

<h1 id="4-maximum-likelihood-methods">4. Maximum likelihood methods</h1>

<p>This chapter focuses on the calculation of likelihood for multiple sequences on a phylogenetic tree. It builds upon Markov chain theory and ML estimation principles from Chapter 1.</p>

<h2 id="41-introduction">4.1 Introduction</h2>

<p>Two main applications of ML in phylogenetics:</p>
<ol>
  <li><strong>Parameter Estimation &amp; Hypothesis Testing (Fixed Topology):</strong> Estimating parameters of an evolutionary model (e.g., branch lengths, substitution rates) and testing hypotheses about the evolutionary process, assuming the tree topology is known. ML provides a powerful and flexible framework for this.</li>
  <li><strong>Tree Topology Inference:</strong> Maximizing the log-likelihood for each candidate tree by optimizing its parameters. The tree with the highest optimized log-likelihood is chosen as the best estimate. This is a model comparison problem.</li>
</ol>

<h2 id="42-likelihood-calculation-on-tree">4.2 Likelihood Calculation on Tree</h2>

<h3 id="421-data-model-tree-and-likelihood">4.2.1 Data, Model, Tree, and Likelihood</h3>
<ul>
  <li><strong>Data ($X$):</strong> An alignment of $s$ sequences, each $n$ sites long. $x_{jh}$ is the $h^{th}$ nucleotide in the $j^{th}$ sequence. $x_h$ is the $h^{th}$ column (site) in the alignment.</li>
  <li><strong>Model:</strong> e.g., K80 model. Assumes sites evolve independently and lineages evolve independently.</li>
  <li><strong>Tree:</strong> (e.g., Fig 4.1 for 5 species). Tips are observed sequences. Internal nodes are ancestral. Branch lengths ($t_i$) are expected number of substitutions per site.</li>
  <li><strong>Parameters ($\theta$):</strong> Collectively, all branch lengths and substitution model parameters (e.g., $\kappa$ for K80).</li>
  <li><strong>Likelihood of Alignment:</strong> Due to site independence,
$L(\theta) = f(X\vert \theta) = \prod_{h=1}^{n} f(x_h\vert \theta)$ (Eq 4.1)</li>
  <li><strong>Log-Likelihood:</strong>
$l(\theta) = \log{L(\theta)} = \sum_{h=1}^{n} \log{f(x_h\vert \theta)}$ (Eq 4.2)</li>
  <li><strong>Likelihood for a Single Site ($f(x_h\vert \theta)$):</strong> Sum over all possible states ($x_0, x_6, x_7, x_8$ for internal nodes 0, 6, 7, 8 in Fig 4.1) of extinct ancestors.
$f(x_h\vert \theta) = \sum_{x_0} \sum_{x_6} \sum_{x_7} \sum_{x_8} \left[ \pi_{x_0} P_{x_0x_6}(t_6) P_{x_6x_7}(t_7) P_{x_7T}(t_1) P_{x_7C}(t_2) P_{x_6A}(t_3) P_{x_0x_8}(t_8) P_{x_8C}(t_4) P_{x_8C}(t_5) \right]$ (Eq 4.3)
where $\pi_{x_0}$ is the prior probability of state $x_0$ at the root (e.g., $1/4$), and $P_{uv}(t)$ is the transition probability from state $u$ to $v$ along a branch of length $t$.</li>
</ul>

<h3 id="422-the-pruning-algorithm-felsenstein-1973b-1981">4.2.2 The Pruning Algorithm (Felsenstein, 1973b, 1981)</h3>
<p>Efficiently calculates $f(x_h\vert \theta)$ by avoiding redundant computations (variant of dynamic programming).</p>
<ul>
  <li><strong>Horner’s Rule Principle:</strong> Factor out common terms to reduce computations (e.g., sum over $x_7$ before $x_6$, and sum over $x_6, x_8$ before $x_0$ in Eq 4.4).</li>
  <li><strong>Conditional Probability $L_i(x_i)$:</strong> Probability of observing data at tips descendant from node $i$, <em>given</em> nucleotide $x_i$ at node $i$.
    <ul>
      <li><strong>If node $i$ is a tip:</strong> $L_i(x_i) = 1$ if $x_i$ is the observed nucleotide at that tip, $0$ otherwise.</li>
      <li><strong>If node $i$ is an interior node with daughter nodes $j$ and $k$:</strong>
$L_i(x_i) = \left[ \sum_{x_j} P_{x_ix_j}(t_j)L_j(x_j) \right] \times \left[ \sum_{x_k} P_{x_ix_k}(t_k)L_k(x_k) \right]$ (Eq 4.5)
This calculates the probability of descendant data given $x_i$ by summing over all possible states at daughters $j$ and $k$.</li>
    </ul>
  </li>
  <li><strong>Traversal:</strong> Calculation proceeds from tips towards the root (post-order traversal). Each node is visited only after its descendants.</li>
  <li><strong>Final Likelihood at Root (node 0):</strong>
$f(x_h\vert \theta) = \sum_{x_0} \pi_{x_0} L_0(x_0)$ (Eq 4.6)</li>
  <li><strong>Example 4.1 (Fig 4.2):</strong> Numerical illustration using K80, fixed branch lengths, and $\kappa=2$. Shows calculation of $L_i(x_i)$ vectors up the tree.</li>
  <li><strong>Savings on Computation (4.2.2.2):</strong>
    <ul>
      <li>Algorithm scales linearly with number of species (nodes).</li>
      <li>Transition probability matrices $P(t)$ computed once per branch length.</li>
      <li>Identical site patterns: compute likelihood once.</li>
      <li>Partial site patterns (subtrees) can be collapsed if data below them is identical.</li>
    </ul>
  </li>
  <li><strong>Hadamard Conjugation (4.2.2.3):</strong> Alternative method for specific models (e.g., binary characters, Kimura’s 3ST) to transform branch lengths to site pattern probabilities and vice versa. Useful for theoretical analysis on small trees.</li>
</ul>

<h3 id="423-time-reversibility-root-and-molecular-clock">4.2.3 Time Reversibility, Root, and Molecular Clock</h3>
<ul>
  <li><strong>Time Reversibility ($\pi_i P_{ij}(t) = \pi_j P_{ji}(t)$):</strong> Common in phylogenetic models.
    <ul>
      <li><strong>Pulley Principle (Felsenstein, 1981):</strong> The root can be moved arbitrarily along any branch of the tree without changing the likelihood.</li>
      <li>This means for unrooted trees (branches have own rates), only the sum of branches like $t_6+t_8$ in Fig 4.3 is estimable, not $t_6$ and $t_8$ individually. The model is overparameterized.</li>
    </ul>
  </li>
  <li><strong>Molecular Clock:</strong>
    <ul>
      <li>If assumed (single rate, tips equidistant from root), the root <em>can</em> be identified.</li>
      <li>Parameters are ages of ancestral nodes (Fig 4.4a).</li>
      <li>Pulley principle can still simplify calculations (Fig 4.4b, Eq 4.8).</li>
    </ul>
  </li>
</ul>

<h3 id="425-amino-acid-codon-and-rna-models">4.2.5 Amino Acid, Codon, and RNA Models</h3>
<ul>
  <li>Pruning algorithm applies directly.</li>
  <li>Difference: State space size (4 for nucleotides, 20 for aa, 61 for codons).</li>
  <li>Likelihood computation is more expensive for aa/codon models.</li>
  <li><strong>RNA dinucleotide models (16 states):</strong> For stem regions, model co-evolution of complementary bases. Loop regions can be problematic.</li>
</ul>

<h3 id="426-missing-data-sequence-errors-and-alignment-gaps">4.2.6 Missing Data, Sequence Errors, and Alignment Gaps</h3>
<ul>
  <li><strong>General Theory (4.2.6.1):</strong>
    <ul>
      <li>$X$: observed data (with ambiguities, errors).</li>
      <li>$Y$: unknown true alignment (fully determined).</li>
      <li>$L(\theta, \gamma) = f(X\vert\theta, \gamma) = \sum_Y f(Y\vert\theta) f(X\vert Y, \gamma)$ (Eq 4.9)</li>
      <li>where $\gamma$ are parameters of the error model $f(X\vert Y, \gamma)$.</li>
      <li>Assuming site independence for errors:
$L(\theta, \gamma) = \prod_h \left[ \sum_{y_h} f(y_h\vert\theta) f(x_h\vert y_h, \gamma) \right]$ (Eq 4.10)</li>
      <li>Modified Pruning: Set tip vector $L_i(y)$ at tip $i$ with observed state $x_i$ to $f(x_i\vert y_i, \gamma)$ for each true state $y$. In NC-IUB notation, $L_i(y) = \epsilon^{(i)}_{yx_i}$. (Eq 4.11)</li>
    </ul>
  </li>
  <li><strong>Ambiguities and Missing Data (4.2.6.2):</strong> Assuming no sequence errors.
    <ul>
      <li>If $x_i$ is an ambiguous code (e.g., Y for T or C), set $L_i(y)=1$ if $y$ is compatible with $x_i$, and 0 otherwise. (e.g., for Y, $L_i = (1,1,0,0)$). This is the common practice.</li>
      <li>This approach implicitly assumes the probability of observing an ambiguity (e.g., Y) is the same whether the true base was T or C. If not, it’s incorrect.</li>
    </ul>
  </li>
  <li><strong>Sequence Errors (4.2.6.3):</strong> Model error as a $4 \times 4$ transition matrix $E = {\epsilon_{yx}}$ where $\epsilon_{yx}$ is $P(\text{observe } x \vert \text{true } y)$. The tip vector $L_i$ becomes the relevant column of $E$.</li>
  <li><strong>Alignment Gaps (4.2.6.4):</strong> Most difficult.
    <ul>
      <li>Models of indels are complex and computationally intensive.</li>
      <li><strong>Ad hoc treatments (for $f(Y\vert\theta)$, ignoring $f(X\vert Y, \gamma)$):</strong>
        <ol>
          <li>Treat gap as 5th state: Problematic (treats multi-site indel as multiple events).</li>
          <li>Delete columns with any gaps: Information loss.</li>
          <li>Treat gaps as missing data (N or ?): Problematic (gap means nucleotide doesn’t exist, not that it’s unknown).</li>
        </ol>
      </li>
      <li>Common practice: Remove unreliable alignment regions, especially for divergent sequences.</li>
    </ul>
  </li>
</ul>

<h2 id="43-likelihood-calculation-under-more-complex-models">4.3 Likelihood Calculation Under More Complex Models</h2>

<p>Models assuming all sites evolve at the same rate with the same pattern are unrealistic.</p>

<h3 id="431-mixture-models-for-variable-rates-among-sites">4.3.1 Mixture Models for Variable Rates Among Sites</h3>
<ul>
  <li><strong>4.3.1.1 Discrete-Rate Model:</strong>
    <ul>
      <li>Sites fall into $K$ classes, class $k$ has rate $r_k$ with probability $p_k$.</li>
      <li>Constraints: $\sum p_k = 1$, average rate $\sum p_k r_k = 1$.</li>
      <li>$2(K-1)$ free parameters. Substitution matrix at site is $r_k Q$.</li>
      <li>Likelihood at a site: $f(x_h\vert\theta) = \sum_{k=1}^K p_k \times f(x_h\vert r=r_k; \theta)$ (Eq 4.15)
(Calculate likelihood $K$ times, once for each rate category, then average).</li>
      <li>$K$ should not exceed 3 or 4 in practice; parameters hard to interpret.</li>
      <li><strong>Invariant-Site Model (+I):</strong> Special case, $K=2$. Rate $r_0=0$ (invariable) with prob $p_0$, rate $r_1=1/(1-p_0)$ with prob $1-p_0$. One parameter $p_0$. (Eq 4.17)</li>
    </ul>
  </li>
  <li><strong>4.3.1.2 Gamma-Rate Model (+$\Gamma$):</strong>
    <ul>
      <li>Rates drawn from a continuous gamma distribution $g(r; \alpha, \beta)$.</li>
      <li>Set mean $\alpha/\beta = 1$ (so $\alpha=\beta$). One shape parameter $\alpha$.</li>
      <li>Likelihood at a site: $f(x_h\vert \theta) = \int_0^\infty g(r) f(x_h\vert r; \theta) dr$ (Eq 4.19)</li>
    </ul>
  </li>
  <li><strong>4.3.1.3 Discrete Gamma Model:</strong>
    <ul>
      <li>Approximates continuous gamma with $K$ discrete categories.</li>
      <li>Each category has probability $p_k=1/K$.</li>
      <li>$r_k$ is the mean (or median) rate for the $k^{th}$ quantile of the gamma distribution (Fig 4.9). Only $\alpha$ is a free parameter.</li>
      <li>$K=4$ or $K=5$ often good approximation. Computationally $K$ times slower.</li>
      <li>This is generally preferred over the general discrete-rate model due to fewer, more stable parameters.</li>
    </ul>
  </li>
  <li><strong>Example 4.3 (12S rRNA):</strong> Discrete gamma fits better than general discrete-rate.</li>
  <li><strong>Pathological “I+$\Gamma$” Model (4.3.1.4):</strong>
    <ul>
      <li>Proportion $p_0$ of sites are invariable; rest $1-p_0$ have rates from gamma.</li>
      <li>Strong correlation between $p_0$ and $\alpha$, hard to estimate. Sensitive to data. Often selected by automated tools but should be avoided. Simple gamma (+$\Gamma$) is preferred.</li>
    </ul>
  </li>
  <li><strong>Gamma Mixture Model:</strong> Rates from a mixture of two gamma distributions. More stable than I+$\Gamma$.</li>
  <li><strong>Empirical Bayes (EB) Estimation of Site Rates (4.3.1.5):</strong>
    <ul>
      <li>After estimating model parameters $\hat{\theta}$ (including $\alpha$ or $p_k, r_k$), estimate rate for a specific site $h$ using its posterior distribution:
$f(r\vert x_h; \hat{\theta}) = \frac{f(r\vert \hat{\theta}) f(x_h\vert r; \hat{\theta})}{f(x_h\vert \hat{\theta})}$ (Eq 4.21)</li>
      <li>Posterior mean can be used as the rate estimate.</li>
    </ul>
  </li>
  <li><strong>Correlated Rates at Adjacent Sites (4.3.1.6):</strong> Hidden Markov Models (HMMs) where rate class transition depends on previous site’s class. Rates are correlated. More complex.</li>
  <li><strong>Covarion Models (4.3.1.7):</strong>
    <ul>
      <li>A site can switch its evolutionary rate class <em>over time</em> along different lineages. (Fast on one branch, slow on another).</li>
      <li>Expanded state space: e.g., A+, A-, C+, C- (on/off states). If nucleotide is ‘off’, it doesn’t change. If ‘on’, it changes according to a standard model.</li>
      <li>Handled by standard pruning algorithm on the expanded state space.</li>
    </ul>
  </li>
</ul>

<h4 id="432-mixture-models-for-pattern-heterogeneity-among-sites">4.3.2 Mixture Models for Pattern Heterogeneity Among Sites</h4>
<ul>
  <li>Different sites might evolve under different substitution <em>patterns</em> (e.g., different $Q$ matrices, different $\pi$ vectors), not just different overall rates.</li>
  <li>Example: Mixture of several empirical amino acid matrices for different site classes. If matrices are fixed, no new parameters.</li>
</ul>

<h4 id="433-partition-models-for-combined-analysis-of-multiple-datasets">4.3.3 Partition Models for Combined Analysis of Multiple Datasets</h4>
<ul>
  <li>If <em>a priori</em> knowledge exists about site heterogeneity (e.g., codon positions, different genes).</li>
  <li>Assign different parameters (rates $r_k$, $\kappa_k$, $\pi_k$, even topology $\tau_k$) to different partitions.</li>
  <li>Log-likelihood is sum over sites, using parameters specific to the partition $I(h)$ of site $h$:
$l(\theta, r_1, …, r_K; X) = \sum_h \log{f(x_h\vert r_{I(h)}; \theta)}$ (Eq 4.22)</li>
  <li>Useful for multi-gene datasets, accommodating different evolutionary dynamics per gene/partition.</li>
  <li>Distinction from mixture models: in partition models, site assignment to a partition is known.</li>
  <li>Debate: Combined analysis (supermatrix, with partitions) vs. separate analysis (then supertree). Partitioned likelihood is a form of combined analysis that accounts for heterogeneity.</li>
</ul>

<h4 id="434-nonhomogeneous-and-nonstationary-models">4.3.4 Nonhomogeneous and Nonstationary Models</h4>
<ul>
  <li>Deal with varying base/amino acid compositions among sequences/lineages (violation of stationarity).</li>
  <li><strong>Branch-Specific Frequencies:</strong> Assign different equilibrium frequency vectors ($\pi^{(b)}$) to different branches or parts of the tree. Many parameters.</li>
  <li><strong>GC Content Models:</strong> Simpler versions where only GC content varies.</li>
  <li>Computationally difficult. Likelihood calculation requires modifications as $P_{ij}(t)$ depends on $\pi$ at both ends of branch if non-stationary.</li>
  <li>Bayesian methods with priors on frequency drift can be used.</li>
</ul>

<h3 id="44-reconstruction-of-ancestral-states-asr">4.4 Reconstruction of Ancestral States (ASR)</h3>

<p>Inferring character states at internal nodes of a tree.</p>

<h4 id="441-overview">4.4.1 Overview</h4>
<ul>
  <li>Traditional uses: comparative method, “chemical paleogenetic restoration” (synthesizing ancestral proteins).</li>
  <li>Parsimony ASR (e.g., Fitch, Sankoff) was common.</li>
  <li><strong>Likelihood/Empirical Bayes (EB) Approach (Yang et al. 1995a):</strong> Calculates posterior probabilities of states at ancestral nodes, given data and model parameters (MLEs).
    <ul>
      <li>Accounts for branch lengths, varying rates. Provides uncertainty measure.</li>
    </ul>
  </li>
</ul>

<h4 id="442-empirical-and-hierarchical-bayesian-reconstruction">4.4.2 Empirical and Hierarchical Bayesian Reconstruction</h4>
<ul>
  <li><strong>Marginal Reconstruction:</strong> Posterior probability of state $x_a$ at a single ancestral node $a$.
    <ul>
      <li>To find $P(x_a \vert  X, \theta)$: Reroot tree at node $a$. Then $P(x_a \vert  X, \theta) = \frac{\pi_{x_a} L_a(x_a)}{\sum_{x’<em>a} \pi</em>{x’_a} L_a(x’_a)}$ (Eq 4.23, where $L_a(x_a)$ is likelihood of data given $x_a$ at new root $a$).</li>
      <li>Example (Fig 4.2): Root at node 0. $P(X_0=C\vert data) = 0.901$.</li>
    </ul>
  </li>
  <li><strong>Joint Reconstruction:</strong> Posterior probability of a <em>set</em> of states for <em>all</em> ancestral nodes simultaneously.
    <ul>
      <li>$P(y_A \vert  X, \theta) = \frac{P(X, y_A \vert  \theta)}{P(X\vert \theta)}$, where $y_A=(x_0, x_6, …)$ is a specific combination of ancestral states.</li>
      <li>Numerator is $\pi_{x_0} \times \prod P(\text{daughter state} \vert  \text{parent state})$ (Eq 4.24).</li>
      <li>Denominator is overall site likelihood $f(X\vert \theta)$.</li>
      <li>Finding the best joint reconstruction often uses dynamic programming (similar to Sankoff’s).</li>
      <li>Marginal probabilities should not be multiplied to get joint probabilities (states at different nodes are not independent).</li>
    </ul>
  </li>
  <li><strong>Comparison with Parsimony (4.4.2.3):</strong> EB and parsimony similar under JC69 + equal branches. Differ with complex models/unequal branches. EB provides probabilities.</li>
  <li><strong>Hierarchical Bayesian ASR (4.4.2.4):</strong> Integrates over uncertainty in model parameters (branch lengths, $\kappa$, $\alpha$) by assigning priors and using MCMC. More robust for small datasets.
    <ul>
      <li>Uncertainty in phylogeny is a more complex issue. Often, a fixed (e.g., ML) tree is used.</li>
    </ul>
  </li>
</ul>

<h4 id="443-discrete-morphological-characters">*4.4.3 Discrete Morphological Characters</h4>
<ul>
  <li>Same EB theory applies.</li>
  <li><strong>Difficulties:</strong>
    <ol>
      <li>Few characters, so model parameters (rates $q_{01}, q_{10}$; branch lengths) hard to estimate reliably from the character itself. Using molecular branch lengths is an option but potentially problematic.</li>
      <li>Rate symmetry ($q_{01}=q_{10}$) assumption is critical.</li>
      <li>Equal branch length assumption is highly unrealistic.
        <ul>
          <li>Hierarchical Bayesian approach (averaging over parameter uncertainty) is preferred but sensitive to priors. Classical ML struggles with few data points.</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h4 id="444-systematic-biases-in-ancestral-reconstruction">4.4.4 Systematic Biases in Ancestral Reconstruction</h4>
<ul>
  <li>Using only the <em>most probable</em> ancestral state (ignoring suboptimal ones) can lead to biases.</li>
  <li>Example (Fig 4.10): If true ancestral base compositions are skewed (e.g., A more frequent than G), and ASR reconstructs A when data is AAG/AGA/GAA and G for GGA/GAG/AGG, this can lead to an artificial “drift” in reconstructed ancestral compositions if one state is more common in the data.</li>
  <li><strong>Remedy:</strong> Instead of using only the “best” reconstruction, use a likelihood approach that sums over all possible ancestral states, weighted by their probabilities. Or, in ASR-based methods, weight contributions from suboptimal reconstructions by their posterior probabilities.</li>
</ul>

<h3 id="45-numerical-algorithms-for-maximum-likelihood-estimation">*4.5 Numerical Algorithms for Maximum Likelihood Estimation</h3>

<p>Finding MLEs $\hat{\theta}$ by maximizing $l(\theta)$ or minimizing $f(\theta) = -l(\theta)$. Derivatives $\partial l / \partial \theta_i = 0$. Usually requires iterative numerical methods.</p>

<h4 id="451-univariate-optimization-line-search">*4.5.1 Univariate Optimization (Line Search)</h4>
<ul>
  <li><strong>Golden Section Search (4.5.1.1):</strong> Reduces interval of uncertainty for a unimodal function by comparing values at two interior points defined by the golden ratio. Linear convergence. (Fig 4.11, 4.12)</li>
  <li><strong>Newton’s Method (Newton-Raphson) (4.5.1.2):</strong> Uses first ($f’$) and second ($f’’$) derivatives. Approximates function locally by a parabola.
$\theta_{k+1} = \theta_k - f’(\theta_k) / f’’(\theta_k)$ (Eq 4.30)
Quadratic convergence (fast) near minimum if $f’’(\theta_k)&gt;0$. Requires derivatives. Can diverge if far from minimum or $f’’ \approx 0$. Safeguards needed (e.g., step halving, Eq 4.31).</li>
</ul>

<h4 id="452-multivariate-optimization">*4.5.2 Multivariate Optimization</h4>
<p>(Covered in detail in previous summary from provided image, Section 4.5.2 of text)</p>
<ul>
  <li>Optimizing one parameter at a time (axis iteration) is inefficient if parameters are correlated (Fig 4.13).</li>
  <li>Standard methods update all variables simultaneously.</li>
  <li><strong>Steepest-Descent (4.5.2.1):</strong> Move in direction of negative gradient $-g$. Then line search. Slow zigzagging near minimum if valley is narrow/curved.
<em>(Other methods like Newton, Quasi-Newton (BFGS, DFP) are described in the text page 138, which was part of a previous query).</em></li>
</ul>

<h4 id="4522-newtons-method-multivariate">4.5.2.2 Newton’s Method (Multivariate)</h4>
<ul>
  <li>Relies on a quadratic approximation of the objective function $f(\theta)$ around the current point $\theta_k$.</li>
  <li>Uses the gradient vector $g_k$ (first partial derivatives) and the Hessian matrix $G_k$ (second partial derivatives, $G = d^2f(\theta)$).</li>
  <li>Taylor expansion: $f(\theta) \approx f(\theta_k) + g_k^T (\theta - \theta_k) + \frac{1}{2} (\theta - \theta_k)^T G_k (\theta - \theta_k)$ (Eq 4.32)</li>
  <li>Minimizing this quadratic approximation yields the next iterate:
$\theta_{k+1} = \theta_k - G_k^{-1} g_k$ (Eq 4.33)</li>
  <li><strong>Drawbacks:</strong> Same as univariate Newton’s method (requires first and second derivatives, can diverge if not close to minimum).</li>
  <li><strong>Safeguarded Newton Algorithm:</strong>
    <ul>
      <li>Use $s_k = -G_k^{-1} g_k$ as a search direction.</li>
      <li>Perform a line search to find step length $\alpha_k$: $\theta_{k+1} = \theta_k + \alpha_k s_k$ (Eq 4.34)</li>
      <li>Simpler: Try $\alpha_k = 1, 1/2, 1/4, …$ until $f(\theta_{k+1}) \le f(\theta_k)$.</li>
      <li>If $G_k$ is not positive definite (required for minimization), it can be reset (e.g., to identity matrix $I$).</li>
    </ul>
  </li>
  <li><strong>Information Matrix:</strong> When $f(\theta) = -l(\theta)$ (negative log-likelihood), $G_k = -\frac{d^2l}{d\theta^2}$ is the <em>observed information matrix</em>.</li>
  <li><strong>Scoring Method:</strong> Uses <em>expected information matrix</em> $I(\theta) = -E\left[\frac{d^2l}{d\theta^2}\right]$ instead of $G_k$ if it’s easier to calculate.</li>
  <li><strong>Benefit:</strong> Approximate variance-covariance matrix of MLEs ($G_k^{-1}$ or $I(\hat{\theta})^{-1}$) is available at convergence.</li>
</ul>

<h4 id="4523-quasi-newton-methods">4.5.2.3 Quasi-Newton Methods</h4>
<ul>
  <li>Require first derivatives ($g$) but not second derivatives ($G$).</li>
  <li>Build up an approximation $B_k$ to the inverse Hessian $G_k^{-1}$ iteratively using values of $f$ and $g$.</li>
  <li><strong>Basic Algorithm:</strong>
a. Initial guess $\theta_0$, initial $B_0$ (e.g., identity matrix).
b. For $k = 0, 1, 2, …$ until convergence:
    1. Test $\theta_k$ for convergence.
    2. Calculate search direction: $s_k = -B_k g_k$.
    3. Line search along $s_k$ to find step length $\alpha_k$: $\theta_{k+1} = \theta_k + \alpha_k s_k$.
    4. Update $B_k$ to $B_{k+1}$ (using formulae like BFGS or DFP).</li>
  <li>$B_k$ is a symmetric positive definite matrix.</li>
  <li>More efficient than derivative-free methods if first derivatives (even approximated) are available.</li>
</ul>

<h4 id="4524-bounds-and-constraints">4.5.2.4 Bounds and Constraints</h4>
<ul>
  <li>Many phylogenetic parameters have bounds (e.g., branch lengths $t \ge 0$; nucleotide frequencies $\pi_i &gt; 0, \sum \pi_i = 1$; divergence times $t_0 &gt; t_1 &gt; t_2 &gt; t_3$).</li>
  <li>Constrained optimization is complex.</li>
  <li><strong>Variable Transformation:</strong> An effective way to convert a constrained problem to an unconstrained one.
    <ul>
      <li><strong>Example (frequencies $\pi_1, \pi_2, \pi_3, \pi_4$):</strong>
Use unconstrained $x_1, x_2, x_3 \in (-\infty, \infty)$, set $x_4=0$.
Let $s = e^{x_1} + e^{x_2} + e^{x_3} + e^{x_4}$ (denominator, using $e^{x_4}=1$).
Then $\pi_i = e^{x_i}/s$. This ensures $\pi_i &gt; 0$ and $\sum \pi_i = 1$.
(Note: text typo $\pi_1=x_1/s$ is incorrect, it should be $\pi_1=e^{x_1}/s$ or similar for positivity).</li>
      <li><strong>Example (divergence times $t_0 &gt; t_1 &gt; t_2 &gt; t_3 &gt; 0$):</strong>
Define $x_0 = t_0$ (root age)
$x_1 = t_1/t_0$
$x_2 = t_2/t_1$
$x_3 = t_3/t_2$
New constraints: $0 &lt; x_0 &lt; \infty$ (can use $x_0=e^{y_0}$), and $0 &lt; x_1, x_2, x_3 &lt; 1$.
The ratio $x_i = t_i / t_{\text{mother node}}$ ensures $0 &lt; x_i &lt; 1$ for non-root nodes if $t_i &lt; t_{\text{mother node}}$.</li>
    </ul>
  </li>
</ul>

<h2 id="46-ml-optimization-in-phylogenetics">4.6 ML Optimization in Phylogenetics</h2>

<h4 id="461-optimization-on-a-fixed-tree">4.6.1 Optimization on a Fixed Tree</h4>
<ul>
  <li>Parameters include branch lengths ($t$) and substitution model parameters ($\psi$).</li>
  <li>Direct multivariate optimization is inefficient because changing one branch length $t_b$ only affects conditional likelihoods $L_i(x_i)$ ancestral to that branch.</li>
  <li><strong>Optimize One Branch Length at a Time:</strong>
    <ul>
      <li>Keep other branches and $\psi$ fixed.</li>
      <li>For branch $b$ connecting nodes $a$ and $b’$ (with length $t_b$), the likelihood can be written (by temporarily rooting at $a$):
$f(x_h\vert \theta) = \sum_{x_a} \sum_{x_{b’}} \pi_{x_a} P_{x_a x_{b’}}(t_b) L_a(x_a) L_{b’}(x_{b’})$ (Eq 4.35, adapted from notation)</li>
      <li>First and second derivatives of $l$ w.r.t $t_b$ can be calculated analytically.</li>
      <li>$t_b$ can be optimized efficiently using <strong>Newton’s method</strong>.</li>
      <li>Iterate through all branches.</li>
    </ul>
  </li>
  <li><strong>Optimizing Substitution Parameters ($\psi$):</strong>
    <ul>
      <li>A change in $\psi$ typically affects all conditional probabilities.</li>
      <li><strong>Two-Phase Strategy (Yang, 2000b):</strong>
        <ol>
          <li>Phase 1: Optimize all branch lengths one-by-one (Newton’s) with $\psi$ fixed. Cycle until convergence.</li>
          <li>Phase 2: Optimize $\psi$ (e.g., BFGS) with branch lengths fixed.</li>
          <li>Repeat 1 &amp; 2.
            <ul>
              <li>Works well if $t$ and $\psi$ are not strongly correlated (e.g., $\kappa$ in HKY85).</li>
              <li>Inefficient if strongly correlated (e.g., branch lengths and $\alpha$ for gamma rates).</li>
            </ul>
          </li>
        </ol>
      </li>
      <li><strong>Embedded Strategy (Swofford, 2000):</strong>
        <ol>
          <li>Outer loop: Optimize $\psi$ using multivariate algorithm (e.g., BFGS).</li>
          <li>Inner loop: For <em>each</em> set of $\psi$ values proposed by BFGS, re-optimize all branch lengths before calculating the likelihood.
            <ul>
              <li>More robust to correlations but computationally intensive.</li>
            </ul>
          </li>
        </ol>
      </li>
    </ul>
  </li>
</ul>

<h4 id="462-multiple-local-peaks-on-the-likelihood-surface-for-a-fixed-tree">4.6.2 Multiple Local Peaks on the Likelihood Surface for a Fixed Tree</h4>
<ul>
  <li>Numerical optimization algorithms are local hill-climbers and may find a local, not global, maximum.</li>
  <li>More common with complex, parameter-rich models or near parameter boundaries (e.g., zero branch lengths).</li>
  <li><strong>Symptom:</strong> Different starting values lead to different MLEs and likelihood scores.</li>
  <li><strong>Remedy:</strong> No foolproof solution.
    <ul>
      <li>Multiple runs from different initial values.</li>
      <li>Stochastic search algorithms (simulated annealing, genetic algorithms).</li>
    </ul>
  </li>
</ul>

<h4 id="463-search-in-the-tree-space">4.6.3 Search in the Tree Space</h4>
<ul>
  <li>If tree topology ($\tau$) is unknown, this is a much harder problem.</li>
  <li><strong>Two Levels of Optimization:</strong>
    <ol>
      <li>Inner: Optimize parameters (branch lengths, $\psi$) for a <em>fixed</em> $\tau$ to get $l(\hat{\theta}_\tau \vert  X)$.</li>
      <li>Outer: Search tree space for $\tau$ that maximizes $l(\hat{\theta}_\tau \vert  X)$.</li>
    </ol>
  </li>
  <li><strong>Example (3 taxa, binary characters, clock - Fig 4.14, 4.15):</strong>
    <ul>
      <li>Data: counts $(n_0, n_1, n_2, n_3)$ or frequencies $(f_0, f_1, f_2, f_3)$ of site patterns (xxx, xxy, yxx, xyx).</li>
      <li>Probabilities of site patterns $p_0, p_1, p_2$ (Eq 4.37, note $p_2=p_3$). $P(\text{data}\vert \tau, t_0, t_1)$ is multinomial (Eq 4.36).</li>
      <li>Parameter space for each tree $\tau_i$ forms a triangle within the sample space (tetrahedron).</li>
      <li>MLE for a fixed tree $\tau_i$ corresponds to finding point in its parameter space closest to observed $f_i$ by Kullback-Leibler divergence:
$D_{KL}(f \vert \vert  p) = \sum_i f_i \log (f_i/p_i)$ (Eq 4.38)
Minimizing $D_{KL}$ is equivalent to maximizing $\sum n_i \log p_i$.</li>
      <li>The ML tree is the one whose parameter space is closest to the data.</li>
    </ul>
  </li>
  <li><strong>Practical Tree Search:</strong>
    <ul>
      <li>Uses tree-rearrangement algorithms (NNI, SPR, TBR - see Chapter 3).</li>
      <li>Candidate trees are evaluated; only affected branch lengths are re-optimized for speed.</li>
    </ul>
  </li>
</ul>

<h4 id="464-approximate-likelihood-method">4.6.4 Approximate Likelihood Method</h4>
<ul>
  <li>Historically, to reduce computation:
    <ul>
      <li>Use other methods (e.g., LS, parsimony) to estimate branch lengths on a given tree, then calculate likelihood.</li>
      <li>Quartet Puzzling: ML for all quartets, then assemble.</li>
    </ul>
  </li>
  <li>Less important now with faster exact ML programs (e.g., RAxML), but can be useful for initial trees.</li>
</ul>

<h2 id="47-model-selection-and-robustness">4.7 Model Selection and Robustness</h2>

<p>This section discusses how to choose appropriate evolutionary models for ML analysis and how to evaluate their fit and the reliability of inferences.</p>

<h3 id="471-likelihood-ratio-test-lrt-applied-to-rbcl-dataset">4.7.1 Likelihood Ratio Test (LRT) Applied to rbcL Dataset</h3>
<ul>
  <li><strong>LRT Principle:</strong> Compares the fit of two <em>nested</em> models.
    <ul>
      <li>$H_0$: Simpler model. $H_1$: More complex model.</li>
      <li>Test statistic: $\Delta = 2(l_1 - l_0)$, where $l_1$ and $l_0$ are maximized log-likelihoods under $H_1$ and $H_0$.</li>
      <li>Under $H_0$, $\Delta \sim \chi^2_{df}$, where $df$ is the difference in the number of free parameters.</li>
    </ul>
  </li>
  <li><strong>Example (rbcL dataset, Table 4.3, 4.4):</strong>
    <ul>
      <li><strong>JC69 vs. K80:</strong> $H_0: \kappa=1$. K80 has 1 extra parameter ($\kappa$). $df=1$. $2\Delta l = 296.3$. Critical $\chi^2_{1,1\%} = 6.63$. JC69 is rejected.</li>
      <li><strong>JC69 vs. JC69+$\Gamma_5$ (rate variation):</strong> $H_0: \alpha=\infty$ (one rate). Alternative has $\alpha$ (1 extra parameter for gamma shape).
        <ul>
          <li><strong>Boundary Issue:</strong> $\alpha=\infty$ is at the boundary of parameter space. The null distribution for $\Delta$ is a 50:50 mixture of a point mass at 0 and a $\chi^2_1$ distribution.</li>
          <li>Using standard $\chi^2_1$ is too conservative.</li>
          <li>For rbcL, $2\Delta l = 648.42$, very significant regardless of the exact null.</li>
        </ul>
      </li>
      <li><strong>JC69 vs. JC69+C (codon position rates):</strong> $H_0: r_1=r_2=r_3$. Alternative allows different rates for 3 codon positions (2 extra parameters). $df=2$. $2\Delta l = 678.50$. JC69 is rejected.</li>
    </ul>
  </li>
  <li><strong>Typical Pattern:</strong> More complex models (e.g., HKY85+$\Gamma_5$, HKY85+C) are often not rejected, while simpler ones are. LRT tends to favor parameter-rich models with large datasets.</li>
</ul>

<h3 id="472-test-of-goodness-of-fit-and-parametric-bootstrap">4.7.2 Test of Goodness of Fit and Parametric Bootstrap</h3>
<ul>
  <li><strong>Goodness-of-Fit (GoF):</strong> Assesses if a <em>single</em> model adequately describes the data (absolute fit), not just relative to a simpler model.</li>
  <li><strong>Saturated Model (Multinomial):</strong> Assigns a probability to each of $4^s$ possible site patterns for $s$ sequences. Has $4^s-1$ parameters. Max log-likelihood under this is $l_{max} = \sum_{i=1}^{4^s} n_i \log(n_i/n)$ (Eq 4.39), where $n_i$ is count of pattern $i$.</li>
  <li><strong>Problem:</strong> Standard $\chi^2$ GoF test (comparing model $l$ to $l_{max}$) usually not applicable because many site patterns have low/zero counts.</li>
  <li><strong>Parametric Bootstrap for GoF (Goldman 1993a):</strong>
    <ol>
      <li>Fit the chosen model (e.g., HKY85+$\Gamma_5$) to real data $\rightarrow \hat{\theta}$. Calculate $l_{model}$ and $l_{max}$. Test statistic $\Delta l_{obs} = l_{max} - l_{model}$.</li>
      <li>Simulate many (e.g., 1000) replicate datasets from the fitted model (Given the tree topology and using $\hat{\theta}$).</li>
      <li>For each simulated dataset, re-calculate $l_{max,sim}$ and $l_{model,sim}$, get $\Delta l_{sim}$.</li>
      <li>The distribution of $\Delta l_{sim}$ values is the null distribution.</li>
      <li>If $\Delta l_{obs}$ is in the extreme tail of this distribution (e.g., p-value = proportion of $\Delta l_{sim} &gt; \Delta l_{obs}$ is small), the model fits poorly.</li>
    </ol>
  </li>
  <li>Parametric bootstrap is general but computationally expensive.</li>
</ul>

<h3 id="473-diagnostic-tests-to-detect-model-violations">*4.7.3 Diagnostic Tests to Detect Model Violations</h3>
<p>If GoF rejects a model, these help identify <em>which</em> assumptions are violated.</p>
<ul>
  <li><strong>Number of Distinct Site Patterns (Goldman 1993b):</strong> If model ignores rate variation, it might predict too few distinct patterns, too many constant sites, etc., compared to observed data. Use bootstrap to get expected distribution.</li>
  <li><strong>Stationarity of Frequencies:</strong> Are base/amino acid frequencies homogeneous across sequences? Test with $s \times 4$ contingency table.</li>
  <li><strong>Symmetry/Reversibility (Tavaré 1986):</strong> For two sequences, count of pattern $ij$ ($N_{ij}$) should equal count of $ji$ ($N_{ji}$) if process is reversible.
$X^2 = \sum_{i&lt;j} \frac{(N_{ij} - N_{ji})^2}{N_{ij} + N_{ji}}$ (Eq 4.40). Approx $\chi^2_6$ for nucleotides.
Powerful for detecting small violations.</li>
</ul>

<h3 id="474-akaike-information-criterion-aic-and-aicc">4.7.4 Akaike Information Criterion (AIC and AICc)</h3>
<ul>
  <li>Compares models (nested or non-nested). Penalizes for number of parameters ($p$).</li>
  <li><strong>AIC (Akaike 1974):</strong> $AIC = -2l + 2p$ (Eq 4.41). Prefer model with lower AIC. Extra parameter “worth it” if it improves $l$ by &gt;1.</li>
  <li>Perceived to not penalize complex models enough.</li>
  <li><strong>AICc (Corrected AIC, Sugiura 1978):</strong> Includes sample size $n$ (sequence length).
$AICc = -2l + \frac{2np}{n-p-1} = AIC + \frac{2p(p+1)}{n-p-1}$ (Eq 4.42)
Recommended over AIC, especially for smaller $n$.</li>
</ul>

<h3 id="475-bayesian-information-criterion-bic">4.7.5 Bayesian Information Criterion (BIC)</h3>
<ul>
  <li><strong>BIC (Schwarz 1978):</strong> $BIC = -2l + p \log(n)$ (Eq 4.43).</li>
  <li>Penalizes parameters more harshly than AIC for $n &gt; 8$ (since $\log n &gt; 2$). Tends to favor simpler models, especially with large datasets.</li>
  <li>All (LRT, AIC, BIC) are formulations of Occam’s Razor.</li>
  <li><strong>MODELTEST (Posada &amp; Crandall 1998):</strong> Automates model selection using these criteria. Caution: Mechanical application can lead to overly complex (e.g., pathological I+$\Gamma$) models.</li>
</ul>

<h3 id="476-model-adequacy-and-robustness">4.7.6 Model Adequacy and Robustness</h3>
<ul>
  <li><strong>Quote:</strong> “All models are wrong but some are useful.” (George Box)</li>
  <li><strong>Purpose of Model:</strong>
    <ul>
      <li>If model <em>is</em> the hypothesis (e.g., testing molecular clock).</li>
      <li>If model is a <em>nuisance</em> (needed for inference, e.g., substitution model for tree reconstruction). This section focuses on selecting nuisance models.</li>
    </ul>
  </li>
  <li><strong>Model Fit vs. Impact on Inference:</strong>
    <ul>
      <li><strong>Adequacy:</strong> How well the model statistically fits the data.</li>
      <li><strong>Robustness:</strong> How much the <em>inference</em> (e.g., tree topology) is affected by model violations.</li>
    </ul>
  </li>
  <li><strong>Goal of Model Selection:</strong> Not to find the “true” model (impossible), but one with sufficient parameters to capture <em>key features of the data relevant to the question asked</em>.</li>
  <li><strong>i.i.d. Models:</strong> Most phylogenetic models (even with rate variation like +$\Gamma$, or covarion models) assume sites are independent and identically drawn from some overall (potentially complex) distribution of evolutionary processes. This is a statistical device to reduce parameters.</li>
  <li><strong>Some features are critical for fit AND inference</strong> (e.g., variable rates among sites).</li>
  <li><strong>Some features improve fit but have little impact on inference</strong> (e.g., Ts/Tv ratio differences between HKY85 and GTR might not change tree much).</li>
  <li><strong>Most troublesome: factors with little impact on fit but HUGE impact on inference</strong> (e.g., different models for lineage rates in divergence time estimation can give similar likelihoods but very different times).</li>
  <li><strong>Robustness to Model Choice:</strong> ML is generally quite robust to substitution model details, but performance is highly dependent on <strong>tree shape</strong> (relative branch lengths).
    <ul>
      <li>“Easy” trees (long internal branches): most methods/models work. Wrong simple models might even seem to perform better.</li>
      <li>“Hard” trees (short internal, long external branches): require complex, realistic models to avoid inconsistency (e.g., LBA).</li>
    </ul>
  </li>
</ul>

<h1 id="5-comparison-of-phylogenetic-methods-and-tests-on-trees">5. Comparison of phylogenetic methods and tests on trees</h1>

<p>This chapter discusses the evaluation of statistical properties of tree reconstruction methods and tests for the significance of estimated phylogenies.</p>

<h2 id="51-statistical-performance-of-tree-reconstruction-methods">5.1 Statistical Performance of Tree Reconstruction Methods</h2>

<p>This section outlines criteria for assessing tree reconstruction methods and summarizes findings from simulation studies.</p>

<h3 id="511-criteria">5.1.1 Criteria</h3>
<p>When comparing phylogenetic methods, two types of error are distinguished:</p>
<ul>
  <li><strong>Random Errors (Sampling Errors):</strong> Due to the finite length of sequences (sample size $n$). These decrease as $n \to \infty$.</li>
  <li><strong>Systematic Errors:</strong> Due to incorrect model assumptions or method deficiencies. These persist or worsen as $n \to \infty$.</li>
</ul>

<p>Criteria for judging methods include:</p>
<ul>
  <li><strong>Computational Speed:</strong> Distance methods are generally fastest, followed by parsimony, then likelihood/Bayesian methods.</li>
  <li><strong>Statistical Properties:</strong>
    <ul>
      <li><strong>5.1.1.1 Identifiability:</strong> A model is unidentifiable if two different parameter sets ($\theta_1, \theta_2$) produce the exact same probability of the data ($f(X\vert \theta_1) = f(X\vert \theta_2)$) for all possible data $X$. In such cases, the parameters cannot be distinguished.
        <ul>
          <li>Example: For a pair of sequences under a time-reversible model like JC69, one cannot separately estimate divergence time $t$ and substitution rate $r$; only their product, the distance $d = t \cdot r$, is identifiable.</li>
          <li>Unidentifiable models should be avoided as they usually indicate flaws in model formulation.</li>
        </ul>
      </li>
      <li><strong>5.1.1.2 Consistency:</strong> An estimator $\hat{\theta}$ is consistent if it converges to the true parameter value $\theta$ as the sample size $n \to \infty$.
        <ul>
          <li>Formally: $\lim_{n\to\infty} P(\vert \hat{\theta} - \theta\vert  &lt; \epsilon) = 1$ for any small $\epsilon &gt; 0$. (Eq 5.1)</li>
          <li><strong>Strong Consistency:</strong> $\lim_{n\to\infty} P(\hat{\theta} = \theta) = 1$. (Eq 5.2)</li>
          <li>For phylogenetic trees (not regular parameters), a method is consistent if the probability of estimating the true tree approaches 1 as $n \to \infty$. This assumes the correctness of the model for model-based methods.</li>
          <li>Parsimony can be inconsistent (Felsenstein 1978b).</li>
          <li>Consistency is considered a fundamental property for any sensible estimator.</li>
        </ul>
      </li>
      <li><strong>5.1.1.3 Efficiency:</strong> A consistent estimator is efficient if it has the asymptotically smallest variance.
        <ul>
          <li>The variance of a consistent, unbiased estimator $\hat{\theta}$ is bounded by the Cramér-Rao lower bound: $\text{var}(\hat{\theta}) \ge 1/I$, where $I = -E\left[\frac{d^2\log f(X\vert \theta)}{d\theta^2}\right]$ is the Fisher information. (Eq 5.3)</li>
          <li>MLEs are asymptotically consistent, unbiased, normally distributed, and attain this bound.</li>
          <li><strong>Relative Efficiency of Tree Reconstruction Methods:</strong>
            <ul>
              <li>$E_{21} = n_1(P)/n_2(P)$: Ratio of sample sizes needed by method 1 ($n_1$) and method 2 ($n_2$) to recover the true tree with the same probability $P$. (Eq 5.4)</li>
              <li>Alternatively: $E^{\ast}<em>{21} = \frac{1 - P</em>{1}(n)}{1 - P_{2}(n)}$: Ratio of error rates for a given sample size $n$. Method 2 is more efficient if $E^*_{21} &gt; 1$. (Eq 5.5)</li>
            </ul>
          </li>
        </ul>
      </li>
      <li><strong>5.1.1.4 Robustness:</strong> A model-based method is robust if it performs well even when its assumptions are slightly violated.</li>
    </ul>
  </li>
</ul>

<h3 id="512-performance">5.1.2 Performance</h3>
<p>Methods for evaluating tree reconstruction performance:</p>
<ol>
  <li><strong>Laboratory-Generated Phylogenies:</strong> True phylogeny is known by experimental design (e.g., Hillis et al., 1992, evolving bacteriophage T7).</li>
  <li><strong>Well-Established Phylogenies:</strong> Using phylogenies widely accepted from other evidence (fossils, morphology, previous molecular data).</li>
  <li><strong>Computer Simulation:</strong> Generate replicate datasets under a known model and tree, then analyze with different methods. Allows control over parameters.
    <ul>
      <li>Criticisms: Models may be too simple; limited parameter space can be explored.</li>
    </ul>
  </li>
</ol>

<p><strong>Generally Accepted Observations from Simulations:</strong></p>
<ol>
  <li>Clock-assuming methods (e.g., UPGMA) perform poorly if the clock is violated.</li>
  <li>Parsimony and methods using simplistic models are prone to long-branch attraction (LBA). Likelihood with complex models is more robust.</li>
  <li>Likelihood methods are often more efficient than parsimony or distance methods (but see counter-examples).</li>
  <li>Distance methods perform poorly with highly divergent sequences or many gaps.</li>
  <li>Optimal performance is at intermediate levels of sequence divergence.</li>
  <li>Tree shape (relative branch lengths) greatly impacts performance.
    <ul>
      <li>“Hard” trees (short internal, scattered long external branches) are difficult.</li>
      <li>“Easy” trees (long internal branches) are easier. Simplistic models might even outperform complex ones on easy trees.</li>
    </ul>
  </li>
</ol>

<h2 id="52-likelihood">5.2 Likelihood</h2>

<p>Focuses on statistical properties of the ML method for tree reconstruction.</p>

<h3 id="521-contrast-with-conventional-parameter-estimation">5.2.1 Contrast with Conventional Parameter Estimation</h3>
<ul>
  <li>Tree reconstruction is argued to be a <strong>model selection</strong> problem, not just parameter estimation.</li>
  <li>Each tree topology $\tau$ represents a different statistical model $f_k(X\vert \theta_k)$, where $\theta_k$ are parameters (branch lengths, substitution model parameters) specific to that topology.</li>
  <li>The likelihood function itself changes with the topology.</li>
</ul>

<h3 id="522-consistency">5.2.2 Consistency</h3>
<ul>
  <li>ML is consistent for tree reconstruction if the model is correct and identifiable.</li>
  <li><strong>Proof Idea:</strong> As sequence length $n \to \infty$:
    <ol>
      <li>Observed site pattern frequencies $f_i$ approach true probabilities $p_i^{(1)}(\theta^{(1)<em>})$ predicted by the true tree ($\tau_1$) and true parameters ($\theta^{(1)</em>}$).</li>
      <li>The MLEs of parameters on the true tree $\hat{\theta}^{(1)}$ approach $\theta^{(1)*}$.</li>
      <li>The maximized log-likelihood for the true tree $l_1 = n \sum f_i \log \hat{p}<em>i^{(1)}(\hat{\theta}^{(1)})$ approaches the maximum possible log-likelihood $l</em>{max} = n \sum f_i \log f_i$. (Eq 5.6, 5.7)</li>
      <li>For any wrong tree $\tau_k$, $l_k$ will be less than $l_{max}$ because its predicted probabilities $\hat{p}_i^{(k)}(\hat{\theta}^{(k)})$ cannot perfectly match all $f_i$.</li>
      <li>The difference $(l_{max} - l_k)/n = \sum f_i \log (f_i / \hat{p}_i^{(k)}(\hat{\theta}^{(k)}))$ is the Kullback-Leibler (K-L) divergence, which is positive if the distributions differ. (Eq 5.8)</li>
    </ol>
  </li>
  <li>The question of whether a wrong tree can perfectly mimic the true tree (unidentifiability) is crucial. Models commonly used in phylogenetics are generally identifiable.</li>
</ul>

<h3 id="523-efficiency">5.2.3 Efficiency</h3>
<ul>
  <li><strong>Counterintuitive Results:</strong> Simulation studies showed that ML under the <em>true</em> model can sometimes have a <em>lower</em> probability of recovering the true tree than parsimony or ML under a <em>wrong/simpler</em> model.
    <ul>
      <li>This is not necessarily due to small sample sizes; the effect can persist as $n \to \infty$.</li>
      <li><strong>Fig 5.1:</strong> Shows ML with a false model (JC69, $\alpha=\infty$) outperforming ML with the true model (JC69+$\Gamma$, $\alpha=0.2$) for certain tree shapes. The relative efficiency $E^*_{TF} = (1-P_F)/(1-P_T)$ can be &lt; 1.</li>
    </ul>
  </li>
  <li><strong>Explanation (Swofford et al. 2001; Bruno &amp; Halpern 1999):</strong>
    <ul>
      <li>Parsimony or ML under a simple/wrong model might have an inherent “bias” (e.g., parsimony’s tendency to group long branches).</li>
      <li>If the true tree happens to have a shape that aligns with this bias (e.g., Farris zone in Fig 5.2), the biased method might recover it more readily than ML under the true model, which evaluates evidence “correctly” but might be “slower” to converge to the truth in these specific zones.</li>
    </ul>
  </li>
  <li><strong>Conclusion:</strong> ML for tree reconstruction is <strong>not asymptotically efficient</strong> in the conventional sense (unlike MLEs for regular parameters). There exist regions of parameter space ($\aleph$) where other methods may be asymptotically more efficient.</li>
  <li>This does not endorse using wrong models for real data analysis. ML under the true (or best approximating) model is always consistent, while parsimony or ML under wrong models can be inconsistent.</li>
</ul>

<h3 id="524-robustness">5.2.4 Robustness</h3>
<ul>
  <li>ML is generally highly robust to violations of model assumptions.</li>
  <li>More robust to rate variation among sites than distance methods like NJ, <em>if</em> rate variation is modeled (e.g., +$\Gamma$).</li>
  <li>Ignoring significant rate variation can make ML inconsistent.</li>
  <li><strong>Heterotachy:</strong> (Rates for sites changing differently across lineages).
    <ul>
      <li>Standard ML (assuming one set of branch lengths for all sites, i.e., a homogeneous model) can perform worse than parsimony if data is a mixture from different underlying trees/branch length sets (Kolaczkowski &amp; Thornton 2004; Fig 5.3).</li>
      <li>Modeling heterotachy (e.g., mixture models with different branch length sets) makes ML perform well but is complex.</li>
    </ul>
  </li>
</ul>

<h2 id="53-parsimony">5.3 Parsimony</h2>

<p>This section discusses attempts to establish an equivalence between parsimony and likelihood under specific models and arguments for justifying parsimony.</p>

<h3 id="531-equivalence-with-misbehaved-likelihood-models">5.3.1 Equivalence with Misbehaved Likelihood Models</h3>
<ul>
  <li><strong>Equivalence Goal:</strong> Find a likelihood model under which the Most Parsimonious (MP) tree and the ML tree are identical for <em>every</em> possible dataset.</li>
  <li>Early attempts established equivalence with “pathological” likelihood models, which are statistically problematic (e.g., number of parameters increases with sample size).
    <ul>
      <li><strong>Felsenstein (1973b, 2004):</strong> Model with a rate for every site. Equivalence when all site rates approach zero. Suggests similarity at low divergence.</li>
      <li><strong>Farris (1973), Goldman (1990):</strong> Models estimating ancestral states. Not standard likelihood; can be inconsistent. Goldman’s model assumed equal branch lengths.</li>
      <li><strong>Tuffley and Steel (1997) “No-Common Mechanism”:</strong> Assumes a separate set of branch lengths for <em>every character</em>. Maximized likelihood tree is the MP tree. This model is statistically problematic and biologically unrealistic (fits data poorly compared to standard models).</li>
    </ul>
  </li>
  <li><strong>Conclusion:</strong> Equivalence to such models offers little statistical justification for parsimony.</li>
</ul>

<h3 id="532-equivalence-with-well-behaved-likelihood-models">5.3.2 Equivalence with Well-Behaved Likelihood Models</h3>
<ul>
  <li>Focus on identifiable models with a fixed number of parameters.</li>
  <li><strong>Tractable Case (3 species, binary characters, molecular clock):</strong> (Section 4.6.3) ML, MP, and LS often agree, picking the tree supported by the most frequent informative pattern. This extends to JC69 for nucleotides.
    <ul>
      <li>The maximum integrated likelihood (Bayesian context, Eq 5.10) also yields the same tree.</li>
    </ul>
  </li>
  <li><strong>More Complex Cases:</strong> Generally, no equivalence.
    <ul>
      <li>Parsimony is inconsistent for 4 species (no clock) or $\ge 5$ species (with clock), while ML (correct model) is consistent.</li>
      <li>Suggestion: Parsimony is behaviorally closer to simplistic ML models (like JC69) than complex ones.</li>
    </ul>
  </li>
</ul>

<h3 id="533-assumptions-and-justifications">5.3.3 Assumptions and Justifications</h3>
<ul>
  <li><strong>5.3.3.1 Occam’s Razor and Maximum Parsimony:</strong> Claim that MP embodies Occam’s Razor by minimizing ad hoc assumptions (changes) is superficial. Statistical criteria like LRT, AIC, BIC are more formal applications.</li>
  <li><strong>5.3.3.2 Is Parsimony a Nonparametric Method?</strong> No. A good nonparametric method should perform well over a wide range of models. Parsimony is known to be inconsistent under simple parametric models (Felsenstein zone).</li>
  <li><strong>5.3.3.3 Inconsistency of Parsimony:</strong> (Recap of LBA). Inconsistency under simplistic models implies inconsistency under more complex, realistic models that include the simple case as a special instance.</li>
  <li><strong>5.3.3.4 Assumptions of Parsimony:</strong>
    <ul>
      <li>Independence of characters (sites) and lineages (branches).</li>
      <li>Standard parsimony: equal weights for all changes (implies equal rates) and all sites (implies same process). Weighted/successive parsimony relax these.</li>
      <li><strong>Felsenstein’s “Low Rates” Argument:</strong> Parsimony isn’t just for low rates. Performance depends on tree shape.</li>
      <li><strong>Connection to Likelihood (Sober 1988; Edwards 1996):</strong> In Markov models, $p_{jj}(t) &gt; p_{ij}(t)$ (probability of no change &gt; probability of specific change for a given branch length $t$) (Eq 5.11). This means trees with fewer changes <em>tend</em> to have higher likelihoods.</li>
    </ul>
  </li>
  <li><strong>Conclusion:</strong> Parsimony is best viewed as a simple, often useful heuristic, rather than seeking a deep statistical justification that remains elusive.</li>
</ul>

<h2 id="54-testing-hypotheses-concerning-trees">5.4 Testing Hypotheses Concerning Trees</h2>

<p>Methods to evaluate the reliability of a reconstructed tree (a point estimate).</p>

<h3 id="541-bootstrap">5.4.1 Bootstrap</h3>
<ul>
  <li><strong>5.4.1.1 Bootstrap Standard Errors and Confidence Intervals (General):</strong>
    <ul>
      <li>A simulation-based method (Efron 1979).</li>
      <li>Generate $B$ bootstrap pseudo-samples $x^<em>$ by sampling $n$ data points *with replacement</em> from the original dataset $x$.</li>
      <li>Calculate estimator $\hat{\theta}^<em>_b = t(x^</em>_b)$ for each pseudo-sample.</li>
      <li>Standard Error (SE) estimated from the variance of $\hat{\theta}^*_b$ values. (Eq 5.12)</li>
      <li>Central idea: Distribution of $\hat{\theta}^*_b - \hat{\theta}$ approximates distribution of $\hat{\theta} - \theta$.</li>
    </ul>
  </li>
  <li><strong>5.4.1.2 Bootstrap for Phylogenies (Felsenstein 1985a):</strong>
    <ul>
      <li>Resample <em>sites (columns)</em> from the original alignment with replacement to create bootstrap alignments (Fig 5.4).</li>
      <li>Reconstruct a tree from each bootstrap alignment using the <em>same method</em> as for the original data.</li>
      <li><strong>Summarization:</strong>
        <ol>
          <li><strong>Bootstrap Support/Proportion for Splits:</strong> For each split (clade) in the original tree, calculate the percentage of bootstrap trees that also contain that split. These values are mapped onto the branches of the original ML tree (Fig 5.5).</li>
          <li>Majority-Rule Consensus Tree: Construct a consensus from bootstrap trees.</li>
        </ol>
      </li>
    </ul>
  </li>
  <li><strong>RELL Approximation (Resampling Estimated Log Likelihoods):</strong> (Kishino &amp; Hasegawa 1989)
    <ul>
      <li>Approximation for ML bootstrap. Instead of full tree search on each bootstrap dataset:</li>
      <li>Use MLEs of parameters from original data to calculate site log-likelihoods for a <em>fixed set</em> of candidate trees.</li>
      <li>Resample these site log-likelihoods to get bootstrap log-likelihoods for each tree in the set.</li>
      <li>Good approximation if the set of trees is well-chosen and tree search is not needed for each bootstrap replicate.</li>
    </ul>
  </li>
  <li><strong>5.4.1.3 Interpretations of Bootstrap Support Values ($P$):</strong> Highly debated.
    <ol>
      <li><strong>Confidence Level/Repeatability (Felsenstein 1985a):</strong> $P$ is the probability of getting the split in replicate datasets. Hillis and Bull (1993) found $P$ varies too much across replicates to be a good measure of this.</li>
      <li><strong>Type-I Error Rate / p-value (Felsenstein &amp; Kishino 1993):</strong> $1-P$ is the p-value for $H_0$: split is absent in true tree (internal branch length = 0).
        <ul>
          <li>Susko (2009) showed $1-P$ is not a correct p-value to first-order.</li>
          <li>Issues: defining $H_0$ (e.g., branch length = 0), selection bias (testing splits found <em>post hoc</em> from the data).</li>
          <li>Generally, bootstrap proportions are conservative as p-values (false positive rate &lt; 5% if $P \ge 95\%$).</li>
        </ul>
      </li>
      <li><strong>Accuracy (Bayesian interpretation):</strong> $P$ is $P(\text{split is true} \vert  \text{data})$. Most common intuitive use by empiricists, but lacks formal frequentist justification.
        <ul>
          <li>Hillis and Bull (1993) suggested $P \ge 70\%$ often corresponds to $\ge 95\%$ probability of split being true, but this is not universal.</li>
        </ul>
      </li>
    </ol>
  </li>
  <li>Refinements to bootstrap (complete-and-partial, modified Efron et al.) exist but are not widely used and don’t fix first-order error issues.</li>
</ul>

<h3 id="542-interior-branch-test">5.4.2 Interior-Branch Test</h3>
<ul>
  <li>Tests if an internal branch length is significantly greater than zero.</li>
  <li><strong>ML:</strong> Use LRT comparing $l$ with estimated branch length vs. $l$ with branch length constrained to 0. Null distribution is 50:50 mixture of 0 and $\chi^2_1$ (Self &amp; Liang 1987).</li>
  <li><strong>Distance methods (e.g., NJ):</strong> Test if estimated branch length is significantly positive using its standard error.</li>
  <li><strong>Difficulties:</strong>
    <ol>
      <li>Hypothesis is data-derived (not <em>a priori</em>).</li>
      <li>Multiple testing if applied to all branches.</li>
      <li>Rationale unclear if tree topology itself is wrong (ML can estimate positive interior branch lengths for wrong trees).</li>
    </ol>
  </li>
</ul>

<h3 id="543-k-h-test-and-related-tests-likelihood-framework">5.4.3 K-H Test and Related Tests (Likelihood Framework)</h3>
<ul>
  <li>Compare two candidate phylogenetic trees.</li>
  <li><strong>Kishino-Hasegawa (K-H) Test (1989):</strong>
    <ul>
      <li>Test statistic $\Delta = l_1 - l_2$.</li>
      <li>Standard error of $\Delta$ estimated from variance of per-site log-likelihood differences: $d_h = \log f_1(x_h\vert \hat{\theta}_1) - \log f_2(x_h\vert \hat{\theta}_2)$. (Eq 5.13-5.15)</li>
      <li>Assumes $d_h$ are i.i.d. and $\Delta$ is normally distributed.</li>
      <li><strong>Valid only if trees are specified <em>a priori</em></strong>.</li>
      <li><strong>Invalid usage:</strong> Testing the ML tree (derived from data) against other trees. Suffers from <em>selection bias</em>, tending to falsely reject non-ML trees.</li>
    </ul>
  </li>
  <li><strong>Shimodaira-Hasegawa (S-H) Test (1999):</strong> Corrects for selection bias by considering a set of candidate trees and comparing them. Very conservative.</li>
  <li><strong>AU (Approximately Unbiased) Test (Shimodaira 2002):</strong> Less conservative than S-H, controls overall type-I error rate in most cases. Implemented in CONSEL.</li>
  <li><strong>Null Hypothesis:</strong> Underlying K-H and S-H tests is somewhat unclear, often related to $E[l_1/n] = E[l_2/n]$.</li>
</ul>

<h3 id="544-example-phylogeny-of-apes">5.4.4 Example: Phylogeny of Apes</h3>
<ul>
  <li>Bootstrap on 7 ape mitochondrial proteins (Table 5.1).
    <ul>
      <li>ML tree $\tau_1$: 99.4% bootstrap support (RELL: 98.7%).</li>
      <li>Alternative $\tau_2$: bootstrap 0.3% (RELL: 1.0%).</li>
      <li>K-H test: $p=0.014$ for $\tau_2$ vs $\tau_1$ (rejects $\tau_2$ at 5% but not 1%). (Fails to correct for multiple comparisons).</li>
      <li>S-H test: $p=0.781$ for $\tau_2$ (fails to reject). Much more conservative.</li>
    </ul>
  </li>
</ul>

<h3 id="545-indexes-used-in-parsimony-analysis">5.4.5 Indexes Used in Parsimony Analysis</h3>
<p>(Often reported but lack straightforward statistical interpretation).</p>
<ul>
  <li><strong>5.4.5.1 Decay Index (Bremer Support):</strong> Difference in tree length (steps) between the most parsimonious tree and the shortest tree <em>not</em> containing a particular split. “Cost” of removing a split.</li>
  <li><strong>5.4.5.2 Winning-Sites Test:</strong> Compares two trees site by site based on parsimony score. Similar to K-H test logic.</li>
  <li><strong>5.4.5.3 Consistency Index (CI) and Retention Index (RI):</strong>
    <ul>
      <li>CI (for a character) = $m/s$ (min possible changes / actual changes on tree). CI (for dataset) = $\sum m_i / \sum s_i$. Range 0 (high homoplasy) to 1 (perfect fit).</li>
      <li>RI = $(\sum M_i - \sum s_i) / (\sum M_i - \sum m_i)$, where $M_i$ is max conceivable steps. Range 0 to 1.</li>
      <li><strong>Problem:</strong> For molecular data, CI and RI are poor indicators of phylogenetic information or parsimony’s success (Fig. 5.6 shows CI barely changes while $P_c$ (prob. of correct tree) varies greatly).</li>
    </ul>
  </li>
</ul>

<h1 id="6-bayesian-theory">6. Bayesian theory</h1>

<h2 id="61-overview">6.1 Overview</h2>

<p>This chapter introduces Bayesian statistics, contrasting it with the classical Frequentist approach, and lays the groundwork for its application in molecular evolution.</p>

<ul>
  <li><strong>Two Principal Philosophies:</strong>
    <ul>
      <li><strong>Frequentist:</strong> Defines probability as the long-run frequency of an event in repeated trials. Performance of inference is judged by properties in repeated sampling (e.g., bias, variance, confidence intervals, p-values). Maximum likelihood (ML) and likelihood ratio tests (LRT) are key tools.</li>
      <li><strong>Bayesian:</strong> Defines probability as a degree of belief in a hypothesis or parameter value. It uses probability distributions to describe uncertainty in parameters.
        <ul>
          <li><strong>Prior Distribution $f(\theta)$:</strong> Represents belief about parameter $\theta$ <em>before</em> seeing the data.</li>
          <li><strong>Posterior Distribution $f(\theta\vert X)$:</strong> Represents updated belief about $\theta$ <em>after</em> observing data $X$, combining prior information with information from the data.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Historical Context:</strong>
    <ul>
      <li>Probability theory developed over centuries (gambling). Statistics is younger.</li>
      <li>Regression/correlation (Galton, Pearson, ~1900).</li>
      <li>Classical statistics blossomed with R.A. Fisher (1920s-30s): likelihood, ANOVA, experimental design.</li>
      <li>Hypothesis testing/confidence intervals (Neyman, Egon Pearson, ~same time).</li>
      <li>Bayesian ideas are older (Thomas Bayes, 1763; Laplace). Initially not popular among 20th-century statisticians due to:
        <ol>
          <li><strong>Philosophical objections:</strong> Reliance on subjective priors.</li>
          <li><strong>Computational challenges:</strong> Calculating posterior probabilities often involves high-dimensional integrals, historically intractable.</li>
        </ol>
      </li>
    </ul>
  </li>
  <li><strong>Modern Resurgence:</strong>
    <ul>
      <li><strong>Markov Chain Monte Carlo (MCMC) algorithms</strong> (Metropolis et al. 1953; Hastings 1970; Gelfand &amp; Smith 1990) revolutionized Bayesian computation, making complex models feasible.</li>
      <li>Bayesian inference now widely applied. Excitement has tempered as implementation complexities are appreciated.</li>
    </ul>
  </li>
  <li><strong>Chapter Scope:</strong> Overview of Bayesian theory and computation. Simple examples will be used, with more complex phylogenetic applications in later chapters.</li>
</ul>

<h2 id="62-the-bayesian-paradigm">6.2 The Bayesian Paradigm</h2>

<h3 id="621-the-bayes-theorem">6.2.1 The Bayes Theorem</h3>
<ul>
  <li><strong>Law of Total Probability:</strong> For events A and B:
$P(B) = P(AB) + P(\bar{A}B) = P(A)P(B\vert A) + P(\bar{A})P(B\vert \bar{A})$ (Eq 6.1)
where $\bar{A}$ is “non A”, $AB$ is “A and B”.</li>
  <li><strong>Bayes’ Theorem (Inverse Probability):</strong> Gives the conditional probability of A given B:
$P(A\vert B) = \frac{P(AB)}{P(B)} = \frac{P(A)P(B\vert A)}{P(B)} = \frac{P(A)P(B\vert A)}{P(A)P(B\vert A) + P(\bar{A})P(B\vert \bar{A})}$ (Eq 6.2)</li>
  <li><strong>Example 6.1 (False Positives of a Clinical Test):</strong>
    <ul>
      <li>Let A = person has infection, $\bar{A}$ = no infection. B = test positive.</li>
      <li>Given: $P(A) = 0.001$ (prevalence), $P(\bar{A}) = 0.999$.</li>
      <li>Test accuracy: $P(B\vert A) = 0.99$ (true positive rate/sensitivity), $P(B\vert \bar{A}) = 0.02$ (false positive rate, so $1-P(B\vert \bar{A})=0.98$ is specificity).</li>
      <li>Probability of a random person testing positive:
$P(B) = (0.001 \times 0.99) + (0.999 \times 0.02) = 0.00099 + 0.01998 = 0.02097$ (Eq 6.3)</li>
      <li>Probability of having infection given a positive test:
$P(A\vert B) = \frac{P(A)P(B\vert A)}{P(B)} = \frac{0.001 \times 0.99}{0.02097} \approx 0.0472$ (Eq 6.4)</li>
      <li>Despite high test accuracy, only ~4.72% of those testing positive actually have the infection due to low prevalence. Most positives are false positives.</li>
    </ul>
  </li>
</ul>

<h3 id="622-the-bayes-theorem-in-bayesian-statistics">6.2.2 The Bayes Theorem in Bayesian Statistics</h3>
<ul>
  <li>Hypotheses $H_1, H_2, …, H_k$ replace events A, $\bar{A}$. Observed data $X$ replaces event B.</li>
  <li>For two hypotheses $H_1, H_2$:
$P(H_1\vert X) = \frac{P(H_1)P(X\vert H_1)}{P(X)} = \frac{P(H_1)P(X\vert H_1)}{P(H_1)P(X\vert H_1) + P(H_2)P(X\vert H_2)}$ (Eq 6.5)
    <ul>
      <li>$P(H_i)$: <strong>Prior probability</strong> of hypothesis $H_i$.</li>
      <li>$P(X\vert H_i)$: <strong>Likelihood</strong> of data $X$ under $H_i$.</li>
      <li>$P(H_i\vert X)$: <strong>Posterior probability</strong> of hypothesis $H_i$ given data $X$.</li>
      <li>$P(X)$: Marginal likelihood of data (normalizing constant).</li>
    </ul>
  </li>
  <li><strong>Continuous Parameters ($\theta$):</strong> Uses probability densities.
$f(\theta\vert X) = \frac{f(\theta)f(X\vert \theta)}{f(X)} = \frac{f(\theta)f(X\vert \theta)}{\int f(\theta’)f(X\vert \theta’) d\theta’}$ (Eq 6.6)
“Posterior $\propto$ Prior $\times$ Likelihood”
    <ul>
      <li>$f(\theta)$: Prior density.</li>
      <li>$f(X\vert \theta)$: Likelihood function (probability of data given $\theta$).</li>
      <li>$f(\theta\vert X)$: Posterior density.</li>
      <li>$f(X) = \int f(\theta)f(X\vert \theta) d\theta$: Marginal likelihood of data / Normalizing constant / Evidence.</li>
    </ul>
  </li>
  <li><strong>Inference from Posterior Distribution:</strong>
    <ul>
      <li><strong>Point Estimate:</strong> Mean, median, or mode of $f(\theta\vert X)$.</li>
      <li><strong>Interval Estimation (Credibility Interval):</strong>
        <ul>
          <li><strong>Equal-Tail Credibility Interval (CI):</strong> Interval $(\theta_L, \theta_U)$ such that $P(\theta &lt; \theta_L\vert X) = \alpha/2$ and $P(\theta &gt; \theta_U\vert X) = \alpha/2$. For 95% CI, use 2.5% and 97.5% quantiles. (Fig 6.2a)</li>
          <li><strong>Highest Posterior Density (HPD) Interval:</strong> Smallest interval containing $(1-\alpha)$ posterior probability. Every point inside has higher density than any point outside. May be disjoint if posterior is multimodal. (Fig 6.2b)</li>
          <li>If posterior is symmetric and unimodal, equal-tail CI and HPD interval are similar.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Nuisance Parameters:</strong> Bayesian approach naturally handles them through marginalization.
    <ul>
      <li>If $\theta = (\lambda, \eta)$ where $\lambda$ are parameters of interest and $\eta$ are nuisance parameters.</li>
      <li>Joint posterior: $f(\lambda, \eta\vert X)$ (Eq 6.7)</li>
      <li>Marginal posterior for $\lambda$: $f(\lambda\vert X) = \int f(\lambda, \eta\vert X) d\eta$ (Eq 6.8)</li>
    </ul>
  </li>
  <li><strong>Example 6.2 (Estimation of Binomial Probability $\theta$):</strong>
    <ul>
      <li>Data: $x$ successes in $n$ trials. Likelihood: $f(x\vert \theta) = \binom{n}{x} \theta^x (1-\theta)^{n-x}$ (Eq 6.9)</li>
      <li>Prior: Beta distribution, $\theta \sim \text{Beta}(a,b)$, $f(\theta) = \frac{1}{B(a,b)} \theta^{a-1}(1-\theta)^{b-1}$ (Eq 6.10)
        <ul>
          <li>$B(a,b) = \frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}$ is the Beta function. Mean $a/(a+b)$.</li>
        </ul>
      </li>
      <li>Posterior: $f(\theta\vert x) = \frac{f(\theta)f(x\vert \theta)}{f(x)}$.
        <ul>
          <li>Marginal likelihood: $f(x) = \int_0^1 f(\theta)f(x\vert \theta)d\theta = \binom{n}{x} \frac{B(x+a, n-x+b)}{B(a,b)}$ (Eq 6.12)</li>
          <li>Posterior distribution: $\theta\vert x \sim \text{Beta}(x+a, n-x+b)$ (Eq 6.13)</li>
          <li>The Beta distribution is a <strong>conjugate prior</strong> for the binomial likelihood (prior and posterior are in the same family).</li>
          <li>Information in prior $\text{Beta}(a,b)$ is like observing $a$ successes in $a+b$ trials.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Example 6.3 (Laplace’s Rule of Succession):</strong>
    <ul>
      <li>Event occurred $x$ times in $n$ trials. Probability of occurring in next trial?</li>
      <li>Prior: Uniform, $\theta \sim U(0,1)$, which is $\text{Beta}(1,1)$.</li>
      <li>Posterior: $\theta\vert x \sim \text{Beta}(x+1, n-x+1)$.</li>
      <li>Probability of success in $(n+1)^{th}$ trial = Posterior mean $E(\theta\vert x) = \frac{x+1}{n+2}$ (Eq 6.14)</li>
      <li>Laplace’s sunrise example: if sun rose for $n$ days, $P(\text{sun rises tomorrow}) = (n+1)/(n+2)$.</li>
      <li>Based on “principle of insufficient reason” (uniform prior for $\theta$). Problematic as priors are not invariant to non-linear transformations.</li>
    </ul>
  </li>
  <li><strong>Example 6.4 (Bayesian Estimation of JC69 Distance $\theta$):</strong>
    <ul>
      <li>Data: $x$ differences in $n$ sites. Likelihood $f(x\vert \theta)$ (Eq 6.19 from $p = \frac{3}{4}(1-e^{-4\theta/3})$ (Eq 6.18)).</li>
      <li>Prior: Exponential, $f(\theta) = \frac{1}{\mu} e^{-\theta/\mu}$ with mean $\mu=0.2$ (Eq 6.16).</li>
      <li>Posterior: $f(\theta\vert x) = \frac{f(\theta)f(x\vert \theta)}{\int_0^\infty f(\theta’)f(x\vert \theta’)d\theta’}$ (Eq 6.17)</li>
      <li>For human-orangutan 12S rRNA ($x=90, n=948$), MLE $\hat{\theta}=0.1015$.</li>
      <li>Posterior mean $E(\theta\vert x) = 0.10213$. Mode $0.10092$.</li>
      <li>95% Equal-tail CI: $(0.08191, 0.12463)$.</li>
      <li>95% HPD Interval: $(0.08116, 0.12377)$.</li>
    </ul>

    <div class="language-r highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">###############################################################</span><span class="w">
</span><span class="c1">##  JC69 distance (θ) – Bayesian and Classical inference</span><span class="w">
</span><span class="c1">##  Data: x = 90 differences, n = 948 sites (human vs. orang-utan 12S rRNA)</span><span class="w">
</span><span class="c1">###############################################################</span><span class="w">
</span><span class="n">library</span><span class="p">(</span><span class="n">HDInterval</span><span class="p">)</span><span class="w">
</span><span class="n">library</span><span class="p">(</span><span class="n">pracma</span><span class="p">)</span><span class="w">

</span><span class="n">n</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">948</span><span class="p">;</span><span class="w">  </span><span class="n">x</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="m">90</span><span class="w">
</span><span class="n">p_fun</span><span class="w">  </span><span class="o">&lt;-</span><span class="w"> </span><span class="k">function</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span><span class="w"> </span><span class="m">0.75</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="m">0.75</span><span class="o">*</span><span class="nf">exp</span><span class="p">(</span><span class="m">-4</span><span class="o">*</span><span class="n">theta</span><span class="o">/</span><span class="m">3</span><span class="p">)</span><span class="w">
</span><span class="n">logLik</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="k">function</span><span class="p">(</span><span class="n">theta</span><span class="p">){</span><span class="w">
    </span><span class="n">p</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">p_fun</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span><span class="w">
    </span><span class="nf">log</span><span class="p">(</span><span class="n">p</span><span class="o">^</span><span class="n">x</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="p">(</span><span class="m">1</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">p</span><span class="p">)</span><span class="o">^</span><span class="p">(</span><span class="n">n</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">x</span><span class="p">))</span><span class="w">
</span><span class="p">}</span><span class="w">

</span><span class="n">mu_values</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="m">0.01</span><span class="p">,</span><span class="w"> </span><span class="m">0.1</span><span class="p">,</span><span class="w"> </span><span class="m">1</span><span class="p">,</span><span class="w"> </span><span class="m">10</span><span class="p">)</span><span class="w">  </span><span class="c1"># Four very different mu</span><span class="w">
</span><span class="n">grid</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">seq</span><span class="p">(</span><span class="m">0</span><span class="p">,</span><span class="w"> </span><span class="m">0.25</span><span class="p">,</span><span class="w"> </span><span class="n">length.out</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">10001</span><span class="p">)</span><span class="w">

</span><span class="n">par</span><span class="p">(</span><span class="n">mfrow</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="m">2</span><span class="p">,</span><span class="m">2</span><span class="p">),</span><span class="w"> </span><span class="n">mar</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="m">4</span><span class="p">,</span><span class="m">4</span><span class="p">,</span><span class="m">2</span><span class="p">,</span><span class="m">1</span><span class="p">))</span><span class="w">
</span><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="n">mu</span><span class="w"> </span><span class="k">in</span><span class="w"> </span><span class="n">mu_values</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span><span class="n">prior</span><span class="w">   </span><span class="o">&lt;-</span><span class="w"> </span><span class="k">function</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="m">1</span><span class="o">/</span><span class="n">mu</span><span class="p">)</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="nf">exp</span><span class="p">(</span><span class="o">-</span><span class="n">theta</span><span class="o">/</span><span class="n">mu</span><span class="p">)</span><span class="w">
</span><span class="n">log_u</span><span class="w">   </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">log</span><span class="p">(</span><span class="n">prior</span><span class="p">(</span><span class="n">grid</span><span class="p">))</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">logLik</span><span class="p">(</span><span class="n">grid</span><span class="p">)</span><span class="w">
</span><span class="n">u</span><span class="w">       </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">exp</span><span class="p">(</span><span class="n">log_u</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nf">max</span><span class="p">(</span><span class="n">log_u</span><span class="p">))</span><span class="w">
</span><span class="n">post</span><span class="w">    </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">u</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="nf">sum</span><span class="p">(</span><span class="n">u</span><span class="p">)</span><span class="w">
</span><span class="n">post_mean</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">sum</span><span class="p">(</span><span class="n">grid</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">post</span><span class="p">)</span><span class="w">
</span><span class="n">theta_samp</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">sample</span><span class="p">(</span><span class="n">grid</span><span class="p">,</span><span class="w"> </span><span class="m">5e5</span><span class="p">,</span><span class="w"> </span><span class="n">replace</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">TRUE</span><span class="p">,</span><span class="w"> </span><span class="n">prob</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">post</span><span class="p">)</span><span class="w">
</span><span class="n">HPD</span><span class="w">  </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">hdi</span><span class="p">(</span><span class="n">theta_samp</span><span class="p">,</span><span class="w"> </span><span class="n">credMass</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">0.95</span><span class="p">)</span><span class="w">
    
</span><span class="n">dens_post</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">post</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="n">diff</span><span class="p">(</span><span class="n">grid</span><span class="p">[</span><span class="m">1</span><span class="o">:</span><span class="m">2</span><span class="p">])</span><span class="w">
</span><span class="n">dens_prior</span><span class="o">&lt;-</span><span class="w"> </span><span class="n">prior</span><span class="p">(</span><span class="n">grid</span><span class="p">);</span><span class="w"> </span><span class="n">dens_prior</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">dens_prior</span><span class="o">/</span><span class="w"> </span><span class="n">trapz</span><span class="p">(</span><span class="n">grid</span><span class="p">,</span><span class="w"> </span><span class="n">dens_prior</span><span class="p">)</span><span class="w">
</span><span class="n">lik</span><span class="w">       </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">exp</span><span class="p">(</span><span class="n">logLik</span><span class="p">(</span><span class="n">grid</span><span class="p">));</span><span class="w"> </span><span class="n">lik</span><span class="w">  </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">lik</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="n">trapz</span><span class="p">(</span><span class="n">grid</span><span class="p">,</span><span class="w"> </span><span class="n">lik</span><span class="p">)</span><span class="w">
    
</span><span class="c1"># MLE and profile likelihood CI</span><span class="w">
</span><span class="n">loglik_vals</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">logLik</span><span class="p">(</span><span class="n">grid</span><span class="p">)</span><span class="w">
</span><span class="n">mle_idx</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">which.max</span><span class="p">(</span><span class="n">loglik_vals</span><span class="p">)</span><span class="w">
</span><span class="n">mle_theta</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">grid</span><span class="p">[</span><span class="n">mle_idx</span><span class="p">]</span><span class="w">
</span><span class="n">cutoff</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">max</span><span class="p">(</span><span class="n">loglik_vals</span><span class="p">)</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="m">0.5</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">qchisq</span><span class="p">(</span><span class="m">0.95</span><span class="p">,</span><span class="w"> </span><span class="n">df</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">1</span><span class="p">)</span><span class="w">
</span><span class="n">ci_idx</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">which</span><span class="p">(</span><span class="n">loglik_vals</span><span class="w"> </span><span class="o">&gt;=</span><span class="w"> </span><span class="n">cutoff</span><span class="p">)</span><span class="w">
</span><span class="n">ci_theta</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nf">range</span><span class="p">(</span><span class="n">grid</span><span class="p">[</span><span class="n">ci_idx</span><span class="p">])</span><span class="w">
    
</span><span class="n">plot</span><span class="p">(</span><span class="n">grid</span><span class="p">,</span><span class="w"> </span><span class="n">dens_post</span><span class="p">,</span><span class="w"> </span><span class="n">type</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"l"</span><span class="p">,</span><span class="w"> </span><span class="n">lwd</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2</span><span class="p">,</span><span class="w">
    </span><span class="n">ylab</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"Density"</span><span class="p">,</span><span class="w"> </span><span class="n">xlab</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">expression</span><span class="p">(</span><span class="n">theta</span><span class="p">),</span><span class="w">
    </span><span class="n">main</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">bquote</span><span class="p">(</span><span class="n">mu</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="n">.</span><span class="p">(</span><span class="n">mu</span><span class="p">)))</span><span class="w">
</span><span class="n">lines</span><span class="p">(</span><span class="n">grid</span><span class="p">,</span><span class="w"> </span><span class="n">dens_prior</span><span class="p">,</span><span class="w"> </span><span class="n">lty</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2</span><span class="p">,</span><span class="w"> </span><span class="n">col</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"red"</span><span class="p">,</span><span class="w"> </span><span class="n">lwd</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2</span><span class="p">)</span><span class="w">
</span><span class="n">lines</span><span class="p">(</span><span class="n">grid</span><span class="p">,</span><span class="w"> </span><span class="n">lik</span><span class="p">,</span><span class="w"> </span><span class="n">lty</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">3</span><span class="p">,</span><span class="w"> </span><span class="n">col</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"darkgreen"</span><span class="p">,</span><span class="w"> </span><span class="n">lwd</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2</span><span class="p">)</span><span class="w">
</span><span class="n">abline</span><span class="p">(</span><span class="n">v</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">post_mean</span><span class="p">,</span><span class="w"> </span><span class="n">col</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"blue"</span><span class="p">,</span><span class="w"> </span><span class="n">lwd</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2</span><span class="p">)</span><span class="w">
</span><span class="n">polygon</span><span class="p">(</span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="n">HPD</span><span class="p">[</span><span class="m">1</span><span class="p">],</span><span class="w"> </span><span class="n">HPD</span><span class="p">[</span><span class="m">2</span><span class="p">],</span><span class="w"> </span><span class="n">HPD</span><span class="p">[</span><span class="m">2</span><span class="p">],</span><span class="w"> </span><span class="n">HPD</span><span class="p">[</span><span class="m">1</span><span class="p">]),</span><span class="w">
        </span><span class="n">y</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="m">0</span><span class="p">,</span><span class="m">0</span><span class="p">,</span><span class="nf">max</span><span class="p">(</span><span class="n">dens_post</span><span class="p">),</span><span class="nf">max</span><span class="p">(</span><span class="n">dens_post</span><span class="p">)),</span><span class="w">
        </span><span class="n">col</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">adjustcolor</span><span class="p">(</span><span class="s2">"blue"</span><span class="p">,</span><span class="m">0.15</span><span class="p">),</span><span class="w"> </span><span class="n">border</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">NA</span><span class="p">)</span><span class="w">
</span><span class="c1"># Add MLE and profile likelihood CI</span><span class="w">
</span><span class="n">abline</span><span class="p">(</span><span class="n">v</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">mle_theta</span><span class="p">,</span><span class="w"> </span><span class="n">col</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"purple"</span><span class="p">,</span><span class="w"> </span><span class="n">lwd</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2</span><span class="p">,</span><span class="w"> </span><span class="n">lty</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2</span><span class="p">)</span><span class="w">
</span><span class="n">polygon</span><span class="p">(</span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="n">ci_theta</span><span class="p">[</span><span class="m">1</span><span class="p">],</span><span class="w"> </span><span class="n">ci_theta</span><span class="p">[</span><span class="m">2</span><span class="p">],</span><span class="w"> </span><span class="n">ci_theta</span><span class="p">[</span><span class="m">2</span><span class="p">],</span><span class="w"> </span><span class="n">ci_theta</span><span class="p">[</span><span class="m">1</span><span class="p">]),</span><span class="w">
        </span><span class="n">y</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="m">0</span><span class="p">,</span><span class="m">0</span><span class="p">,</span><span class="nf">max</span><span class="p">(</span><span class="n">dens_post</span><span class="p">),</span><span class="nf">max</span><span class="p">(</span><span class="n">dens_post</span><span class="p">)),</span><span class="w">
        </span><span class="n">col</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">adjustcolor</span><span class="p">(</span><span class="s2">"purple"</span><span class="p">,</span><span class="m">0.15</span><span class="p">),</span><span class="w"> </span><span class="n">border</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">NA</span><span class="p">)</span><span class="w">
</span><span class="n">legend</span><span class="p">(</span><span class="s2">"topright"</span><span class="p">,</span><span class="w">
        </span><span class="nf">c</span><span class="p">(</span><span class="s2">"Posterior"</span><span class="p">,</span><span class="s2">"Prior"</span><span class="p">,</span><span class="s2">"Likelihood"</span><span class="p">,</span><span class="w">
        </span><span class="s2">"Posterior mean"</span><span class="p">,</span><span class="s2">"95% HPD"</span><span class="p">,</span><span class="w">
        </span><span class="s2">"MLE"</span><span class="p">,</span><span class="s2">"95% Profile Likelihood CI"</span><span class="p">),</span><span class="w">
        </span><span class="n">lty</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="m">1</span><span class="p">,</span><span class="m">2</span><span class="p">,</span><span class="m">3</span><span class="p">,</span><span class="m">1</span><span class="p">,</span><span class="w"> </span><span class="kc">NA</span><span class="p">,</span><span class="w"> </span><span class="m">2</span><span class="p">,</span><span class="w"> </span><span class="kc">NA</span><span class="p">),</span><span class="w">
        </span><span class="n">lwd</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="m">2</span><span class="p">,</span><span class="m">2</span><span class="p">,</span><span class="m">2</span><span class="p">,</span><span class="m">2</span><span class="p">,</span><span class="w"> </span><span class="kc">NA</span><span class="p">,</span><span class="w"> </span><span class="m">2</span><span class="p">,</span><span class="w"> </span><span class="kc">NA</span><span class="p">),</span><span class="w">
        </span><span class="n">pch</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="kc">NA</span><span class="p">,</span><span class="kc">NA</span><span class="p">,</span><span class="kc">NA</span><span class="p">,</span><span class="kc">NA</span><span class="p">,</span><span class="w"> </span><span class="m">15</span><span class="p">,</span><span class="w"> </span><span class="kc">NA</span><span class="p">,</span><span class="w"> </span><span class="m">15</span><span class="p">),</span><span class="w">
        </span><span class="n">col</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"black"</span><span class="p">,</span><span class="s2">"red"</span><span class="p">,</span><span class="s2">"darkgreen"</span><span class="p">,</span><span class="s2">"blue"</span><span class="p">,</span><span class="w">
                </span><span class="n">adjustcolor</span><span class="p">(</span><span class="s2">"blue"</span><span class="p">,</span><span class="m">0.4</span><span class="p">),</span><span class="w">
                </span><span class="s2">"purple"</span><span class="p">,</span><span class="w"> </span><span class="n">adjustcolor</span><span class="p">(</span><span class="s2">"purple"</span><span class="p">,</span><span class="m">0.4</span><span class="p">)),</span><span class="w">
        </span><span class="n">pt.cex</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">1.2</span><span class="p">,</span><span class="w"> </span><span class="n">bty</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"n"</span><span class="p">)</span><span class="w">
</span><span class="p">}</span><span class="w">
</span><span class="n">par</span><span class="p">(</span><span class="n">mfrow</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="m">1</span><span class="p">,</span><span class="m">1</span><span class="p">))</span><span class="w">

</span></code></pre></div>    </div>
    <p><img src="/files/MESA/example_6.4.png" alt="alt text" /></p>
  </li>
</ul>

<h3 id="623-classical-versus-bayesian-statistics">*6.2.3 Classical versus Bayesian Statistics</h3>
<ul>
  <li><strong>6.2.3.1 Criticisms of Frequentist Statistics (from Bayesian perspective):</strong>
    <ul>
      <li>Frequentist methods make probability statements about data or procedures, not directly about parameters of interest after data is observed.</li>
      <li><strong>Confidence Intervals:</strong> A 95% CI means that if we repeat the experiment many times, 95% of <em>such constructed intervals</em> will contain the true parameter. It does <em>not</em> mean there’s a 95% probability that the <em>specific interval we calculated</em> contains the true parameter. (Fig 6.4)</li>
      <li><strong>p-values:</strong> The probability of observing data as extreme or more extreme than what was actually observed, <em>if the null hypothesis ($H_0$) were true</em>. It is <em>not</em> $P(H_0\vert \text{data})$.
        <ul>
          <li><strong>Likelihood Principle Violation:</strong> p-values can depend on the stopping rule of an experiment (e.g., fixed $n$ trials vs. fixed number of successes), even if the likelihood function $L(\theta\vert x)$ is the same. (Fig 6.5 - binomial vs. negative binomial). Bayesian inference respects the likelihood principle.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>6.2.3.2 Criticisms of Bayesian Methods (from Frequentist perspective):</strong>
    <ul>
      <li>Levied on the <strong>prior distribution $f(\theta)$</strong>.</li>
      <li><strong>Objective Bayes:</strong> Aims to represent “prior ignorance.”
        <ul>
          <li>Uniform priors (principle of insufficient reason) seem intuitive for ignorance but lead to contradictions because they are not invariant to parameter transformations (e.g., uniform on side length $a$ vs. uniform on area $A=a^2$).</li>
          <li>No single prior truly represents “total ignorance.”</li>
        </ul>
      </li>
      <li><strong>Subjective Bayes:</strong> Prior represents researcher’s personal belief.
        <ul>
          <li>Classical statisticians reject incorporating personal beliefs into scientific inference.</li>
          <li>Likelihood models also involve subjectivity but can be checked against data; priors often cannot.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>6.2.3.3 Does it Matter?</strong>
    <ol>
      <li><strong>Stable Estimation Problems:</strong> Well-formulated model, large dataset. Prior has little effect. Likelihood and Bayesian estimates (and CIs/credibility intervals) are similar. (e.g., Example 6.4, Fig 6.3, Fig 6.6).</li>
      <li><strong>Prior and Likelihood Both Influential:</strong> Ill-formulated/barely identifiable models, sparse data. Posterior is sensitive to prior. Classical and Bayesian results may differ.</li>
      <li><strong>Hypothesis Testing/Model Selection with Vague Priors:</strong> Bayesian results can be highly sensitive to prior choice.
        <ul>
          <li><strong>Lindley’s Paradox:</strong> For $H_0: \mu=0$ vs. $H_1: \mu \ne 0$ (normal data). Large $n$, small $\bar{x}$ can lead to small p-value (reject $H_0$), but Bayesian analysis with a diffuse prior on $\mu$ under $H_1$ can strongly support $H_0$ ($P_0 \approx 1$). (Eq 6.27-6.33)</li>
          <li>This happens because a diffuse prior spreads probability thinly over a wide range, making the marginal likelihood $M_1 = \int L_1(\mu)f(\mu\vert H_1)d\mu$ small.</li>
          <li>The posterior model probability $P_0$ is sensitive to the “diffuseness” (e.g., variance $\sigma_0^2$) of the prior on $\mu$ under $H_1$. (Eq 6.33, 6.36)</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h2 id="63-prior">6.3 Prior</h2>

<p>Specification of the prior distribution $f(\theta)$.</p>

<h3 id="631-methods-of-prior-specification">6.3.1 Methods of Prior Specification</h3>
<ul>
  <li>Prior should reflect belief <em>before</em> data analysis. Can use past experiments or model the physical/biological process.</li>
  <li><strong>Vague/Diffuse Priors (Objective Bayes idea):</strong> Used when little prior information.
    <ul>
      <li>Principle of insufficient reason (uniform).</li>
      <li>Invariance to reparameterization (Jeffreys prior).</li>
      <li>Maximization of missing information (Reference prior).</li>
    </ul>
  </li>
  <li><strong>Hierarchical Bayesian Approach:</strong> If prior involves unknown parameters (hyper-parameters), assign priors to them (hyper-priors). Usually 2-3 levels.</li>
  <li><strong>Empirical Bayes (EB):</strong> Estimate hyper-parameters from the marginal likelihood of the data $f(x\vert \text{hyper-param}) = \int f(\theta\vert \text{hyper-param})f(x\vert \theta)d\theta$, then use these estimates in the prior for $\theta$. Widely used in phylogenetics (e.g., estimating site rates, ASR).</li>
  <li><strong>Robustness Analysis:</strong> Always assess sensitivity of posterior to prior choice. If posterior dominated by data, prior choice is less critical.</li>
</ul>

<h3 id="632-conjugate-priors">6.3.2 Conjugate Priors</h3>
<ul>
  <li>Prior and posterior have the same distributional form. Likelihood updates parameters of the distribution.
    <ul>
      <li><strong>Beta prior for binomial $\theta$:</strong> Likelihood $\theta^x(1-\theta)^{n-x}$. Prior $\theta^{a-1}(1-\theta)^{b-1}$. Posterior $\theta^{x+a-1}(1-\theta)^{n-x+b-1}$. (Eq 6.37-6.39)
        <ul>
          <li>$U(0,1) \equiv \text{Beta}(1,1)$.</li>
          <li>Jeffreys prior for binomial $\theta$ is $\text{Beta}(1/2, 1/2)$.</li>
          <li>Haldane’s prior $\text{Beta}(0,0)$ (improper, $f(\theta) \propto \theta^{-1}(1-\theta)^{-1}$) gives posterior mean = MLE ($x/n$).</li>
        </ul>
      </li>
      <li><strong>Gamma prior for Poisson rate $\lambda$:</strong> Likelihood $\lambda^{\sum x_i} e^{-n\lambda}$. Prior $\lambda^{\alpha-1}e^{-\beta\lambda}$. Posterior $\lambda^{\sum x_i+\alpha-1}e^{-(n+\beta)\lambda}$. (Eq 6.40-6.43)</li>
      <li><strong>Normal prior for normal mean $\mu$ (known $\sigma^2$):</strong> Posterior is also normal. Posterior mean is weighted average of prior mean and sample mean, weights are precisions (inverse variances). Posterior precision = prior precision + sample precision. (Eq 6.44)</li>
    </ul>
  </li>
  <li>Rarely used in complex phylogenetic models.</li>
</ul>

<h3 id="633-flat-or-uniform-priors">6.3.3 Flat or Uniform Priors</h3>
<ul>
  <li>Common when little information.</li>
  <li><strong>Improper Prior:</strong> If it doesn’t integrate to 1. Permissible if posterior is proper.</li>
  <li>May not be biologically reasonable (e.g., $U(0,10)$ for JC69 distance $\theta$ implies most distances are large, while data suggests small).</li>
  <li>Can cause MCMC convergence problems.</li>
  <li>For JC69 distance $\theta$, uniform prior on $p$ (proportion of different sites) $p \sim U(0, 3/4)$ implies $f(\theta) = \frac{4}{3}e^{-4\theta/3}$ (Eq 6.47), favoring small distances. This is more reasonable than uniform on $\theta$.</li>
</ul>

<h3 id="634-the-jeffreys-priors">*6.3.4 The Jeffreys Priors</h3>
<ul>
  <li>Based on Fisher information $I(\theta)$. Invariant to reparameterization.</li>
  <li>$f(\theta) \propto [\det I(\theta)]^{1/2}$ (Eq 6.49)
    <ul>
      <li>For binomial $\theta$: $I(\theta) = n/(\theta(1-\theta))$. Prior $f(\theta) \propto \theta^{-1/2}(1-\theta)^{-1/2}$, which is $\text{Beta}(1/2, 1/2)$. (Eq 6.52)</li>
      <li>For JC69 distance $\theta$: $f(\theta) \propto (e^{8\theta/3} + 2e^{4\theta/3} - 3)^{-1/2}$. (Eq 6.56)</li>
    </ul>
  </li>
  <li>Reference prior is often Jeffreys prior for single parameter models. Rarely used in phylogenetics.</li>
</ul>

<h3 id="635-the-reference-priors">*6.3.5 The Reference Priors</h3>
<ul>
  <li>Maximizes expected K-L divergence between prior and posterior (maximizes missing information in prior).</li>
  <li>Formal procedure for derivation. Jeffreys prior for regular single-parameter models.</li>
  <li>Rarely used in phylogenetics.</li>
</ul>

<h2 id="64-methods-of-integration">6.4 Methods of Integration</h2>

<p>Calculating the marginal likelihood $f(X) = \int f(\theta)f(X\vert \theta)d\theta$ is hard, especially for high-dimensional $\theta$.</p>

<h3 id="641-laplace-approximation">*6.4.1 Laplace Approximation</h3>
<ul>
  <li>For large sample size $n$, likelihood $L(\theta) = e^{nh(\theta)}$ is highly peaked around MLE $\hat{\theta}$.</li>
  <li>Approximate $h(\theta)$ by Taylor expansion around $\hat{\theta}$: $h(\theta) \approx h(\hat{\theta}) + \frac{1}{2}(\theta-\hat{\theta})^T H (\theta-\hat{\theta})$, where $H = \frac{d^2h}{d\theta^2}\vert _{\hat{\theta}}$.</li>
  <li>$I = \int f(\theta)e^{nh(\theta)}d\theta \approx f(\hat{\theta})L(\hat{\theta}) \sqrt{(2\pi)^p \vert V\vert }$ (Eq 6.66 for multivariate)
where $V = -(nH)^{-1}$ is the asymptotic variance-covariance matrix of $\hat{\theta}$, $p$ is dimension of $\theta$.
For univariate: $I \approx f(\hat{\theta})L(\hat{\theta}) \sqrt{2\pi V}$ (Eq 6.64).</li>
  <li>Relatively accurate for peaked likelihoods.</li>
</ul>

<h3 id="642-mid-point-and-trapezoid-methods">6.4.2 Mid-point and Trapezoid Methods</h3>
<ul>
  <li>Numerical integration by dividing interval $[a,b]$ into $n$ segments. (Fig 6.7)
    <ul>
      <li><strong>Mid-point:</strong> Sum areas of rectangles (height = function value at mid-point of segment). (Eq 6.68)</li>
      <li><strong>Trapezoid:</strong> Sum areas of trapezoids. (Eq 6.69)</li>
    </ul>
  </li>
</ul>

<h3 id="643-gaussian-quadrature">6.4.3 Gaussian Quadrature</h3>
<ul>
  <li>Approximates $\int_{-1}^1 f(x)dx \approx \sum_{i=1}^N w_i f(x_i)$ using pre-determined points $x_i$ and weights $w_i$. (Eq 6.70)</li>
  <li>Exact if $f(x)$ is a polynomial of degree $2N-1$ or less.</li>
  <li>Integral over $(a,b)$ converted to $(-1,1)$ by linear transform (Eq 6.71).</li>
  <li><strong>Curse of Dimension:</strong> For $d$-dimensional integrals, $N^d$ points needed. Feasible for low dimensions (1-3) only.</li>
</ul>

<h3 id="644-marginal-likelihood-calculation-for-jc69-distance-estimation">6.4.4 Marginal Likelihood Calculation for JC69 Distance Estimation</h3>
<ul>
  <li>Illustrates numerical integration for $I = \int_0^\infty f(\theta)f(x\vert \theta)d\theta$ from Example 6.4. (Eq 6.62)</li>
  <li>Requires transforming $\theta \in (0, \infty)$ to $y \in (-1,1)$ or similar finite range. (Table 6.1, Fig 6.8)
    <ul>
      <li>Transform 1: $y = (\theta-1)/(\theta+1)$ (Eq 6.73) $\rightarrow I_1$ (Eq 6.74)</li>
      <li>Transform 2 (based on $p$): $y = \frac{8}{3}p-1$ (Eq 6.75) $\rightarrow I_2$ (Eq 6.76)</li>
      <li>Transform 3 (log-$t_2$ sigmoid): Based on fitting log $\theta$ with a $t_2$ distribution. (Eq 6.79, 6.80)</li>
      <li>Transform 4 (log-logistic sigmoid): Based on fitting log $\theta$ with a logistic distribution. (Eq 6.82, 6.83)</li>
    </ul>
  </li>
  <li><strong>Results:</strong> Quadrature methods (esp. with good transforms like log-$t_2$ or log-logistic) are much more accurate than mid-point/trapezoid for same number of points $N$. Good transforms flatten the integrand.</li>
</ul>

<h3 id="645-monte-carlo-mc-integration">6.4.5 Monte Carlo (MC) Integration</h3>
<ul>
  <li>To compute $I = E_f[h(\theta)] = \int h(\theta)f(\theta)d\theta$.</li>
  <li>Draw $N$ samples $\theta_i$ from $f(\theta)$. Estimate $\hat{I} = \frac{1}{N}\sum_{i=1}^N h(\theta_i)$. (Eq 6.84, 6.85)</li>
  <li>Variance of $\hat{I}$ depends on $N$, not dimensionality of $\theta$. (Eq 6.86)</li>
  <li>For marginal likelihood $f(X)$, $f(\theta)$ is prior, $h(\theta)$ is likelihood $f(X\vert \theta)$.</li>
  <li>Inefficient if prior $f(\theta)$ is very different from posterior (i.e., if likelihood $h(\theta)$ is sharply peaked and prior is diffuse), as most samples $\theta_i$ will have tiny $h(\theta_i)$. (Table 6.2)</li>
</ul>

<h3 id="646-importance-sampling">6.4.6 Importance Sampling</h3>
<ul>
  <li>Sample $\theta_i$ from a different proposal distribution $g(\theta)$ instead of $f(\theta)$.</li>
  <li>$I = E_g \left[ h(\theta) \frac{f(\theta)}{g(\theta)} \right]$. Estimate $\hat{I}<em>{IS} = \frac{1}{N}\sum</em>{i=1}^N h(\theta_i) \frac{f(\theta_i)}{g(\theta_i)}$. (Eq 6.87, 6.88)
    <ul>
      <li>$w(\theta_i) = f(\theta_i)/g(\theta_i)$ are importance weights.</li>
    </ul>
  </li>
  <li>Optimal $g(\theta) \propto h(\theta)f(\theta)$ (i.e., the posterior), but this requires knowing $I$.</li>
  <li>Choose $g(\theta)$ to be similar to posterior, and heavier-tailed than $f(\theta)$.</li>
  <li>Alternative form (sampling from unnormalized $g^<em>$):
$I_{IS}^</em> = \frac{\sum h(\theta_i) f(\theta_i)/g^<em>(\theta_i)}{\sum f(\theta_i)/g^</em>(\theta_i)}$ (Eq 6.90) (More robust to unbounded $f/g$ ratios).</li>
  <li>Using log-$t_2$ or log-logistic as sampling distributions $g(\theta)$ for JC69 example greatly improves efficiency over simple MC. (Table 6.2)</li>
</ul>

<h1 id="7-bayesian-computation-mcmc">7. Bayesian computation (MCMC)</h1>

<p>This chapter delves into Markov chain Monte Carlo (MCMC) methods, which are simulation algorithms essential for Bayesian computation, particularly when the posterior distribution is complex and cannot be analyzed analytically.</p>

<h2 id="71-markov-chain-monte-carlo">7.1 Markov Chain Monte Carlo</h2>

<h3 id="711-metropolis-algorithm">7.1.1 Metropolis Algorithm</h3>
<ul>
  <li><strong>Concept:</strong> MCMC generates a <em>dependent</em> sample $(\theta_1, \theta_2, …, \theta_n)$ from a target probability density $\pi(\theta)$ (typically the posterior distribution $f(\theta\vert X)$). This sequence forms a stationary Markov chain whose states are the possible values of $\theta$.</li>
  <li><strong>Estimating Expectations:</strong> The expectation of a function $h(\theta)$ over $\pi(\theta)$, which is an integral $I = E_{\pi}{h(\theta)} = \int h(\theta)\pi(\theta) d\theta$ (Eq 7.1), can be estimated by the sample average:
$\tilde{I} = \frac{1}{n} \sum_{i=1}^{n} h(\theta_i)$ (Eq 7.2)</li>
  <li><strong>Variance of the Estimate:</strong> Unlike independent Monte Carlo integration, the variance of $\tilde{I}$ from an MCMC sample must account for autocorrelation. If $\rho_k = \text{corr}(h(\theta_i), h(\theta_{i+k}))$ is the autocorrelation at lag $k$:
$\text{var}(\tilde{I}) = \text{var}(\hat{I}) \times [1 + 2(\rho_1 + \rho_2 + \rho_3 + \dots)] = \text{var}(\hat{I}) \times \tau$ (Eq 7.3)
where $\text{var}(\hat{I})$ is the variance for an independent sample, and $\tau = [1 + 2\sum \rho_k]$ is the <strong>autocorrelation time</strong>.</li>
  <li><strong>Effective Sample Size (ESS):</strong> The efficiency of the MCMC sample relative to an independent sample is $E = \text{var}(\hat{I})/\text{var}(\tilde{I}) = 1/\tau$ (Eq 7.4). An MCMC sample of size $n$ is as informative as an independent sample of size $nE = n/\tau$.</li>
  <li><strong>Why MCMC?</strong> It’s often hard to generate <em>independent</em> samples from the posterior, but MCMC provides a way to generate <em>dependent</em> samples.</li>
</ul>

<p><strong>Metropolis Algorithm (Metropolis et al., 1953) - Illustrated with a 3-state discrete example (robot on boxes, Fig 7.1a):</strong>
Let $\theta$ take values ${1, 2, 3}$ with target probabilities $\pi_1, \pi_2, \pi_3$.</p>
<ol>
  <li><strong>Initialization:</strong> Set initial state (e.g., $\theta = 1$).</li>
  <li><strong>Proposal:</strong> Propose a new state $\theta’$ from the current state $\theta$. In this simple symmetric example, choose one of the two alternative states with probability $1/2$ each.</li>
  <li><strong>Accept/Reject:</strong>
    <ul>
      <li>If $\pi(\theta’) &gt; \pi(\theta)$, accept $\theta’$ (move to the higher box).</li>
      <li>Otherwise (if $\pi(\theta’) \le \pi(\theta)$), accept $\theta’$ with probability $\alpha = \frac{\pi(\theta’)}{\pi(\theta)}$.</li>
      <li>If the proposal is accepted, the next state is $\theta’$. Otherwise, the next state remains $\theta$.
(This can be implemented by drawing $u \sim U(0,1)$; if $u &lt; \alpha$, accept, else reject).</li>
    </ul>
  </li>
  <li><strong>Record:</strong> Print out the current state.</li>
  <li><strong>Iterate:</strong> Go to step 2.</li>
</ol>

<p><strong>Key Features of Metropolis Algorithm:</strong></p>
<ul>
  <li><strong>Ratio of Densities:</strong> Only the ratio $\frac{\pi(\theta’)}{\pi(\theta)}$ is needed, not $\pi(\theta)$ itself. This is crucial because for posteriors, $\pi(\theta) = f(\theta\vert X) = \frac{f(\theta)f(X\vert \theta)}{f(X)}$. The normalizing constant $f(X)$ (marginal likelihood) is often very hard to compute but cancels out in the ratio:
$\alpha = \min\left(1, \frac{\pi(\theta’)}{\pi(\theta)}\right) = \min\left(1, \frac{f(\theta’)f(X\vert \theta’)}{f(\theta)f(X\vert \theta)}\right)$ (Eq 7.5)
This allows sampling from the posterior without calculating $f(X)$.</li>
  <li><strong>Markov Chain:</strong> The sequence of states is a Markov chain (next state depends only on current state).</li>
  <li><strong>Stationary Distribution:</strong> If run long enough, the proportion of time spent in each state $i$ will be $\pi_i$. So, $\pi(\theta)$ is the stationary distribution of the chain.
    <ul>
      <li><em>Proof Sketch (Detailed Balance):</em> The net flow from state $i$ to state $j$ is $f_i P_{ij} - f_j P_{ji}$. If $\pi_i \le \pi_j$, then $P_{ij}$ (proposal $i \to j$) is $1 \times \text{Prob(propose j from i)}$, and $P_{ji}$ is $\frac{\pi_i}{\pi_j} \times \text{Prob(propose i from j)}$. For symmetric proposals, $\text{Prob(propose j from i)} = \text{Prob(propose i from j)}$. The net flow is proportional to $f_i - f_j \frac{\pi_i}{\pi_j}$. This flow is positive (from $i$ to $j$) if $f_i/f_j &gt; \pi_i/\pi_j$, meaning state $i$ is currently overrepresented relative to $j$. The chain moves to correct this imbalance, eventually reaching $f_i/f_j = \pi_i/\pi_j$. The chain is reversible under detailed balance.</li>
    </ul>
  </li>
  <li><strong>Continuous Parameters:</strong> The algorithm is essentially the same.
    <ul>
      <li><strong>Example 7.1 (JC69 distance $\theta$):</strong>
        <ul>
          <li>Prior: $f(\theta) = \frac{1}{\mu} e^{-\theta/\mu}$</li>
          <li>Likelihood: $f(x\vert \theta) = \left(\frac{3}{4} - \frac{3}{4}e^{-4\theta/3}\right)^x \left(\frac{1}{4} + \frac{3}{4}e^{-4\theta/3}\right)^{n-x}$ (Eq 7.6)</li>
          <li>Proposal: Sliding window $\theta’ \sim U(\theta - w/2, \theta + w/2)$. If $\theta’&lt;0$, reflect ($\theta’ = -\theta’$).</li>
          <li>Acceptance ratio $\alpha$: As in Eq 7.7 (using product of prior ratio and likelihood ratio).</li>
          <li><strong>Window Size ($w$):</strong> Critical for mixing. (Fig 7.2a)
            <ul>
              <li>Too small $w$: High acceptance ($P_{jump}$), but tiny steps (poor mixing, high autocorrelation).</li>
              <li>Too large $w$: Low acceptance ($P_{jump}$), chain gets stuck (poor mixing).</li>
              <li>Optimal $P_{jump}$ often around 20-50% (e.g., ~30-40% for normal-like 1D targets).</li>
            </ul>
          </li>
          <li><strong>Burn-in:</strong> Initial samples are discarded until the chain reaches stationarity (Fig 7.2b).</li>
          <li>Posterior can be summarized by histogram (Fig 7.2c) or kernel density estimate (Fig 7.2d).</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h3 id="712-asymmetrical-moves-and-proposal-ratio-metropolis-hastings">7.1.2 Asymmetrical Moves and Proposal Ratio (Metropolis-Hastings)</h3>
<ul>
  <li><strong>Metropolis-Hastings (MH) Algorithm (Hastings, 1970):</strong> Generalizes Metropolis to allow <em>asymmetric</em> proposal densities $q(\theta’\vert \theta)$ (probability of proposing $\theta’$ given current $\theta$).</li>
  <li><strong>Acceptance Ratio $\alpha$ modified:</strong>
$\alpha(\theta, \theta’) = \min \left(1, \frac{\pi(\theta’)}{\pi(\theta)} \times \frac{q(\theta\vert \theta’)}{q(\theta’\vert \theta)}\right)$
$= \min \left(1, \text{prior ratio} \times \text{likelihood ratio} \times \text{proposal ratio} \right)$ (Eq 7.8)
The term $\frac{q(\theta\vert \theta’)}{q(\theta’\vert \theta)}$ is the <strong>Hastings ratio</strong> or <strong>proposal ratio</strong>, correcting for asymmetry in proposals.</li>
  <li><strong>Robot Example (Fig 7.1b):</strong> Robot has ‘left bias’ (proposes left box with $2/3$, right with $1/3$).
    <ul>
      <li>If current $\theta=1$, propose $\theta’=2$. $q(2\vert 1) = 1/3$ (assuming it picks right with $1/3$). For reverse move, if current $\theta=2$, propose $\theta’=1$. $q(1\vert 2) = 2/3$ (assuming it picks left with $2/3$).</li>
      <li>Proposal ratio $q(1\vert 2)/q(2\vert 1) = (2/3)/(1/3) = 2$.</li>
    </ul>
  </li>
  <li><strong>Conditions for Convergence:</strong> Proposal density $q(\cdot\vert \cdot)$ must define an irreducible (can reach any state from any state) and aperiodic (no fixed cycles) chain.</li>
</ul>

<h3 id="713-the-transition-kernel">7.1.3 The Transition Kernel</h3>
<ul>
  <li>For a continuous state space, the Markov chain is defined by a transition kernel $p(x, y)$, the probability density of moving to state $y$ given current state $x$.</li>
  <li>For MH:
$p(x, y) = q(y\vert x) \cdot \alpha(x, y)$, for $y \neq x$
$p(x, x) = 1 - \int q(y\vert x) \cdot \alpha(x, y) dy$ (probability of rejection, staying at $x$) (Eq 7.9, 7.10, 7.11)</li>
  <li>There’s typically a point mass at $y=x$ due to rejections.</li>
  <li><strong>Acceptance Proportion ($P_{jump}$):</strong> Overall probability that a proposal is accepted.
$P_{jump} = \iint \pi(x) q(y\vert x) \alpha(x, y) dx dy = \int \pi(x) (1 - p(x,x)) dx$ (Eq 7.12)</li>
</ul>

<h3 id="714-single-component-metropolis-hastings-algorithm">7.1.4 Single-Component Metropolis-Hastings Algorithm</h3>
<ul>
  <li>For multi-parameter models $\theta = (x, y, z, \dots)$, updating all parameters simultaneously can be difficult or inefficient.</li>
  <li><strong>Single-Component MH:</strong> Update parameters (or blocks of parameters) one at a time, conditioning on the current values of other parameters.</li>
  <li><strong>Iteration (3 blocks $x,y,z$):</strong>
    <ol>
      <li>Propose $x^{\ast}$ from $q(x^{\ast} \vert x, y, z)$. Accept with probability $\alpha_x$ based on $\frac{\pi(x^{\ast}, y, z)}{\pi(x, y, z)}$ and proposal ratio for $x$. Update $x \to x’$.</li>
      <li>Propose $y^{\ast}$ from $q(y^{\ast} \vert x’, y, z)$. Accept with probability $\alpha_y$ based on $\frac{\pi(x’, y^{\ast}, z)}{\pi(x’, y, z)}$ and proposal ratio for $y$. Update $y \to y’$.</li>
      <li>Propose $z^{\ast}$ from $q(z^{\ast} \vert x’, y’, z)$. Accept with probability $\alpha_z$ based on $\frac{\pi(x’, y’, z^{\ast})}{\pi(x’, y’, z)}$ and proposal ratio for $z$. Update $z \to z’’$.</li>
    </ol>
  </li>
  <li>The ratio of joint posteriors simplifies to the ratio of <strong>full conditional distributions</strong>. For step 2:
$\frac{\pi(x’, y^{\ast}, z)}{\pi(x’, y, z)} = \frac{\pi(y^{\ast} \vert x’, z)}{\pi(y \vert x’, z)}$ (Eq 7.16)</li>
  <li>Allows tailoring proposal mechanisms for different components. Advisable to block highly correlated parameters and update them together.</li>
</ul>

<h3 id="715-gibbs-sampler">7.1.5 Gibbs Sampler</h3>
<ul>
  <li>A special case of single-component MH.</li>
  <li>To update a component (e.g., $y$), <strong>propose directly from its full conditional distribution</strong>: $q(y^{\ast} \vert x’, y, z) = \pi(y^{\ast} \vert x’, z)$.</li>
  <li>This makes the acceptance ratio $\alpha = 1$ always (Eq 7.13-7.16). All proposals are accepted.</li>
  <li>Widely used in linear models where priors and likelihoods are normal, making full conditionals also normal and easy to sample from.</li>
  <li>Seldom used in phylogenetics as full conditionals are usually complex.</li>
</ul>

<h2 id="72-simple-moves-and-their-proposal-ratios">7.2 Simple Moves and Their Proposal Ratios</h2>

<p>The proposal ratio depends only on the proposal algorithm, not the prior or likelihood.</p>
<ul>
  <li><strong>7.2.1 Sliding Window with Uniform Proposal:</strong>
    <ul>
      <li>$x’ \sim U(x - w/2, x + w/2)$ (Eq 7.17)</li>
      <li>Proposal ratio is 1 because $q(x’\vert x) = q(x\vert x’) = 1/w$.</li>
      <li><strong>Constraints:</strong> If $x \in (a,b)$, reflections are used for proposed values outside the interval. E.g., if $x’ &lt; a$, new $x’ = a + (a-x’) = 2a-x’$.</li>
      <li>Proposal ratio remains 1 even with reflections.</li>
    </ul>
  </li>
  <li><strong>7.2.2 Sliding Window with Normal Proposal:</strong>
    <ul>
      <li>$x’\vert x \sim N(x, \sigma^2)$ (Eq 7.18)</li>
      <li>Proposal ratio is 1 because $q(x’\vert x) = q(x\vert x’)$. (Normal PDF is symmetric around mean).</li>
      <li>Handles constraints by reflection, proposal ratio still 1.</li>
    </ul>
  </li>
  <li><strong>7.2.3 Bactrian Proposal (Yang &amp; Rodriguez 2013):</strong>
    <ul>
      <li>Aims to avoid proposing states very close to current state. Shaped like a two-humped camel.</li>
      <li>Standard Bactrian: 1:1 mixture of $N(-m, 1-m^2)$ and $N(m, 1-m^2)$. Mean 0, variance 1. Parameter $m \in [0,1)$ controls “spikiness”.</li>
      <li>To use as sliding window: $x’ = x + y\sigma$, where $y$ is from standard Bactrian, $\sigma$ is step size.</li>
      <li>Proposal density $q(x’\vert x; m, \sigma^2) = \frac{1}{2\sigma\sqrt{1-m^2}} \left[ \exp\left(-\frac{(x’-x+m\sigma)^2}{2\sigma^2(1-m^2)}\right) + \exp\left(-\frac{(x’-x-m\sigma)^2}{2\sigma^2(1-m^2)}\right) \right]$ (Eq 7.20)</li>
      <li>Symmetric, so proposal ratio is 1. Often more efficient than uniform/normal. $m=0.95$ is a good choice. (Fig 7.4)</li>
    </ul>
  </li>
  <li><strong>7.2.4 Sliding Window with Multivariate Normal Proposal:</strong>
    <ul>
      <li>To update $k$ parameters $x = (x_1, …, x_k)$ at once.</li>
      <li>Simplest: $x’\vert x \sim N_k(x, I\sigma^2)$ where $I$ is identity matrix. Proposal ratio 1.</li>
      <li>Inefficient if parameters have different scales or are correlated (Fig 7.5).</li>
      <li>Better: $x’\vert x \sim N_k(x, S\sigma^2)$, where $S$ is an estimate of the posterior variance-covariance matrix. (Can be estimated from pilot runs). This accounts for scales and correlations. Proposal ratio is still 1.</li>
    </ul>
  </li>
  <li><strong>7.2.5 Proportional Scaling (Multiplier Proposal):</strong>
    <ul>
      <li>Useful for positive parameters (e.g., branch lengths, rates).</li>
      <li>$x’ = x \cdot c$, where $c = e^{\lambda(u-1/2)}$ and $u \sim U(0,1)$. $\lambda$ is a tuning parameter.</li>
      <li>Proposal density (from variable transform): $q(x’\vert x) = 1/(\lambda\vert x’\vert )$ (Eq 7.22, assuming $x’&gt;0$).</li>
      <li>Proposal ratio: $q(x\vert x’)/q(x’\vert x) = \vert x’\vert /\vert x\vert  = c$.</li>
      <li>Alternative view: it’s a sliding window on $y = \log(x)$, where $y’ \sim U(y-\lambda/2, y+\lambda/2)$. Jacobian of transform $\log(x) \to x$ is $e^y=x$. Proposal ratio from Theorem 2 (Appendix A) is $x’/x = c$.</li>
      <li>Cannot move a parameter from 0. Bounds handled by reflection in log-space.</li>
      <li>Can scale multiple parameters $x_i’ = c x_i$. Proposal ratio is $c^m$ for $m$ parameters.</li>
    </ul>
  </li>
  <li><strong>7.2.6 Proportional Scaling with Bounds:</strong>
    <ul>
      <li>For $m$ variables $x_i \in (a,b)$.</li>
      <li>Transform: $y_i = (b-x_i)/(x_i-a)$, so $y_i \in (0, \infty)$. (Eq 7.23)</li>
      <li>Apply proportional scaling to $y_i$: $y_i’ = y_i \cdot c$. (Eq 7.24)</li>
      <li>Proposal ratio for $x$: $c^m \times \prod_{i=1}^m \left(\frac{x_i’-a}{x_i-a}\right)^2$. (Eq 7.26)</li>
    </ul>
  </li>
</ul>

<h2 id="73-convergence-mixing-and-summary-of-mcmc">7.3 Convergence, Mixing, and Summary of MCMC</h2>

<h3 id="731-convergence-and-tail-behaviour">7.3.1 Convergence and Tail Behaviour</h3>
<ul>
  <li><strong>7.3.1.1 Rejection Rate and Light/Heavy Tails:</strong>
    <ul>
      <li><strong>Geometric Convergence:</strong> Distance between current distribution and stationary distribution $\pi(x)$ decreases by $r^n$ ($r&lt;1$) in $n$ steps.</li>
      <li>Mengersen &amp; Tweedie (1996): For 1D MCMC, geometric convergence if and only if $\lim_{x\to\infty} \nabla \log \pi(x) &lt; 0$. (Eq 7.27)
        <ul>
          <li>This means the posterior must be <strong>light-tailed</strong> (e.g., normal, exponential, gamma).</li>
          <li>Heavy-tailed posteriors (e.g., Cauchy, t-dist, inverse gamma) may lead to non-geometric convergence (random walk behavior in tails).</li>
        </ul>
      </li>
      <li><strong>Tail Paradox:</strong> For light-tailed posteriors, the further in the tail, the flatter $\pi(x)$ is, but the steeper $\nabla \log \pi(x)$ is, leading to faster movement out of the tail. (Example: Normal distribution, Eq 7.28).</li>
      <li>For heavy-tailed posteriors (e.g., inverse gamma, Eq 7.29), $\nabla \log \pi(x) \to 0$, so acceptance ratio for moves to right approaches 1. Chain behaves like random walk, very slow convergence if started in tail.</li>
      <li><strong>Multidimensional Problem:</strong> (Roberts &amp; Tweedie, 1996) Posterior must be light-tailed AND “smooth” (no sharp ridges) (Fig 7.6 example, Eq 7.30).</li>
    </ul>
  </li>
  <li><strong>7.3.1.2 Multiple Modes in the Posterior:</strong>
    <ul>
      <li>Can cause serious convergence/mixing problems if MCMC gets trapped in a local mode.</li>
      <li>Often due to conflict between prior and likelihood (Fig 7.7, 7.8).</li>
      <li>Example: Human-chimp 12S rRNA distance. Informative (unreasonable) gamma prior $G(100,10)$ (mean 10, var 1) conflicts with likelihood (MLE $\approx 0.01172$). Posterior has two modes, one near MLE, one near prior mean (Fig 7.8). MCMC might get stuck in the very low prior-induced mode if started there.</li>
    </ul>
  </li>
</ul>

<h3 id="732-mixing-efficiency-jump-probability-and-step-length">7.3.2 Mixing Efficiency, Jump Probability, and Step Length</h3>
<p>Focus on discrete state chains first for theory, then continuous.</p>
<ul>
  <li><strong>7.3.2.1 Discrete State Chains:</strong>
    <ul>
      <li>Asymptotic variance of $\tilde{I} = \frac{1}{n}\sum h(X_i)$ can be calculated from transition matrix $P={p_{ij}}$ (Eq 7.35, 7.37). $v = h^T B (2Z - I - A) h$, where $Z = [I-(P-A)]^{-1}$ is fundamental matrix.</li>
      <li>Efficiency related to second largest eigenvalue $\lambda_2$ of $P$. Smaller $\vert \lambda_2\vert $ means better mixing.</li>
      <li><strong>Peskun’s Theorem (1973):</strong> For two reversible chains $P^{(1)}, P^{(2)}$ with same stationary $\pi$, if $p^{(1)}<em>{ij} \ge p^{(2)}</em>{ij}$ for all $i \ne j$ (i.e., $P^{(1)}$ has larger off-diagonal elements), then $P^{(1)}$ is more efficient (smaller variance for estimates of $I$). More mobile chains are better.</li>
      <li><strong>Two States:</strong> Optimal $p_{12} = \pi_2/\pi_1$ and $p_{21}=1$ (if $\pi_1 \ge \pi_2$). Efficiency $E = p_{12}/(2\pi_2 - p_{12})$. (Eq 7.40)</li>
      <li><strong>K States:</strong> Highest $P_{jump} = 2(1-\pi_1)$ (if states ordered by $\pi_i$). (Eq 7.41, 7.42).</li>
      <li>Frigessi et al. (1992) construction for P achieving optimal $\lambda_2 = -\pi_K/(1-\pi_K)$. (Eq 7.43-7.46).</li>
    </ul>
  </li>
  <li><strong>7.3.2.2 Efficiency of Continuous State Chains:</strong>
    <ul>
      <li>Discretize state space to use discrete theory.</li>
      <li>Gelman et al. (1996): For $N(0,1)$ target and $N(x, \sigma^2)$ proposal, optimal $\sigma \approx 2.5$ (relative to target SD), gives $P_{jump} \approx 0.43$, efficiency $E \approx 0.23$. (Table 7.2)</li>
      <li>Yang &amp; Rodriguez (2013): Compared proposals for different targets (Fig 7.9, 7.10, Table 7.2).
        <ul>
          <li>Bactrian proposal generally best, then uniform, then normal.</li>
          <li>Bactrian with $m=0.95$ often optimal, $P_{jump} \approx 0.3$.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>7.3.2.3 Convergence Rate and Step Length:</strong>
    <ul>
      <li>Convergence rate dominated by $R = \max_{k\ge 2} \vert \lambda_k\vert $.</li>
      <li>Optimal step length for fast convergence can be slightly larger than for efficient mixing (for uniform/normal). Suggests larger steps in burn-in.</li>
    </ul>
  </li>
  <li><strong>7.3.2.4 Automatic Adjustment of Step Length:</strong>
    <ul>
      <li>$P_{jump}$ is usually monotonic with step length $\sigma$. Can adjust $\sigma$ during burn-in to achieve target $P_{jump}$ (e.g., 0.3-0.4).</li>
      <li>For Normal target &amp; Normal proposal: $P_{jump} = \frac{2}{\pi} \tan^{-1}(\sigma/2)$. Can invert to find optimal $\sigma^*$ given current $\sigma, P_{jump}$ (Eq 7.50, 7.51, Fig 7.12, 7.13).</li>
      <li>Similar logic can be applied for Bactrian, though integral for $P_{jump}$ is more complex (Eq 7.52).</li>
    </ul>
  </li>
</ul>

<h3 id="733-validating-and-diagnosing-mcmc-algorithms">7.3.3 Validating and Diagnosing MCMC Algorithms</h3>
<ul>
  <li>MCMC enables complex models but introduces computational challenges (correctness, convergence, mixing).</li>
  <li><strong>Diagnostic Strategies:</strong>
    <ol>
      <li><strong>Time-series (Trace) Plots:</strong> Plot parameter values against iteration number. Look for stability, good exploration.</li>
      <li><strong>Acceptance Proportion:</strong> Should be in a reasonable range (e.g., 20-50% for many proposals).</li>
      <li><strong>Multiple Chains:</strong> Run from different, over-dispersed starting points. Should converge to same distribution.</li>
      <li><strong>Run with No Data:</strong> Posterior should equal prior.</li>
      <li><strong>Simulate Data:</strong> Analyze simulated data (where truth is known) to see if Bayesian estimates are consistent and CIs have correct coverage.
        <ul>
          <li><strong>Hit Probability:</strong> Proportion of CIs that include the true parameter value.</li>
          <li><strong>Coverage Probability:</strong> Average posterior probability density within a fixed prior interval.</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h3 id="734-potential-scale-reduction-statistic-hatr">7.3.4 Potential Scale Reduction Statistic ($\hat{R}$)</h3>
<ul>
  <li><strong>Gelman &amp; Rubin (1992):</strong> Uses multiple chains ($m$) of length $n$ (post burn-in).</li>
  <li>Compares within-chain variance ($W$) and between-chain variance ($B$).
    <ul>
      <li>$B = \frac{n}{m-1} \sum_{i=1}^m (\bar{x}<em>{i\cdot} - \bar{x}</em>{\cdot\cdot})^2$ (Eq 7.53)</li>
      <li>$W = \frac{1}{m(n-1)} \sum_{i=1}^m \sum_{j=1}^n (x_{ij} - \bar{x}_{i\cdot})^2$ (Eq 7.54)</li>
    </ul>
  </li>
  <li>Estimate of posterior variance: $\hat{\sigma}^2 = \frac{n-1}{n}W + \frac{1}{n}B$ (Eq 7.55)</li>
  <li><strong>Potential Scale Reduction Factor:</strong> $\hat{R} = \sqrt{\hat{\sigma}^2 / W}$ (Eq 7.56)</li>
  <li>$\hat{R}$ approaches 1 as chains converge. Values $&lt; 1.1$ or $&lt; 1.2$ often indicate convergence.</li>
</ul>

<h3 id="735-summary-of-mcmc-output">7.3.5 Summary of MCMC Output</h3>
<ul>
  <li><strong>Burn-in:</strong> Discard initial samples.</li>
  <li><strong>Thinning:</strong> Sample every $k^{th}$ iteration to reduce autocorrelation and file size (though theoretically less efficient than using all samples).</li>
  <li><strong>Marginal Posterior:</strong> For a parameter $\theta$, use its samples, ignoring others. Visualize with histogram/density plot.</li>
  <li><strong>Point Estimate:</strong> Sample mean or median.</li>
  <li><strong>Credible Interval (CI):</strong>
    <ul>
      <li><strong>Equal-tail CI:</strong> e.g., 2.5% and 97.5% percentiles of sorted samples.</li>
      <li><strong>Highest Posterior Density (HPD) Interval:</strong> Shortest interval containing (e.g.) 95% of posterior mass. For unimodal, can be found by finding shortest interval among $((j), (j+0.95n))$ from sorted samples (Fig 7.14). More complex for multimodal.</li>
    </ul>
  </li>
  <li><strong>Autocorrelation Time ($\tau$) / ESS ($n/\tau$):</strong> Can be estimated from output using methods like initial positive sequence (Geyer 1992).</li>
</ul>

<h2 id="74-advanced-monte-carlo-methods">7.4 Advanced Monte Carlo Methods</h2>

<p>This section discusses MCMC algorithms designed to handle more challenging situations, such as posteriors with multiple local peaks or the need to compare models of different dimensions.</p>

<h3 id="741-parallel-tempering-mc">7.4.1 Parallel Tempering (MC³)</h3>
<ul>
  <li><strong>Problem:</strong> Standard MCMC can get stuck in local peaks of a rugged posterior distribution (Fig 7.15).</li>
  <li><strong>Metropolis-Coupled MCMC (MC³ or MCMCMC):</strong> (Geyer 1991; Marinari &amp; Parisi 1992).
    <ul>
      <li>Run $m$ Markov chains in parallel.</li>
      <li>Each chain $j$ samples from a “heated” (flattened) version of the target posterior $\pi(\theta)$:
$\pi_j(\theta) \propto [\pi(\theta)]^{1/T_j}$ (Eq 7.57)
where $T_j$ is the “temperature” for chain $j$.</li>
      <li>Typically, $T_j = 1 + \delta(j-1)$ with $\delta &gt; 0$.
        <ul>
          <li>The first chain ($j=1, T_1=1$) is the <strong>cold chain</strong> and samples from the true posterior $\pi(\theta)$. This is the chain used for inference.</li>
          <li>Other chains ($j&gt;1, T_j &gt; 1$) are <strong>hot chains</strong>. Higher $T_j$ means a flatter surface, allowing these chains to cross valleys between peaks more easily.</li>
        </ul>
      </li>
      <li><strong>Within-chain moves:</strong> Each chain $j$ performs standard MH updates using its target $\pi_j(\theta)$. Acceptance for a symmetric move from $\theta$ to $\theta’$ in chain $j$:
$\alpha = \min \left(1, \left[\frac{\pi(\theta’)}{\pi(\theta)}\right]^{1/T_j}\right)$ (Eq 7.58)</li>
      <li><strong>Chain Swaps:</strong> Periodically, attempt to swap the current states $(\theta_i, \theta_j)$ between two randomly chosen chains $i$ and $j$. The acceptance probability for swapping states:
$\alpha_{swap} = \min \left(1, \frac{\pi_i(\theta_j)}{\pi_i(\theta_i)} \times \frac{\pi_j(\theta_i)}{\pi_j(\theta_j)}\right) = \min \left(1, \left[\frac{\pi(\theta_j)}{\pi(\theta_i)}\right]^{1/T_i - 1/T_j}\right)$ (Eq 7.59)
Swapping allows the cold chain to occasionally receive a state from a hot chain that might have explored a different peak.</li>
      <li><strong>Optimal Temperature Spacing:</strong> Atchadé et al. (2011) suggest spacing temperatures so that ~23.4% of chain swaps are accepted.</li>
      <li><strong>Drawback:</strong> Only the cold chain’s output is used for inference, making it computationally more expensive as $m-1$ chains are run primarily to improve mixing of the cold chain.</li>
      <li>Widely used in phylogenetics (e.g., MrBayes).</li>
      <li>Fig 7.16 shows how a standard MCMC gets stuck in one of three peaks, while MC³ aims to allow transitions between them.</li>
    </ul>
  </li>
</ul>

<h3 id="742-trans-model-and-trans-dimensional-mcmc">7.4.2 Trans-model and Trans-dimensional MCMC</h3>
<p>Used when comparing different models or models with different numbers of parameters.</p>

<h4 id="7421-general-framework">7.4.2.1 General Framework</h4>
<ul>
  <li><strong>Goal:</strong> Sample from the joint posterior of model indicator $H_k$ and its parameters $\theta_k$:
$f(H_k, \theta_k \vert  X) = \frac{1}{Z} \pi_k f(\theta_k\vert H_k) f(X\vert H_k, \theta_k)$ (Eq 7.60)
where $Z$ is the normalizing constant (sum of marginal likelihoods over all models, Eq 7.61), $\pi_k$ is prior on model $H_k$.
Can be written as: $f(H_k, \theta_k \vert  X) = f(H_k\vert X) f(\theta_k\vert H_k, X)$ (Eq 7.62) (Posterior model prob $\times$ within-model parameter posterior).</li>
</ul>

<h4 id="7422-trans-model-mcmc-models-with-same-number-of-parameters">7.4.2.2 Trans-model MCMC (Models with Same Number of Parameters)</h4>
<ul>
  <li>If different models $H_1, H_2, …$ have parameters that can be matched up (e.g., $\mu_1 \leftrightarrow \mu_2$, $\sigma_1 \leftrightarrow \sigma_2$).</li>
  <li>The MCMC state is $(k, \theta_k)$. Moves can be within-model (update $\theta_k$ given $H_k$) or between-model (jump from $H_k$ to $H_{k’}$).</li>
  <li><strong>Example (Normal vs. Gamma model for 5 data points, Table 7.3, 7.4):</strong>
    <ul>
      <li>$H_1$: Normal $N(\mu, \sigma^2)$, parameters $\theta_1 = (\mu, \sigma)$.</li>
      <li>$H_2$: Gamma $G(\alpha, \beta)$, parameters $\theta_2 = (\alpha, \beta)$.</li>
      <li><strong>Algorithm 1 (Simple Matching):</strong> $\mu \leftrightarrow \alpha$, $\sigma \leftrightarrow \beta$.
        <ol>
          <li>Initial model and parameters.</li>
          <li>Within-model move (e.g., update $\mu, \sigma$ if current model is $H_1$).</li>
          <li>Trans-model move (with some probability):
If in $H_1$ (current params $\mu, \sigma$), propose $H_2$ with params $\alpha’=\mu, \beta’=\sigma$.
If in $H_2$ (current params $\alpha, \beta$), propose $H_1$ with params $\mu’=\alpha, \sigma’=\beta$.
Acceptance ratio $\alpha_{1 \leftrightarrow 2} = \min \left(1, \frac{f(H_{new}, \theta_{new}\vert X)}{f(H_{old}, \theta_{old}\vert X)}\right)$. (Eq 7.71)
Proposal ratio is 1 as no new random variables are generated for the parameters.</li>
        </ol>
      </li>
      <li><strong>Algorithm 2 (Moment Matching):</strong> Match means and variances.
To move $H_1 \to H_2$: set $\alpha’ = (\mu/\sigma)^2$, $\beta’ = \mu/\sigma^2$ (so gamma mean is $\mu$, variance is $\sigma^2$).
To move $H_2 \to H_1$: set $\mu’ = \alpha/\beta$, $\sigma’ = \sqrt{\alpha}/\beta$.
The acceptance ratio now includes a <strong>Jacobian determinant</strong> for the parameter transformation (Eq 7.73, 7.74, 7.75).</li>
      <li><strong>Algorithm 3 (Random Proposal):</strong> To move $H_1 \to H_2$, propose new $\alpha’, \beta’$ from distributions centered on current $\mu, \sigma$ (e.g., $\text{new mean } u_1 \sim G(10, 10/\mu)$, $\text{new SD } u_2 \sim G(10, 10/\sigma)$, then set $\alpha’=(u_1/u_2)^2, \beta’=u_1/u_2^2$).
The acceptance ratio includes ratio of proposal densities $g(v_1,v_2)/g(u_1,u_2)$ and the Jacobian (Eq 7.79, 7.80, 7.81).</li>
      <li><strong>Performance:</strong> Moment matching (Alg 2) had highest acceptance (70.3%) and efficiency. Simple matching (Alg 1) was very poor (1.1% acceptance).</li>
    </ul>
  </li>
</ul>

<h4 id="7423-trans-dimensional-mcmc-rjmcmc-green-1995">7.4.2.3 Trans-dimensional MCMC (rjMCMC) (Green 1995)</h4>
<ul>
  <li>For comparing models with <em>different numbers</em> of parameters (different dimensions).</li>
  <li>E.g., $H_1$ with parameter $\theta_1$ (dimension $d_1$) vs. $H_2$ with $\theta_2$ (dimension $d_2$, where $d_1 &lt; d_2$).</li>
  <li><strong>Dimension Matching:</strong> To move $H_1 \to H_2$, generate $d_2-d_1$ random auxiliary variables $u \sim g(u)$. Transform $(\theta_1, u) \to \theta_2$ using a deterministic, invertible function $T$. So, $\theta_2 = T(\theta_1, u)$.</li>
  <li>To move $H_2 \to H_1$, use inverse transform $(\theta_1, u) = T^{-1}(\theta_2)$. Drop $u$.</li>
  <li><strong>Acceptance Ratio (e.g., $H_1 \to H_2$):</strong>
$R_{12} = \frac{f(H_2)f(\theta_2\vert H_2)f(X\vert H_2, \theta_2)}{f(H_1)f(\theta_1\vert H_1)f(X\vert H_1, \theta_1)} \times \frac{r_{21}}{r_{12}} \times \frac{1}{g(u)} \times \left\vert  \frac{\partial \theta_2}{\partial(\theta_1, u)} \right\vert $ (Eq 7.83)
where $r_{12}, r_{21}$ are probabilities of attempting the jump between models, and the last term is the Jacobian.</li>
  <li><strong>Example (JC69 vs K80 for 2 sequences):</strong>
    <ul>
      <li>$H_1$ (JC69): param $\theta_1 = (d)$. $H_2$ (K80): params $\theta_2 = (d, \kappa)$. $d_1=1, d_2=2$.</li>
      <li>Auxiliary variable $u = \kappa$. To move $H_1 \to H_2$: keep $d$ same, generate $\kappa \sim g(\kappa)$ (e.g., from its prior).</li>
      <li>To move $H_2 \to H_1$: keep $d$ same, drop $\kappa$.</li>
      <li>Table 7.5 shows different rjMCMC proposals. Algorithm 1 (generating $\kappa$ from prior) most efficient.</li>
    </ul>
  </li>
  <li><strong>Mixing Problems of rjMCMC:</strong>
    <ul>
      <li>Often severe, especially if data is informative (within-model posteriors are concentrated).</li>
      <li>Proposals for new model parameters are often poor, leading to high rejection rates.</li>
      <li>No direct analogue to step-size tuning of within-model MCMC.</li>
      <li>Product-space method (Carlin &amp; Chib 1995) is an alternative but may be difficult for high-dimensional phylogenetic problems.</li>
    </ul>
  </li>
</ul>

<h4 id="7425-model-averaging">7.4.2.5 Model Averaging</h4>
<ul>
  <li>If interested in a quantity $\theta$ present in all models, its posterior can be estimated by averaging over models, weighted by posterior model probabilities $f(H_k\vert X)$:
$f(\theta\vert X) = \sum_{k=1}^K f(H_k\vert X) f(\theta\vert H_k, X)$ (Eq 7.89)</li>
  <li>Can be done by sampling $\theta$ from the rjMCMC output irrespective of current model.</li>
  <li><strong>Usefulness:</strong>
    <ul>
      <li>Appealing for accounting for model uncertainty.</li>
      <li>If one model strongly dominates ($f(H_k\vert X) \approx 1$), model averaging gives similar result to using best model.</li>
      <li>If several models fit nearly equally well <em>but give different inferences for $\theta$</em>, model averaging is most useful (posterior for $\theta$ might become multimodal).</li>
      <li>If all models fit poorly, model averaging is unlikely to help.</li>
    </ul>
  </li>
</ul>

<h3 id="743-bayes-factor-and-marginal-likelihood">7.4.3 Bayes Factor and Marginal Likelihood</h3>
<ul>
  <li><strong>Bayes Factor ($B_{01}$):</strong> Ratio of posterior odds to prior odds for two models $H_0, H_1$. Equals ratio of marginal likelihoods.
$B_{01} = \frac{M_0}{M_1} = \frac{f(X\vert H_0)}{f(X\vert H_1)} = \frac{\int f(X\vert \theta_0, H_0)f(\theta_0\vert H_0)d\theta_0}{\int f(X\vert \theta_1, H_1)f(\theta_1\vert H_1)d\theta_1}$ (Eq 7.91)</li>
  <li>$\text{Posterior Odds} = \text{Prior Odds} \times B_{01}$ (Eq 7.92)</li>
  <li>If prior odds are 1 ($f(H_0)=f(H_1)=1/2$), then $f(H_0\vert X) = B_{01} / (1+B_{01}) = 1/(1+1/B_{01})$ (Eq 7.93)</li>
  <li>Interpretation of $B_{01}$ (Table 7.6).</li>
  <li><strong>Differences from LRT:</strong>
    <ol>
      <li>Bayes factor averages over parameters (via prior), LRT optimizes. Priors have strong influence.</li>
      <li>Numerical results differ. Bayes factor (model selection) is often more conservative than LRT (hypothesis testing), less likely to reject $H_0$ for large datasets.</li>
      <li>Bayes factors easily compare non-nested models or &gt;2 models.</li>
    </ol>
  </li>
  <li>Requires proper priors (marginal likelihood infinite for improper priors if likelihood doesn’t go to zero fast enough).</li>
  <li><strong>Methods for Calculating Marginal Likelihood ($z=f(X)$):</strong>
    <ol>
      <li><strong>Arithmetic Mean (Prior):</strong> $z \approx \frac{1}{n} \sum f(X\vert \theta_i)$, where $\theta_i \sim f(\theta)$. Inefficient as prior $f(\theta)$ usually far from posterior. (Eq 7.94, 7.95)</li>
      <li><strong>Harmonic Mean (Posterior):</strong> $z \approx n / (\sum [1/f(X\vert \theta_i)])$, where $\theta_i \sim f(\theta\vert X)$. Unstable, infinite variance, positive bias. Generally unusable. (Eq 7.96)</li>
      <li><strong>Thermodynamic Integration (Path Sampling):</strong> (Lartillot &amp; Philippe 2006)
        <ul>
          <li>Define power posterior $p_\beta(\theta) \propto [f(X\vert \theta)]^\beta f(\theta)$. ($z_\beta$ is its normalizing constant).</li>
          <li>$\log z_1 - \log z_0 = \log f(X) = \int_0^1 E_\beta[\log f(X\vert \theta)] d\beta$ (Eq 7.99-7.101)</li>
          <li>Run MCMC for several $\beta$ values between 0 (prior) and 1 (posterior). Estimate $E_\beta[\log f(X\vert \theta)]$ from each. Numerically integrate.</li>
        </ul>
      </li>
      <li><strong>Stepping Stone Sampling (Xie et al. 2011):</strong>
        <ul>
          <li>$z_1/z_0 = \prod_{k=1}^K (z_{\beta_k}/z_{\beta_{k-1}})$, where $0=\beta_0 &lt; \beta_1 &lt; \dots &lt; \beta_K=1$.</li>
          <li>Each ratio $r_k = z_{\beta_k}/z_{\beta_{k-1}}$ estimated by importance sampling using samples from $p_{\beta_{k-1}}(\theta)$:
$\hat{r}<em>k = \frac{1}{n} \sum</em>{i=1}^n [f(X\vert \theta_i)]^{\beta_k - \beta_{k-1}}$ (Eq 7.104)</li>
          <li>Requires $K-1$ MCMC runs (if prior can be sampled directly).</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h1 id="8-bayesian-phylogenetics">8. Bayesian phylogenetics</h1>

<p>This chapter provides an overview of Bayesian inference as applied to phylogenetic reconstruction, including historical background, MCMC algorithms, model and prior choices, and issues related to interpreting posterior probabilities.</p>

<h2 id="81-overview">8.1 Overview</h2>

<h3 id="811-historical-background">8.1.1 Historical Background</h3>
<ul>
  <li><strong>Early Efforts (1960s):</strong> Edwards and Cavalli-Sforza attempted to apply Fisher’s likelihood method to infer human population trees using gene frequency data.
    <ul>
      <li>They used the Yule process (pure birth process) for tree probabilities (prior on labeled histories) and Brownian motion for gene frequency drift.</li>
      <li>This work led to the development of distance (additive-tree) and parsimony (minimum-evolution) methods as approximations to ML.</li>
      <li>Edwards (1970) clarified that the tree (or labeled history) should be estimated from its conditional distribution given the data (i.e., the posterior), marking an early application of Bayesian ideas to phylogenetics.</li>
    </ul>
  </li>
  <li><strong>Introduction to Molecular Phylogenetics (1990s):</strong> Three groups independently introduced Bayesian inference for sequence data:
    <ul>
      <li>Rannala and Yang (1996; Yang and Rannala 1997)</li>
      <li>Mau and Newton (1997)</li>
      <li>Li et al. (2000)</li>
      <li>Early studies often assumed a molecular clock and uniform priors on rooted trees (either labeled histories or simple rooted trees).</li>
    </ul>
  </li>
  <li><strong>Development of MCMC Software:</strong>
    <ul>
      <li><strong>BAMBE (Larget and Simon 1999)</strong> and <strong>MrBayes (Huelsenbeck and Ronquist 2001)</strong> implemented more efficient MCMC algorithms.</li>
      <li>The clock constraint was relaxed, allowing for more realistic evolutionary models.</li>
      <li>Tree perturbation algorithms (NNI, SPR, TBR) were adapted as MCMC proposals.</li>
      <li>Later versions of MrBayes (Ronquist et al. 2003, 2012b) incorporated many ML models and can handle heterogeneous multi-gene datasets.</li>
    </ul>
  </li>
  <li><strong>Modern Bayesian Programs:</strong>
    <ul>
      <li><strong>BEAST (Drummond et al. 2006; Drummond and Rambaut 2007):</strong> Focuses on estimating rooted trees under clock and relaxed-clock models, particularly for divergence time estimation.</li>
      <li><strong>PhyloBayes (Lartillot et al. 2007, 2009; Lartillot and Philippe 2008):</strong> Implements sophisticated models for substitution heterogeneity (e.g., CAT model) important for deep phylogenies.</li>
      <li>These are now standard tools alongside fast ML programs like RAxML and PhyML.</li>
    </ul>
  </li>
</ul>

<h3 id="812-a-sketch-mcmc-algorithm">8.1.2 A Sketch MCMC Algorithm</h3>
<ul>
  <li><strong>General Framework:</strong>
    <ul>
      <li>Data: Sequence alignment $X$.</li>
      <li>Tree Topology: $\tau_i$, $i=1, \dots, T_s$. Prior $f(\tau_i)$ (often uniform $1/T_s$).</li>
      <li>Branch Lengths: Vector $t_i$ for tree $\tau_i$. Prior $f(t_i \vert \tau_i)$ (often simplified to $f(t_i)$).</li>
      <li>Substitution Model Parameters: $\theta$. Prior $f(\theta)$.</li>
    </ul>
  </li>
  <li><strong>Joint Posterior Distribution:</strong>
$f(\tau_i, t_i, \theta \vert X) \propto f(\theta) f(\tau_i) f(t_i \vert \tau_i) f(X \vert \theta, \tau_i, t_i)$ (Eq 8.1)
The normalizing constant $f(X)$ (marginal likelihood of data) is usually intractable. MCMC avoids its direct calculation.</li>
  <li><strong>Sketch of an MCMC Algorithm:</strong>
    <ol>
      <li><strong>Initialization:</strong> Start with a random tree $\tau$, random branch lengths $t$, and random substitution parameters $\theta$.</li>
      <li><strong>Iteration:</strong> Repeat the following steps:
a.  Propose a change to the tree topology $\tau \to \tau’$ (using NNI, SPR, TBR). This may also change branch lengths $t \to t’$.
b.  Propose changes to branch lengths $t \to t’$.
c.  Propose changes to substitution parameters $\theta \to \theta’$.
d.  Every $k$ iterations (thinning), sample the current state $(\tau, t, \theta)$ and save it to disk.</li>
      <li><strong>Summarization:</strong> After a sufficient number of iterations (post burn-in), summarize the collected samples.</li>
    </ol>
  </li>
</ul>

<h3 id="813-the-statistical-nature-of-phylogeny-estimation">8.1.3 The Statistical Nature of Phylogeny Estimation</h3>
<ul>
  <li><strong>Tree as a Model:</strong> A phylogenetic tree is a statistical model, not just a parameter. Phylogeny reconstruction is therefore a <strong>model selection</strong> problem.</li>
  <li><strong>Importance of Distinction:</strong>
    <ol>
      <li><strong>Asymptotic Efficiency of MLEs:</strong> Applies to parameter estimation <em>within</em> a fixed model (e.g., branch lengths on a given tree), not to ML tree topology selection (see §5.2.3).</li>
      <li><strong>MCMC Design:</strong> Proposals changing tree topology are <strong>cross-model moves</strong> and should be designed/optimized differently from <strong>within-model moves</strong> (parameter changes on a fixed tree).</li>
    </ol>
  </li>
  <li><strong>Phylogeny vs. Typical Model Selection/Hypothesis Testing:</strong>
    <ul>
      <li>Phylogenetics involves a vast number of tree models with complex relationships.</li>
      <li>The likelihood model is a combination of the tree (topology) and the process model (substitution model).</li>
    </ul>
  </li>
  <li><strong>MCMC Moves:</strong>
    <ul>
      <li><strong>Within-tree move (within-model):</strong> Modifies branch lengths or substitution parameters without changing topology. Goal: Traverse parameter space efficiently. Optimal $P_{jump}$ (acceptance proportion) around 30-40%.</li>
      <li><strong>Cross-tree move (cross-model):</strong> Changes tree topology. Goal: Efficiently move between models (trees). Higher $P_{jump}$ is generally better. Branch lengths in the new tree should be proposed to maximize acceptance, not necessarily to explore parameter space.</li>
      <li>Many current proposals mix these, making step-length tuning awkward. The overall acceptance rate is often not a good indicator of efficiency; acceptance rate of topology changes is more relevant.</li>
    </ul>
  </li>
</ul>

<h2 id="82-models-and-priors-in-bayesian-phylogenetics">8.2 Models and Priors in Bayesian Phylogenetics</h2>

<p>To implement a model in a Bayesian framework: (i) assign priors to parameters, (ii) design MCMC proposals.</p>

<h3 id="821-priors-on-branch-lengths">8.2.1 Priors on Branch Lengths</h3>
<ul>
  <li>A binary unrooted tree for $s$ species has $2s-3$ branches. Vector of branch lengths $t = {t_1, \dots, t_{2s-3}}$.</li>
  <li><strong>Common i.i.d. Priors (e.g., in MrBayes):</strong>
    <ul>
      <li><strong>Uniform:</strong> $t_i \sim U(0, A)$. User specifies $A$. Default $A=100$ in MrBayes.</li>
      <li><strong>Exponential:</strong> $t_i \sim \text{Exp}(\beta)$ with density $f(t_i \vert \beta) = \beta e^{-\beta t_i}$, $t_i &gt; 0$. Mean $1/\beta$. Default $\beta=10$ (mean 0.1) in MrBayes. (Eq 8.2)</li>
    </ul>
  </li>
  <li><strong>Problem with i.i.d. Priors:</strong> Collectively, they can make strong and unreasonable statements about the <strong>tree length</strong> $T = \sum t_i$.
    <ul>
      <li>If $t_i \sim \text{Exp}(\beta)$ i.i.d., then $T \sim \text{Gamma}(2s-3, \beta)$. Density: $f(T \vert \beta, s) = \frac{\beta^{2s-3}}{\Gamma(2s-4)} T^{2s-4}e^{-\beta T}$. (Eq 8.3)
        <ul>
          <li>For large $s$, this Gamma distribution is approximately normal with mean $(2s-3)/\beta$ and variance $(2s-3)/\beta^2$.</li>
          <li>Example: $s=100, \beta=10 \implies$ prior mean $T=19.7$, 99% prior CI for $T$ is $(16.3, 22.9)$. If data suggests $T&lt;1$, this prior is extremely informative and will bias results towards long trees.</li>
        </ul>
      </li>
      <li>If $t_i \sim U(0,A)$ i.i.d., then $T \approx N((2s-3)A/2, (2s-3)A^2/12)$. This implies very long trees if $A$ is large (e.g., $A=100$).</li>
      <li>These i.i.d. priors can lead to posterior tree lengths being orders of magnitude too large, especially in analyses of closely related sequences.</li>
    </ul>
  </li>
  <li><strong>Improved Priors (Compound Dirichlet Priors, Rannala et al. 2012):</strong>
    <ol>
      <li>Assign a prior on the total tree length $T$.
        <ul>
          <li><strong>Gamma prior on T:</strong> $f(T; \alpha_T, \beta_T) = \frac{\beta_T^{\alpha_T}}{\Gamma(\alpha_T)} e^{-\beta_T T} T^{\alpha_T-1}$. (Eq 8.4)
(Typically $\alpha_T=1$ for a diffuse prior on $T$).</li>
        </ul>
      </li>
      <li>Partition $T$ into individual branch lengths $t_i$ using a symmetric Dirichlet distribution for proportions $x_i = t_i/T$.
$f(x; \alpha_1, \dots, \alpha_K) = \frac{\Gamma(\alpha_0)}{\prod \Gamma(\alpha_i)} \prod x_i^{\alpha_i-1}$, where $\alpha_0 = \sum \alpha_i$. (Eq 8.5)
If symmetric, all $\alpha_i=1$, then $f(x) = (K-1)!$ where $K=2s-3$.</li>
      <li>The joint prior on $t$ is (using $T=\sum t_i$ and $x_i=t_i/T$):
$f(t \vert \alpha_T, \beta_T) = \frac{\beta_T^{\alpha_T}}{\Gamma(\alpha_T)} e^{-\beta_T \sum t_i} (\sum t_i)^{\alpha_T-1-(2s-4)} (2s-4)!$ (Eq 8.8, given $T = \sum t_i$ and Jacobian $\vert  \frac{\partial(T,x)}{\partial(t)} \vert  = T^{-(2s-4)}$).
        <ul>
          <li><strong>Inverse Gamma prior on T:</strong> $T \sim \text{invGamma}(\alpha_T, \beta_T)$, density $f(T; \alpha_T, \beta_T) = \frac{\beta_T^{\alpha_T}}{\Gamma(\alpha_T)} e^{-\beta_T/T} T^{-\alpha_T-1}$. (Eq 8.9)
Heavy-tailed. With symmetric Dirichlet, joint prior on $t$:
$f(t \vert \alpha_T, \beta_T) = \frac{\beta_T^{\alpha_T}}{\Gamma(\alpha_T)} e^{-\beta_T/\sum t_i} (\sum t_i)^{-\alpha_T-1-(2s-4)} (2s-4)!$ (Eq 8.10)</li>
          <li>These compound priors are more robust to misspecification of prior mean tree length (Fig 8.2, Table 8.1). Tree topology inference is less affected by branch length priors than branch length estimation itself.</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h3 id="822-priors-on-parameters-in-substitution-models">8.2.2 Priors on Parameters in Substitution Models</h3>
<ul>
  <li><strong>8.2.2.1 Nucleotide Substitution Models:</strong>
    <ul>
      <li><strong>Rate Ratios (e.g., $\kappa$ in K80/HKY85, $a-f$ in GTR):</strong>
        <ul>
          <li>$\kappa$: Gamma prior, e.g., $G(2,1)$ (mean 2). Or transform $y=\kappa/(1+\kappa) \sim \text{Beta}(a,b)$. Density for $\kappa$: $f(\kappa) = \frac{1}{B(a,b)} \kappa^{a-1}(1+\kappa)^{-a-b}$. (Eq 8.12)</li>
        </ul>
      </li>
      <li><strong>Base Frequencies ($\pi_T, \pi_C, \pi_A, \pi_G$):</strong>
        <ul>
          <li>Dirichlet prior, e.g., $\text{Dir}(1,1,1,1)$ (uniform).</li>
          <li>Often fixed at observed frequencies if reliably estimated.</li>
        </ul>
      </li>
      <li><strong>GTR Relative Rates ($r_{TC}, r_{TA}, \dots, r_{AG}$):</strong>
        <ul>
          <li>Assign Dirichlet prior on relative rates summing to 1. E.g., $\text{Dir}(1,1,1,1,1,1)$.</li>
          <li>Alternatively, fix one rate (e.g., $r_{AG}=1$) and assign Gamma priors to others. Uniform priors on rate ratios (e.g., $U(0,100)$) are ill-advised.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>8.2.2.2 Amino Acid and Codon Models:</strong>
    <ul>
      <li><strong>Empirical AA Models (e.g., JTT, WAG):</strong> No free parameters typically, unless using +F to estimate AA frequencies (Dirichlet prior).</li>
      <li><strong>GY94-type Codon Models:</strong>
        <ul>
          <li>Codon frequencies: Dirichlet prior or fixed.</li>
          <li>$\kappa$: Gamma prior.</li>
          <li>$\omega = d_N/d_S$: Gamma prior, e.g., $G(2,4)$ (mean 0.5), or $\omega/(1+\omega) \sim \text{Beta}$.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>8.2.2.3 Models of Variable Substitution Rates Among Sites:</strong>
    <ul>
      <li><strong>Gamma Model (+$\Gamma$):</strong> Shape parameter $\alpha$.
        <ul>
          <li>Gamma prior, e.g., $G(2,4)$ (mean 0.5). Exponential prior also reasonable.</li>
          <li>Uniform prior (e.g., $U(0,200)$ in MrBayes) is poor as likelihood is flat for large $\alpha$.</li>
        </ul>
      </li>
      <li><strong>Invariant Sites Model (+I):</strong> Proportion of invariable sites $p_0$.
        <ul>
          <li>Uniform prior $p_0 \sim U(0,1)$ is common.</li>
        </ul>
      </li>
      <li><strong>I+$\Gamma$ Model:</strong> Pathological, strong correlation between $p_0$ and $\alpha$. Ideally, prior should account for this.</li>
      <li><strong>Finite-Mixture Models (Discrete Rates):</strong> $K$ rate classes. Probabilities $(p_1, \dots, p_K) \sim \text{Dir}(1,\dots,1)$. Relative rates $(r_1, \dots, r_K) \sim \text{Dir}(1,\dots,1)$, then rescaled.</li>
    </ul>
  </li>
  <li><strong>8.2.2.4 Dirichlet Process Models of Among-Site Heterogeneity:</strong>
    <ul>
      <li>Nonparametric prior on partitions of sites into $K$ classes, where $K$ itself is estimated.</li>
      <li><strong>Chinese Restaurant Process Analogy:</strong> Defines probability of assigning $n$ sites into $K$ clusters.
        <ul>
          <li>$f(K, \mathbf{z} \vert \alpha, n) = \frac{\alpha^K \prod_{i=1}^K (n_i-1)!}{\prod_{i=1}^n (\alpha+i-1)}$, where $n_i$ is size of cluster $i$. (Eq 8.16)</li>
        </ul>
      </li>
      <li>Expected number of clusters $E(K\vert \alpha,n) \approx \alpha \log(1+n/\alpha)$. (Eq 8.18)</li>
      <li>Concentration parameter $\alpha$ controls tendency to form new clusters.</li>
      <li>Used to model variable rates (Huelsenbeck &amp; Suchard 2007) or variable patterns (e.g., CAT model).</li>
      <li>Can lead to very many site classes if prior favors them.</li>
    </ul>
  </li>
  <li><strong>8.2.2.5 Nonhomogeneous Models (Compositional Heterogeneity):</strong>
    <ul>
      <li>Allow base frequencies to drift across the tree.</li>
      <li><strong>Foster (2004):</strong> Fixed number of base frequency sets, assignment to branches varied in MCMC.</li>
      <li><strong>Blanquart &amp; Lartillot (2006 “Breakpoint Model”):</strong> Compound Poisson process for breakpoints on branches. At breakpoint, new base frequencies drawn from prior. rjMCMC needed for number of breakpoints.</li>
      <li><strong>CAT-BP (Blanquart &amp; Lartillot 2008):</strong> Combines CAT site mixture model with breakpoint model for nonstationarity.</li>
    </ul>
  </li>
  <li><strong>8.2.2.6 Partition and Mixture Models for Large Genomic Datasets:</strong>
    <ul>
      <li>Partition data (e.g., by gene, by codon position).</li>
      <li>Allow different overall rates $r_k$ for partitions.
        <ul>
          <li>Priors on $r_k$: Dirichlet for relative rates, or i.i.d. $r_i \sim G(\alpha,\alpha)$ (mean 1).</li>
        </ul>
      </li>
      <li>Can also have different substitution model parameters (e.g., $\kappa_k, \pi_k$) per partition.</li>
      <li>Within each partition, can further use a mixture model (e.g., +$\Gamma$) for remaining rate heterogeneity.</li>
    </ul>
  </li>
</ul>

<h3 id="823-priors-on-tree-topology">8.2.3 Priors on Tree Topology</h3>
<ul>
  <li><strong>8.2.3.1 Prior on Rooted Trees:</strong>
    <ul>
      <li>Often generated by a stochastic model of cladogenesis (speciation/extinction).</li>
      <li><strong>Yule Process (Pure Birth):</strong> Generates labeled histories with equal probability.</li>
      <li><strong>Birth-Death-Sampling Process (Yang &amp; Rannala 1997):</strong> Parameters $\lambda$ (birth), $\mu$ (death), $\rho$ (sampling fraction). Also generates labeled histories with equal probability. Used for divergence time estimation.</li>
    </ul>
  </li>
  <li><strong>8.2.3.2 Prior on Unrooted Trees:</strong>
    <ul>
      <li><strong>Uniform Prior:</strong> Common. $P(\tau_i) = 1/U_s$, where $U_s$ is total number of unrooted trees for $s$ species.</li>
      <li><strong>Problem (Pickett &amp; Randle 2005; Steel &amp; Pickett 2006):</strong> Uniform prior on trees induces a <em>non-uniform</em> prior on splits/clades. Smallest (2 taxa) and largest ($s-2$ taxa) splits are combinatorially more frequent among all possible trees than intermediate-sized splits.</li>
      <li>This can lead to spuriously high posterior probabilities for incorrect small/large splits, especially if data is uninformative about a “rogue” taxon (Fig 8.3).</li>
    </ul>
  </li>
</ul>

<h2 id="83-mcmc-proposals-in-bayesian-phylogenetics">8.3 MCMC Proposals in Bayesian Phylogenetics</h2>

<p>This section details the MCMC proposal mechanisms used for updating parameters within a fixed tree topology (within-tree moves) and for changing the tree topology itself (cross-tree moves).</p>

<h3 id="831-within-tree-moves">8.3.1 Within-Tree Moves</h3>

<p>These proposals modify parameters like branch lengths or substitution model parameters without altering the tree topology. Standard Metropolis-Hastings (MH) algorithms are used.</p>

<h4 id="8311-updating-branch-lengths-t_i">8.3.1.1 Updating Branch Lengths ($t_i$)</h4>
<ul>
  <li><strong>Individual Branch Length Updates:</strong>
    <ul>
      <li>Update one branch length at a time using a sliding window (uniform, normal, or Bactrian proposal) or a multiplier (proportional scaling, see §7.2.1-5).</li>
      <li>Updating all in a fixed order can be computationally advantageous (saves re-calculating parts of the likelihood).</li>
      <li>Step length/multiplier size adjusted during burn-in for good mixing ($P_{jump} \approx 30-40\%$).</li>
      <li>Multiplier proposal (log-scale sliding window) is often more suitable as longer branches tend to have larger variances and can take larger steps proportionally.</li>
    </ul>
  </li>
  <li><strong>Scaling the Whole Tree:</strong>
    <ul>
      <li>Apply a single multiplier $c$ to <em>all</em> branch lengths simultaneously ($t_i’ = c \cdot t_i$). Proposal ratio is $c^{N_b}$ where $N_b$ is the number of branches (§7.2.5).</li>
      <li>Useful for bringing all branch lengths into the correct scale, or for dealing with correlation between overall tree length and parameters like $\alpha$ (gamma shape).</li>
    </ul>
  </li>
  <li><strong>Scaling a Subtree:</strong>
    <ul>
      <li>Select an internal node $x$ (and its mother $a$). Propose a new age $t_x’$ for node $x$ (reflected into range $(0, t_a)$).</li>
      <li>Scale all node ages within the clade defined by $x$ proportionally: $t_j’ = t_j \times (t_x’/t_x)$. (Fig 8.4)</li>
      <li>The proposal ratio for this scaling part is $(t_x’/t_x)^m$, where $m$ is the number of internal nodes within the clade $x$.</li>
    </ul>
  </li>
  <li><strong>Branch Length Constraints:</strong>
    <ul>
      <li>Branch lengths $t_i \ge 0$.</li>
      <li>Problems near zero:
        <ol>
          <li>$P(\text{data})$ can become 0 or negative due to rounding errors if tree distance between two different sequences is close to zero.</li>
          <li>If $t_i=0$, multiplier moves will keep it at 0.</li>
        </ol>
      </li>
      <li><strong>Solution:</strong> Apply minimum bounds (e.g., $t_i &gt; 10^{-6}$ for external, $t_i &gt; 10^{-8}$ for internal). Reflect proposals into the bounded range. Truncation effect on prior usually negligible.</li>
    </ul>
  </li>
</ul>

<h4 id="8312-updating-substitution-parameters">8.3.1.2 Updating Substitution Parameters</h4>
<ul>
  <li>Standard MH proposals for parameters like $\kappa$ (Ts/Tv ratio) or $\alpha$ (gamma shape).</li>
  <li><strong>Nucleotide Frequencies $\pi = (\pi_T, \pi_C, \pi_A, \pi_G)$:</strong> Sum to 1.
    <ul>
      <li>Sample new frequencies $\pi’$ from a Dirichlet distribution centered on current $\pi$: $\pi’ \sim \text{Dir}(\alpha_0\pi_T, \alpha_0\pi_C, \alpha_0\pi_A, \alpha_0\pi_G)$. $\alpha_0$ is a concentration parameter (step length).</li>
      <li>Proposal ratio: $q(\pi\vert \pi’)/q(\pi’\vert \pi) = \frac{\prod \Gamma(\alpha_0\pi_i’) \cdot (\pi_i)^{\alpha_0\pi_i’-1}}{\prod \Gamma(\alpha_0\pi_i) \cdot (\pi_i’)^{\alpha_0\pi_i-1}}$. (Eq 8.19)</li>
      <li>Simpler: Pick two frequencies (e.g., $\pi_i, \pi_j$), keep sum $s=\pi_i+\pi_j$ fixed. Propose $\pi_i’$ from $U(0,s)$ (reflected), set $\pi_j’ = s-\pi_i’$. Proposal ratio is 1. (1D move).</li>
    </ul>
  </li>
  <li>Amino acid/codon frequencies updated similarly.</li>
</ul>

<h3 id="832-cross-tree-moves">8.3.2 Cross-Tree Moves</h3>
<p>Proposals that change the tree topology $\tau$. These are more complex as they are moves between different statistical models.</p>

<h4 id="8321-proposals-and-proposal-ratios-general">8.3.2.1 Proposals and Proposal Ratios (General)</h4>
<ul>
  <li>A move from state $x=(\tau, t)$ to $x’=(\tau’, t’)$ can be broken into component steps. If $x \to y \to z \to x’$, then the proposal ratio is a product of ratios for component steps:
$\frac{q(x\vert x’)}{q(x’\vert x)} = \frac{q(x\vert y)}{q(y\vert x)} \times \frac{q(y\vert z)}{q(z\vert y)} \times \frac{q(z\vert x’)}{q(x’\vert z)}$ (Eq 8.20)</li>
  <li><strong>Typical Two-Step Cross-Tree Move for NNI:</strong>
    <ol>
      <li>$(\tau, t) \to (\tau’, t)$: Change topology (e.g., NNI). Symmetrical, component proposal ratio is 1.</li>
      <li>$(\tau’, t) \to (\tau’, t’)$: Modify branch lengths for the new topology $\tau’$.</li>
    </ol>
  </li>
  <li><strong>Acceptance Rate (from §7.4.2.2, Eq 7.63 for trans-model MCMC):</strong>
$\alpha = \frac{f(\tau’, t’\vert X)}{f(\tau, t\vert X)} \times \frac{r_{\tau’\tau}}{r_{\tau\tau’}} \times \frac{q((\tau,t)\vert (\tau’,t’))}{q((\tau’,t’)\vert (\tau,t))}$ (Eq 8.21)
where $f(\cdot\vert X)$ is posterior, $r_{\tau\tau’}$ is probability of proposing topology $\tau’$ given current $\tau$, and the last term is the branch length proposal ratio.</li>
  <li><strong>Key Questions for Designing Cross-Tree Moves:</strong>
i.  <strong>Computational Effort:</strong> How to divide between cross-tree and within-tree moves? (More mobile chain is better, so frequent cross-tree moves are desired. New branch lengths are automatically from posterior for the new tree if accepted, no need for many within-tree moves in the new tree immediately after a jump).
ii. <strong>Tree Perturbation Algorithm:</strong> NNI (local), SPR/TBR (global). Choice depends on tree space landscape.
iii. <strong>Generating Branch Lengths for New Tree $\tau’$:</strong> Crucial for acceptance. Aim to propose “good” branch lengths.</li>
</ul>

<h4 id="8322-criteria-for-evaluating-cross-tree-moves">8.3.2.2 Criteria for Evaluating Cross-Tree Moves</h4>
<ul>
  <li>Evaluate MCMC mixing efficiency across trees using posterior probabilities of splits.</li>
  <li>Define a distance from “true” split probabilities (from a very long reference run) to estimates from test chain: $\delta_n = \max_i \vert \hat{p}_i - p_i\vert $ (Eq 8.22). Average $\delta_n$ over replicate runs.</li>
</ul>

<h4 id="8323-empirical-observations-on-branch-lengths-in-different-trees">8.3.2.3 Empirical Observations on Branch Lengths in Different Trees</h4>
<ul>
  <li><strong>Example (5 ape species mtDNA, Fig 8.5):</strong>
    <ul>
      <li>MLEs of branch lengths for 15 unrooted trees under JC69.</li>
      <li>Good trees (high likelihood) have similar ML tree lengths and MP tree lengths.</li>
      <li>External branch lengths are quite similar across trees.</li>
      <li>Internal branch lengths are very similar for trees that share that internal branch (e.g., the (HC)G split, if present, has similar length).</li>
      <li>If a split is not supported by data (tree containing it has low likelihood), its branch length tends to be short, while branches within the incorrect subtrees might become long.</li>
    </ul>
  </li>
  <li>These observations can guide how branch lengths are proposed for new topologies.</li>
</ul>

<h3 id="833-nni-for-unrooted-trees">8.3.3 NNI for Unrooted Trees</h3>
<ul>
  <li><strong>Basic NNI (Fig 8.6):</strong>
    <ol>
      <li>Select an internal branch (focal branch $u-v$) at random. This defines 4 subtrees $a,b,c,d$. Current tree is e.g., $((a,b),c,d)$.</li>
      <li>Choose one of the two alternative NNI neighbors (e.g., $((a,c),b,d)$) at random.</li>
      <li><strong>Branch Length Transfer:</strong> Simplest: transfer branch lengths from old tree to new tree without alteration (e.g., length of $u-v$ becomes length of new internal branch).
        <ul>
          <li>Proposal ratio for this basic NNI is 1 (both topology choice and branch length transfer are symmetric).</li>
        </ul>
      </li>
    </ol>
  </li>
  <li><strong>Random Modification (Multiplier):</strong> Can apply a multiplier $c = e^{\lambda(u-1/2)}$ to the internal branch length $t_0$. Proposal ratio becomes $c$. (But this might reduce acceptance).</li>
  <li><strong>LOCAL Move (Larget and Simon 1999):</strong> (Fig 8.6a)
    <ol>
      <li>Pick focal internal branch $u-v$. Choose one branch from each end (e.g., $b-u, v-c$) to form a 3-branch backbone $b-u-v-c$.</li>
      <li>Multiply these 3 lengths ($t_b, t_0, t_c$) by a common multiplier $c$. This step contributes $c^3$ to proposal ratio.</li>
      <li>Select one end of $u-v$ (e.g., $u$). Move $u$ and its other attached subtree ($a$) to a random location along the $b-u-v-c$ backbone. This step is symmetrical (proposal ratio 1).
        <ul>
          <li>Overall proposal ratio $c^3$. (Holder et al. 2005 corrected original $c^2$).</li>
          <li>Mixture of within-tree and cross-tree moves. Random modification of 3 branches might be detrimental to cross-tree acceptance.</li>
        </ul>
      </li>
    </ol>
  </li>
  <li><strong>Lakner et al. NNI Variant:</strong>
    <ul>
      <li>Choose one of 3 topologies around focal branch with probability $1/3$.</li>
      <li>Modify all 5 branches around focal point with independent multipliers. (Proposal ratio is product of multipliers). This extensive random modification is likely poor for acceptance.</li>
    </ul>
  </li>
  <li><strong>Selection of Target Tree:</strong> Random choice of NNI neighbor might not be optimal.
    <ul>
      <li>Can use weights (e.g., based on parsimony scores $s_\tau, s_{\tau’}$) to propose target trees: $r_{\tau\tau’} = w_{\tau\tau’} / \sum_j w_{\tau j}$, where $w_{\tau\tau’} = e^{-\beta(s_{\tau’}-s_\tau)}$. (Eq 8.24)</li>
    </ul>
  </li>
</ul>

<h3 id="834-spr-for-unrooted-trees">8.3.4 SPR for Unrooted Trees</h3>
<ul>
  <li><strong>Algorithm (Fig 8.7a,b):</strong>
    <ol>
      <li>Choose a focal branch $a$ (connecting subtrees $A$ and $B$). Prune $A$ (with $a$).</li>
      <li>Choose a random regrafting branch $r$ in the remaining tree $B$.</li>
      <li>Break $r$ into $x’$ and $r’$ by $u \sim U(0,1)$ ($x’=ru, r’=r(1-u)$). Reattach $A$ via branch $a$.</li>
    </ol>
  </li>
  <li><strong>Proposal Ratio (branch lengths):</strong> Original branches $p,x,r$ become $p’ = p+x$, $a$ (reattached), $x’$, $r’$. (Mapping Fig 8.7b).
    <ul>
      <li>Mapping: $(p,x,r,u) \leftrightarrow (p’,x’,r’,u’)$. $u’ = x’/(x’+p’)$.</li>
      <li>Jacobian $\vert  \frac{\partial(p’,x’,r’,u’)}{\partial(p,x,r,u)} \vert  = r/(x+p)$. (Eq 8.26)</li>
      <li>Proposal ratio (if $u \sim U(0,1)$ and reverse $u’$ is calculated): $r/(x+p)$.</li>
    </ul>
  </li>
  <li><strong>Lakner et al. SPR Variants (rSPR, eSPR):</strong>
    <ul>
      <li>Select internal branches as focal.</li>
      <li><strong>rSPR:</strong> Random pruning and regrafting.</li>
      <li><strong>eSPR (Extending SPR):</strong> Scheme to give different probabilities to neighbors (favors local moves).</li>
      <li><strong>Branch Length Transfer (Fig 8.7c):</strong> Move branch $x$ (on backbone) along with $A$. $p,a,r$ lengths preserved. $b_1, b_2, \dots$ on backbone are split/merged. If only $x$ is between $a$ and $r$, it’s NNI-like. Proposal ratio 1 for this transfer.</li>
      <li>If SPR is not NNI, transferring $x$ might be too disruptive. Fig 8.7b strategy (breaking/merging) might be better.</li>
      <li>Lakner et al. also apply random multipliers to $a$ and $x$, likely reducing acceptance.</li>
    </ul>
  </li>
</ul>

<h3 id="835-tbr-for-unrooted-trees">8.3.5 TBR for Unrooted Trees</h3>
<ul>
  <li><strong>Algorithm (Fig 8.8):</strong>
    <ol>
      <li>Cut an internal bisection branch $a$, splitting tree into $X, Y$.</li>
      <li>Choose reconnecting branch $x$ in $X$ and $y$ in $Y$.</li>
      <li>Generate $r_1, r_2 \sim U(0,1)$. Break $x$ into $x’, t’$ ($x’=xr_1, t’=x(1-r_1)$). Break $y$ into $y’, v’$ ($y’=yr_2, v’=y(1-r_2)$).</li>
      <li>Reconnect by joining new node to $x’$ and $y’$, with new internal branch $a’$ (length of old $a$).</li>
    </ol>
  </li>
  <li><strong>Branch Length Mapping (Fig 8.8a-c):</strong> Old $s,t$ merge to $s’$. Old $u,v$ merge to $u’$.
\(x \to x', t'\\
y \to y', v'\\
s, t \to s' = s+t\\
u, v \to u' = u+v\\
a \to a'\\\)</li>
  <li><strong>Proposal Ratio (branch lengths):</strong>
Jacobi determinant of $(x,t,s,y,v,u,r_1,r_2) \leftrightarrow (x’,t’,s’,y’,v’,u’,r_1’,r_2’)$ is $xy/[(s+t)(u+v)]$. (Eq 8.28)
This is the proposal ratio if $r_1, r_2 \sim U(0,1)$.</li>
  <li>TBR affects many branches but preserves relationships within $X$ and $Y$.</li>
</ul>

<h3 id="836-subtree-swapping-sts">8.3.6 Subtree Swapping (STS)</h3>
<ul>
  <li><strong>Algorithm (Fig 8.9):</strong>
    <ol>
      <li>Pick two (non-adjacent) branches $x, y$ with their subtrees $X, Y$.</li>
      <li>Swap them. Branch lengths $x,y$ are transferred without alteration.</li>
    </ol>
  </li>
  <li><strong>Proposal Ratio:</strong> 1.</li>
  <li>NNI is a special case.</li>
  <li><strong>eSTS (Lakner et al.):</strong> Extension mechanism favoring local swaps. Applies multipliers to backbone branches, may reduce acceptance.</li>
</ul>

<h3 id="837-nni-for-rooted-trees">8.3.7 NNI for Rooted Trees</h3>
<ul>
  <li>Parameters are node ages $t_u, t_v, \dots$. Constraint: $t_{child} &lt; t_{parent}$.</li>
  <li><strong>NNI Move (Fig 8.10):</strong>
    <ul>
      <li>Internal branch $u-v$ defines 3 subtrees $a,b$ (daughters of $v$) and $c$ (sibling of $v$). Current tree $\tau_1 = ((a,b)v, c)u$.</li>
      <li>Alternatives: $\tau_2 = ((c,a)v, b)u$, $\tau_3 = ((b,c)v, a)u$.</li>
    </ul>
  </li>
  <li><strong>Drummond et al. (2002) “Narrow Exchange”:</strong>
    <ul>
      <li>Choose one of $\tau_2, \tau_3$ at random. Swap if node age constraints are met (e.g., for $\tau_2$, need $t_c &lt; t_v$).</li>
      <li>Node ages are <em>not changed</em>. Proposal ratio is 1.</li>
    </ul>
  </li>
  <li><strong>Kuhner et al. (1995), Larget &amp; Simon (1999 “LOCAL with clock”):</strong>
    <ul>
      <li>Modify ages $t_u, t_v$. Other ages fixed.</li>
      <li>$t_u’, t_v’$ generated (e.g., uniformly between $t_w$ and older of $t_a, t_b, t_c$).</li>
      <li>Mixture of within-tree and cross-tree.</li>
      <li>Better to keep $t_u$ (height of clade $(abc)$) unchanged for cross-tree moves.</li>
    </ul>
  </li>
</ul>

<h3 id="838-spr-on-rooted-trees">8.3.8 SPR on Rooted Trees</h3>
<ul>
  <li><strong>Algorithm (Fig 8.11, Wilson &amp; Balding 1998; Rannala &amp; Yang 2003):</strong>
    <ol>
      <li>Prune subtree $x$ (by cutting branch $a-x$, mother of $x$ is $a$).</li>
      <li>Select random reattachment node $y$ in remaining tree.</li>
      <li>Generate new age for node $a$, $t_a’$.
        <ul>
          <li>If $y$ is not root: $t_a’ \sim U(\max(t_x, t_y), t_b)$ where $b$ is mother of $y$.</li>
          <li>If $y$ is root: $t_a’ \sim \text{Exp}$ above $t_x$.</li>
        </ul>
      </li>
    </ol>
  </li>
  <li><strong>Proposal Ratio (Rannala &amp; Yang 2003):</strong> $n/m$, where $m$ is number of feasible reattachment branches in forward move (given $t_a’$), $n$ is for reverse move (given $t_a$).
    <ul>
      <li>If root changes, ratio involves ratio of uniform and exponential densities (Eq 8.29).</li>
    </ul>
  </li>
</ul>

<h3 id="839-node-slider">8.3.9 Node Slider</h3>
<ul>
  <li>Slides an internal node $x$ (mother $a$) along the tree. (Fig 8.12)
    <ol>
      <li>Choose non-root internal node $x$.</li>
      <li>Generate new age $t_a^*$ for its mother $a$ using sliding window. (Symmetric proposal, factor 1).</li>
      <li>Slide $a$ (with $x$) up/down according to $t_a^*$. Path chosen with equal probability at bifurcations. If tip is hit, reflect.</li>
      <li>Let final age of $a$ be $t_a’$. Scale all $m$ nodes inside subtree $x$ by factor $t_a’/t_a$.</li>
    </ol>
  </li>
  <li><strong>Proposal Ratio:</strong> $(t_a’/t_a)^m$.</li>
  <li>Mixture of local/global, within/cross-tree.</li>
</ul>

<h2 id="84-summarizing-mcmc-output">8.4 Summarizing MCMC Output</h2>
<ul>
  <li><strong>Point Estimate of Tree:</strong> Maximum A Posteriori (MAP) tree (topology with highest posterior probability). Should be similar to ML tree if data is informative.</li>
  <li><strong>Credibility Set of Trees:</strong> Smallest set of trees whose cumulative posterior probability exceeds threshold (e.g., 95%).</li>
  <li><strong>Posterior Split/Clade Probabilities:</strong> Proportion of sampled trees (post burn-in) that contain a specific split. Usually shown on a majority-rule consensus tree or MAP tree.</li>
  <li><strong>Concerns:</strong>
    <ul>
      <li>Consensus tree may not be any of the sampled trees.</li>
      <li>Uniform prior on trees induces non-uniform prior on splits (Pickett &amp; Randle 2005), potentially biasing split posteriors if data is weak.</li>
    </ul>
  </li>
  <li>Posterior means of branch lengths on consensus trees should be interpreted cautiously, better to fix topology if branch lengths are primary interest.</li>
</ul>

<h2 id="85-high-posterior-probabilities-for-trees">8.5 High Posterior Probabilities for Trees</h2>

<p>Bayesian posterior probabilities for trees/splits are often very high (e.g., close to 1.0), even when bootstrap support is lower or relationships are known to be difficult.</p>

<h3 id="851-high-posterior-probabilities-for-trees-or-splits">8.5.1 High Posterior Probabilities for Trees or Splits</h3>
<ul>
  <li><strong>Observation:</strong> Posterior probabilities (PPs) from MrBayes etc. are often much higher than bootstrap values.</li>
  <li><strong>Reasons for Spurious High PPs:</strong>
    <ol>
      <li><strong>Errors:</strong> Theory faults, program bugs, MCMC convergence/mixing problems (chain stuck in local peak). Generally less likely to be the fundamental reason for widespread observation.</li>
      <li><strong>Model Misspecification:</strong> Using overly simplistic/wrong models can inflate PPs. (Though high PPs seen even when true model is used in simulations).</li>
      <li><strong>Impact of Prior &amp; Asymptotic Behavior of Bayesian Model Selection:</strong> This is considered a major factor. Bayesian model selection is consistent (converges to true model as data size $n \to \infty$). If multiple models are “equally wrong” or equally close to true, Bayesian selection tends to pick one with posterior probability approaching 1, even if data doesn’t strongly differentiate them.</li>
    </ol>
  </li>
</ul>

<h3 id="852-star-tree-paradox">8.5.2 Star Tree Paradox</h3>
<ul>
  <li><strong>Scenario (Fig 8.13):</strong> Data simulated under a star tree (no resolution). Bayesian analysis of binary trees.</li>
  <li><strong>Intuition:</strong> PPs for the 3 binary trees should approach $1/3$.</li>
  <li><strong>Actual Behavior (Lewis et al. 2005; Yang &amp; Rannala 2005):</strong> One of the binary trees gets PP close to 1, others close to 0. The favored tree varies randomly among datasets. (Distribution Fig 8.14).</li>
  <li>This is an extreme example of Bayesian methods giving confident (but arbitrary) answers when data lacks information.</li>
</ul>

<h3 id="853-fair-coin-paradox-fair-balance-paradox-and-bayesian-model-selection">*8.5.3 Fair Coin Paradox, Fair Balance Paradox, and Bayesian Model Selection</h3>
<p>Examines simple cases to understand Bayesian model selection behavior with large data.</p>
<ul>
  <li><strong>8.5.3.1 Simple Models (No Free Parameters, Fig 8.15a):</strong>
    <ul>
      <li>Data from $N(0,1)$. Compare $H_1: \mu=\mu_1$ vs $H_2: \mu=\mu_2$.</li>
      <li>If $\mu_1, \mu_2$ are equally wrong (e.g., $\mu_1 = -0.1, \mu_2 = 0.1$), as $n \to \infty$, $P(H_1\vert X)$ converges to a 2-point distribution (0 or 1, each with prob 1/2). (Fig 8.16a).</li>
      <li>If $H_1$ is less wrong than $H_2$ (e.g., $\mu_1=-0.1, \mu_2=0.2$), $P(H_1\vert X) \to 1$. (Fig 8.16b).</li>
      <li>Bayesian selection becomes certain even if choosing between wrong models.</li>
    </ul>
  </li>
  <li><strong>8.5.3.2 Composite Models (With Free Parameters):</strong>
    <ul>
      <li><strong>Overlapping Models, Truth in Overlap (Fig 8.15b):</strong> e.g., $H_1: \theta \in [0, 0.6]$, $H_2: \theta \in [0.4, 1.0]$. True $\theta_0=0.5$. $P(H_1\vert X) \to 1/2$. Desirable behavior.</li>
      <li><strong>Models Bordering at Truth (Fig 8.15c, Star Tree Paradox is an instance):</strong> e.g., $H_1: \mu&lt;0$, $H_2: \mu&gt;0$. True $\mu_0=0$. Data from $N(0,1)$, prior $\mu \sim N(0, \sigma_p^2)$ truncated. $P(H_1\vert X)$ converges to $U(0,1)$ distribution. (Fig 8.17).</li>
      <li><strong>Models Crossing at Truth (Fig 8.15d):</strong> e.g., Data $N(0,1)$. $H_1: X \sim N(\mu,1)$ (unknown $\mu$). $H_2: X \sim N(0, 1/\beta)$ (unknown precision $\beta$). $P(H_1\vert X)$ converges to a U-shaped distribution (peaks at 0 and 1). (Fig 8.18).</li>
    </ul>
  </li>
</ul>

<h3 id="854-conservative-bayesian-phylogenetics">8.5.4 Conservative Bayesian Phylogenetics</h3>
<p>Attempts to alleviate overly confident PPs.</p>
<ul>
  <li><strong>Yang &amp; Rannala (2005):</strong> Exponential priors on internal ($\mu_0$) and external ($\mu_1$) branch lengths. Suggested small $\mu_0$ for internal branches (data size dependent, e.g., $\mu_0 = 0.1n^{-2/3}$).</li>
  <li><strong>Polytomy Prior (Lewis et al. 2005):</strong> Assign non-zero prior probability to multifurcating (star-like) trees. This resolves star tree paradox (posterior will favor star tree if data supports it). Computationally more complex (rjMCMC).</li>
  <li><strong>Example (Apes, Fig 8.19):</strong> Using different priors on internal branch lengths (default i.i.d. Exp(0.1); Exp with mean $0.1n^{-2/3}$; gamma-Dirichlet) for the 7 ape mtDNA dataset. All priors give PPs of 1.0 for all splits in the MAP tree (which is the ML tree). This suggests for this very informative dataset, the prior on branch length has little impact on split PPs, although it can affect branch length estimates.</li>
</ul>

<h1 id="chapter-9-coalescent-theory-and-species-trees">Chapter 9: Coalescent Theory and Species Trees</h1>

<p>This chapter reviews computational methods for analyzing genetic and genomic sequence data under the coalescent model, applicable to samples from a single species or multiple closely related species. The focus is on likelihood-based inference methods.</p>

<h2 id="91-overview">9.1 Overview</h2>
<ul>
  <li><strong>Coalescent Model:</strong> Framework for analyzing sequence data from one or more populations/species.
    <ul>
      <li><strong>Single Population Coalescent (§9.2):</strong> Basic model.</li>
      <li><strong>Multispecies Coalescent (§9.3 onwards):</strong> Extends to multiple closely related species, providing a framework for:
        <ul>
          <li>Estimating species trees despite conflicting gene trees.</li>
          <li>Bayesian species delimitation.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Interface of Population Genetics and Phylogenetics:</strong> Statistical analysis of sequence data from closely related species (statistical phylogeography) draws from both fields. Bayesian MCMC algorithms share similarities (sampling in tree space, calculating likelihoods).</li>
  <li><strong>Scope:</strong> Focus on sequence data. Recombination and selection are not covered. Other data types (RFLPs, microsatellites, SNPs) are ignored.</li>
  <li><strong>Trends in Theoretical Population Genetics:</strong>
    <ol>
      <li>Shift from probabilistic predictions of model behavior to <strong>statistical inference</strong> (parameter estimation, hypothesis testing) driven by the availability of genomic data.</li>
      <li>The <strong>coalescent approach</strong> has become central to statistical methods for comparative data analysis.</li>
    </ol>
  </li>
</ul>

<h2 id="92-the-coalescent-model-for-a-single-species">9.2 The Coalescent Model for a Single Species</h2>

<h3 id="921-the-backward-time-machine">9.2.1 The Backward Time Machine</h3>
<ul>
  <li><strong>Coalescence:</strong> The merging or joining of ancestral lineages when tracing genealogy backwards in time.</li>
  <li><strong>Kingman’s Coalescent (1980s):</strong> A genealogical process modeling the joining of lineages backwards in time.</li>
  <li><strong>Contrast with Classical (Forward) Population Genetics:</strong>
    <ul>
      <li><strong>Forward:</strong> Models allele frequency changes over generations under mutation, drift, selection, etc.</li>
      <li><strong>Backward (Coalescent):</strong> Focuses on the genealogy of a <em>sample</em> of genes, tracing lineages back to their Most Recent Common Ancestor (MRCA). Ignores individuals not ancestral to the sample.</li>
    </ul>
  </li>
  <li><strong>Advantages of Coalescent:</strong>
    <ul>
      <li>Modeling genealogy backward is often easier under neutral models with random mating.</li>
      <li>Allows separation of genealogical process (tree structure, coalescent times) from mutational process (mutations dropped onto the tree).</li>
    </ul>
  </li>
  <li><strong>Focus of Study:</strong> In molecular phylogenetics, the species phylogeny is often the primary interest. In coalescent analyses, the genealogy is usually a means to infer population parameters or demographic history.</li>
</ul>

<h3 id="922-fisher-wright-model-and-the-neutral-coalescent">9.2.2 Fisher-Wright Model and the Neutral Coalescent</h3>
<ul>
  <li><strong>Fisher-Wright Model (Idealized):</strong> (Fig 9.1a)
    <ul>
      <li>Constant diploid population size $N$ (so $2N$ gene copies).</li>
      <li>Non-overlapping generations.</li>
      <li>Random mating (panmixia).</li>
      <li>Neutral evolution (no selection).</li>
      <li>No recombination within a locus, free recombination between loci.</li>
    </ul>
  </li>
  <li><strong>Effective Population Size ($N_e$):</strong> The size of an idealized Fisher-Wright population that would experience the same amount of genetic drift as the real population. $N_e$ is often smaller than census size $N$ due to factors like biased sex ratio, changing population size (bottlenecks reduce $N_e$ via harmonic mean). Hereafter, $N$ usually means $N_e$.</li>
  <li><strong>Coalescence of Two Genes:</strong>
    <ul>
      <li>In a diploid population of size $N$, the probability that two gene lineages pick the same parent in the previous generation (coalesce) is $1/(2N)$.</li>
      <li>Probability they do <em>not</em> coalesce in the previous generation is $1 - 1/(2N)$.</li>
      <li>Probability they do not coalesce in the first $i$ generations: $P(T’_2 &gt; i) = (1 - 1/(2N))^i$. (Eq 9.1)</li>
      <li>Probability they coalesce exactly $i$ generations ago: $P(T’_2 = i) = (1 - 1/(2N))^{i-1} \times (1/(2N))$. (Eq 9.2)</li>
      <li>$T’_2$ (time to coalescence in generations) follows a geometric distribution with mean $2N$.</li>
    </ul>
  </li>
  <li><strong>Rescaled Time ($T_2$):</strong> Time measured in units of $2N$ generations. $T_2 = T’_2 / (2N)$.
    <ul>
      <li>For large $N$, $P(T_2 &gt; t) = P(T’_2 &gt; 2Nt) = (1 - 1/(2N))^{2Nt} \approx e^{-t}$. (Eq 9.3)</li>
      <li>$T_2$ follows an exponential distribution with mean 1 and density $f(T_2) = e^{-T_2}$. (Eq 9.4)</li>
    </ul>
  </li>
  <li><strong>Mutation Time Scale ($t_2$):</strong> Time measured in expected number of mutations per site. $t_2 = T’_2 \mu = T_2 \cdot (2N\mu) = T_2 \cdot (\theta/2)$, where $\mu$ is mutation rate per site per generation.
    <ul>
      <li><strong>Population Size Parameter $\theta = 4N\mu$.</strong> This is a measure of genetic diversity.</li>
      <li>$t_2$ follows an exponential distribution with mean $\theta/2$ and density $f(t_2) = (2/\theta) e^{-(2/\theta)t_2}$. (Eq 9.5)</li>
      <li>Coalescent events occur at rate $2/\theta$ when time is measured in mutations.</li>
      <li>For humans, $\theta \approx 0.0006$ (0.6 per kb). Given generation time $g \approx 20$ yrs and $\mu/g \approx 1.2 \times 10^{-9}$ mutations/site/year, $N_e \approx 6250$.</li>
    </ul>
  </li>
</ul>

<h3 id="923-a-sample-of-n-genes">9.2.3 A Sample of $n$ Genes</h3>
<ul>
  <li>Consider $n$ gene lineages. Probability that no pair coalesces in the previous generation:
$\approx 1 - \binom{n}{2} \frac{1}{2N}$ (Eq 9.6)
(Each of $\binom{n}{2}$ pairs has $1/(2N)$ chance to coalesce; assumes $n \ll N$).</li>
  <li>$T’_n$: Waiting time (generations) until the <em>next</em> coalescent event when there are $n$ lineages.
    <ul>
      <li>$P(T’_n = i) = \left(1 - \binom{n}{2}\frac{1}{2N}\right)^{i-1} \times \binom{n}{2}\frac{1}{2N}$. (Eq 9.7)</li>
      <li>Geometric distribution with mean $2N / \binom{n}{2}$.</li>
    </ul>
  </li>
  <li>Rescaled time $T_j = T’_j / (2N)$: Waiting time (in $2N$ units) when there are $j$ lineages.
    <ul>
      <li>$T_j \sim \text{Exp}(\text{rate} = \binom{j}{2})$ with mean $2/(j(j-1))$. (Eq 9.8)</li>
    </ul>
  </li>
  <li><strong>Genealogy:</strong> A random bifurcating tree. The $n-1$ coalescent times $T_n, T_{n-1}, \dots, T_2$ are independent exponential variables.</li>
  <li>The genealogical tree is a <strong>labeled history</strong> (ranking of nodes by age matters, §3.1.1.5). Number of labeled histories $H_n = n!(n-1)!/2^{n-1}$. (Eq 9.9) Each has probability $1/H_n$.</li>
  <li>Joint density of coalescent times for a given labeled history $G$:
$f(T_n, T_{n-1}, \dots, T_2 \vert G) = \prod_{j=2}^n \left[ \binom{j}{2} \exp\left(-\binom{j}{2}T_j\right) \right]$. (Eq 9.10)</li>
  <li>Joint density of tree $G$ and times: $f(G, T_n, \dots, T_2) = \prod_{j=2}^n \exp\left(-\binom{j}{2}T_j\right)$. (Eq 9.11)</li>
  <li><strong>Time to MRCA ($T_{MRCA}$):</strong> $T_{MRCA} = T_n + T_{n-1} + \dots + T_2$. (Eq 9.12)
    <ul>
      <li>$E(T_{MRCA}) = \sum_{j=2}^n \frac{2}{j(j-1)} = 2(1 - 1/n)$. (Eq 9.13)</li>
      <li>$V(T_{MRCA}) = \sum_{j=2}^n \left(\frac{2}{j(j-1)}\right)^2$.</li>
      <li>For large $n$, $E(T_{MRCA}) \approx 2$ (in $2N$ units). Variation mostly from $T_2$.</li>
    </ul>
  </li>
  <li><strong>Total Tree Length ($T_{total}$):</strong> Sum of all branch lengths = $\sum_{j=2}^n j T_j$. (Fig 9.2)
    <ul>
      <li>$E(T_{total}) = \sum_{j=2}^n j \frac{2}{j(j-1)} = 2 \sum_{j=1}^{n-1} \frac{1}{j}$. (Eq 9.14)</li>
      <li>Grows slowly with $n$ (approx $2(\gamma + \log n)$, $\gamma \approx 0.577$ Euler’s constant).</li>
    </ul>
  </li>
  <li>Probability that MRCA of sample is MRCA of whole population: $(n-1)/(n+1)$.</li>
  <li>Coalescent trees are very variable, short tips, long near-root branches (Fig 9.3). Increasing sample size $n$ is ineffective for inferring ancient events or $\theta$.</li>
</ul>

<h3 id="924-simulating-the-coalescent">9.2.4 Simulating the Coalescent</h3>
<ul>
  <li><strong>Forward Simulation:</strong> Tracks all $2N$ gene copies. Computationally intensive.</li>
  <li><strong>Coalescent (Backward) Simulation:</strong> Tracks only ancestors of the sample. Much more efficient.
    <ol>
      <li><strong>Algorithm 9.1 (Mutations and Coalescences as Competing Poisson Events):</strong>
        <ul>
          <li>Start with $k=n$ lineages.</li>
          <li>Waiting time to next event (coalescence or mutation) is $\text{Exp}(\text{rate}_c + \text{rate}_m)$, where $\text{rate}_c = \binom{k}{2}$ (coalescence rate in $2N$ units) and $\text{rate}_m = kl(\theta/2)$ (total mutation rate for $k$ lineages, $l$ sites).</li>
          <li>If event is coalescence (prob $\text{rate}_c / (\text{rate}_c + \text{rate}_m)$), pick two lineages to merge, $k \to k-1$.</li>
          <li>If mutation (prob $\text{rate}_m / (\text{rate}_c + \text{rate}_m)$), pick a lineage and site to mutate.</li>
          <li>Repeat until $k=1$.</li>
        </ul>
      </li>
      <li><strong>Algorithm 9.2 (Genealogy First, then Mutations):</strong> Preferred.
        <ul>
          <li>
            <ol>
              <li>Set $k=n$.</li>
            </ol>
          </li>
          <li>
            <ol>
              <li>Loop until $k=1$:
                <ul>
                  <li>Generate waiting time $T_k \sim \text{Exp}(\binom{k}{2})$.</li>
                  <li>Choose a random pair from $k$ lineages to join. $k \to k-1$.</li>
                </ul>
              </li>
            </ol>
          </li>
          <li>
            <ol>
              <li>Generate root sequence. Evolve along branches (length $T_k \times \theta/2$ in mutations) to get tip sequences.</li>
            </ol>
          </li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h3 id="925-estimation-of-theta-from-a-sample-of-dna-sequences">9.2.5 Estimation of $\theta$ from a Sample of DNA Sequences</h3>
<ul>
  <li><strong>9.2.5.1 Estimation under the Infinite-Site Model:</strong> Assumes every new mutation occurs at a new site.
    <ul>
      <li><strong>One Locus, Two Sequences ($n=2$):</strong>
        <ul>
          <li>Number of differences $x$ (given $T_2$) $\sim \text{Poisson}(T_2 \cdot l\theta)$. Averaging over $T_2 \sim \text{Exp}(1)$:
$P(x) = \frac{(l\theta)^x}{(1+l\theta)^{x+1}}$ (Geometric distribution with mean $l\theta$). (Eq 9.16)</li>
        </ul>
      </li>
      <li><strong>One Locus, Many Sequences ($n&gt;2$):</strong>
        <ul>
          <li>$S_n$: number of segregating (variable) sites. Given $T_{total}$, $S_n \sim \text{Poisson}(T_{total} \cdot l\theta/2)$.</li>
          <li>$E(S_n) = l\theta \sum_{j=1}^{n-1} (1/j)$.</li>
          <li><strong>Watterson’s Estimator $\hat{\theta}<em>S = S_n / (l \sum</em>{j=1}^{n-1} (1/j))$.</strong> (Eq 9.18)</li>
          <li><strong>Tajima’s Estimator $\hat{\theta}_\pi = \pi/l$,</strong> where $\pi$ is average pairwise differences.</li>
        </ul>
      </li>
      <li><strong>Many Loci ($L$), Two Sequences:</strong>
        <ul>
          <li>Log-likelihood: $l(\theta) = \sum_{i=1}^L \left[ x_i \log \frac{l_i\theta}{1+l_i\theta} - \log(1+l_i\theta) \right]$. (Eq 9.19) MLE $\hat{\theta}$ found numerically.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>9.2.5.2 Estimation under a Finite-Site Model (e.g., JC69):</strong> Allows multiple hits.
    <ul>
      <li><strong>Two Sequences:</strong> Coalescent time $t \sim \text{Exp}(2/\theta)$ (in mutations per site). (Eq 9.20)
        <ul>
          <li>Given $t$, probability of $x_i$ differences at locus $i$ with $l_i$ sites (using JC69, $p(t) = \frac{3}{4}(1-e^{-8t/3})$ is prob. of difference per site):
$f(x_i\vert t) = \binom{l_i}{x_i} [p(t)]^{x_i} [1-p(t)]^{l_i-x_i}$.</li>
          <li>Likelihood for locus $i$: $f(x_i\vert \theta) = \int_0^\infty f(t\vert \theta) f(x_i\vert t) dt$. (Eq 9.22)</li>
          <li>Total log-likelihood: $l(\theta) = \sum_{i=1}^L \log f(x_i\vert \theta)$. (Eq 9.23)</li>
        </ul>
      </li>
      <li><strong>Many Sequences ($n_i&gt;2$ at locus $i$):</strong>
        <ul>
          <li>Joint density of gene tree $G_i$ and coalescent times $t_i$ (in mutations): $f(G_i, t_i\vert \theta)$ (Eq 9.24, scaling Eq 9.11 by $\theta/2$).</li>
          <li>Log-likelihood: $l(\theta) = \sum_{i=1}^L \log \left[ \sum_{G_i} \int_{t_i} f(G_i, t_i\vert \theta) f(X_i\vert G_i, t_i) dt_i \right]$. (Eq 9.25)
$f(X_i\vert G_i, t_i)$ is the standard phylogenetic likelihood.</li>
          <li>Summation/integration is intractable for ML.</li>
        </ul>
      </li>
      <li><strong>Bayesian MCMC (Algorithm 9.3, Rannala &amp; Yang 2003):</strong>
        <ul>
          <li>Joint posterior: $f(\theta, G, t\vert X) \propto f(\theta) \prod_{i=1}^L [f(G_i, t_i\vert \theta) f(X_i\vert G_i, t_i)]$. (Eq 9.26)</li>
          <li>MCMC steps:
            <ol>
              <li>Propose changes to coalescent times $t_i$ in each gene tree.</li>
              <li>Propose changes to genealogy $G_i$ (e.g., SPR).</li>
              <li>Propose change to $\theta$.</li>
              <li>Propose change to all coalescent times using a multiplier.</li>
            </ol>
          </li>
        </ul>
      </li>
      <li><strong>Example 9.1 (Human $\theta$ from 3 loci, Fig 9.4):</strong> Posterior mean $\hat{\theta} \approx 0.00053$.</li>
    </ul>
  </li>
</ul>

<h2 id="93-population-demographic-process">9.3 Population Demographic Process</h2>

<p>Using multi-locus data to infer demographic history (population size changes).</p>

<h3 id="931-homogeneous-and-nonhomogeneous-poisson-processes">9.3.1 Homogeneous and Nonhomogeneous Poisson Processes</h3>
<ul>
  <li><strong>Homogeneous Poisson Process:</strong> Events occur at constant rate $\lambda$.
    <ul>
      <li>Number of events in $(0,T)$ is $\text{Poisson}(\lambda T)$. Density $p_k = e^{-\lambda T}(\lambda T)^k/k!$. (Eq 9.27)</li>
      <li>Waiting times between events are $\text{Exp}(\lambda)$.</li>
    </ul>
  </li>
  <li><strong>Nonhomogeneous Poisson Process:</strong> Event rate $\lambda(t)$ varies with time.
    <ul>
      <li>Number of events in $(0,T)$ is $\text{Poisson}(\bar{\lambda}T)$, where $\bar{\lambda} = \frac{1}{T}\int_0^T \lambda(t)dt$. (Eq 9.28, 9.29)</li>
      <li>Joint PDF for $k$ events at times $y_1, \dots, y_k$ in $(0,T)$:
$\left[ \prod_{i=1}^k \lambda(y_i) \right] \times \exp\left(-\int_0^T \lambda(s)ds\right)$. (Eq 9.31)</li>
    </ul>
  </li>
</ul>

<h3 id="932-deterministic-population-size-change">9.3.2 Deterministic Population Size Change</h3>
<ul>
  <li>Coalescent is a variable-rate Poisson process. If $j$ lineages exist at time $t$ (ago), coalescent rate (in mutations/site) is $\lambda(t) = \binom{j}{2} \frac{2}{\theta(t)}$. (Eq 9.32)</li>
  <li>Joint density of gene tree $G$ and coalescent times $(t_n, \dots, t_2)$:
$f(G, t_n, \dots, t_2) = \left( \prod_{j=2}^n \frac{2}{\theta(t_j)} \right) \times \exp \left( -\sum_{j=2}^n \int_{t_{j+1}}^{t_j} \binom{j}{2} \frac{2}{\theta(s)} ds \right)$. (Eq 9.33)
(Product of rates at coalescent events $\times$ prob. of no other events).</li>
  <li><strong>Exponential Growth Model:</strong> $\theta(t) = \theta_0 e^{-rt}$. (Population grows forward, so size parameter decreases backward). Integral is tractable. (Eq 9.34)</li>
</ul>

<h3 id="933-nonparametric-population-demographic-models">9.3.3 Nonparametric Population Demographic Models</h3>
<p>Avoid strong assumptions of specific functional forms for $\theta(t)$.</p>
<ul>
  <li><strong>Piecewise Constant (Change-Point) Model (Fig 9.5a):</strong> $\theta(t)$ is constant within segments defined by $K$ change points $s_1, \dots, s_K$. Parameters: $s_k$’s and $\theta_k$’s. (Drummond et al. 2005, Bayesian skyline plot).</li>
  <li><strong>Piecewise Linear Model (Fig 9.5b):</strong> $\theta(t)$ is linear between change points. Integral $\int 1/\theta(s)ds = \int 1/(as+b)ds = \frac{1}{a}\log\vert \frac{at_1+b}{at_0+b}\vert $. (Eq 9.35) (Opgen-Rhein et al. 2005; Heled &amp; Drummond 2008).</li>
  <li><strong>Implementations:</strong>
    <ul>
      <li>Bayesian Skyline Plot (BEAST): Piecewise constant, works for one locus. Extended to multiple loci.</li>
      <li>Bayesian Skyride (Minin et al. 2008): Uses Gaussian random field prior for $\log \theta(t)$.</li>
      <li>Number of change points $K$ can be fixed or estimated (rjMCMC). Concern: assumption that population size changes coincide with coalescent events in some implementations.</li>
    </ul>
  </li>
</ul>

<h2 id="94-multispecies-coalescent-species-trees-and-gene-trees">9.4 Multispecies Coalescent, Species Trees and Gene Trees</h2>

<p>This section introduces the multispecies coalescent model, which describes the genealogical relationships of sequences sampled from several related species, accounting for the species phylogeny.</p>

<h3 id="941-multispecies-coalescent">9.4.1 Multispecies Coalescent</h3>
<ul>
  <li><strong>Concept:</strong> Models how gene lineages coalesce within the branches (populations) of a known species tree. (Fig 9.6)</li>
  <li><strong>Parameters ($C$):</strong>
    <ul>
      <li>Species divergence times ($\tau_S$).</li>
      <li>Effective population sizes ($\theta_S = 4N_S\mu$) for each ancestral and extant species $S$ on the species tree.</li>
      <li>Both $\tau_S$ and $\theta_S$ are typically measured in expected number of mutations per site.</li>
    </ul>
  </li>
  <li><strong>Assumptions:</strong>
    <ul>
      <li>Known species tree topology.</li>
      <li>Complete isolation after species divergence (no migration/hybridization/introgression).</li>
      <li>No recombination within a locus; free recombination between loci (gene trees are independent conditional on $C$).</li>
    </ul>
  </li>
  <li><strong>Process:</strong> Gene lineages trace backwards in time within each species (population branch) according to the standard single-species coalescent. Lineages from different species can only coalesce once they reach a common ancestral species.</li>
  <li><strong>Probability Density of a Gene Tree ($f(G_i, t_i \vert C)$):</strong>
    <ul>
      <li>$G_i$: Gene tree topology (labeled history) for locus $i$.</li>
      <li>$t_i$: Vector of coalescent times on gene tree $G_i$.</li>
      <li>Calculated by considering the independent coalescent processes within each population segment of the species tree.</li>
      <li>For a segment of the species tree (population $P$) of duration $\Delta\tau_P$ (in mutations/site) and population size parameter $\theta_P$:
        <ul>
          <li>If $m$ lineages enter population $P$ and $n$ lineages leave ($n \le m$):
The contribution to the gene tree density from this segment is:
$\left[ \prod_{j=n+1}^{m} \frac{2}{\theta_P} \right] \times \exp \left( -\sum_{j=n+1}^{m} \binom{j}{2}\frac{2}{\theta_P} t_j \right) \times \exp \left( -\binom{n}{2}\frac{2}{\theta_P} \left(\Delta\tau_P - \sum_{k=n+1}^{m} t_k\right) \right)$ (Eq 9.38, adapted)
This formula has:
            <ol>
              <li>Product of coalescent rates ($2/\theta_P$) for each of the $m-n$ coalescent events within this population.</li>
              <li>Probability of waiting times $t_j$ for these coalescences.</li>
              <li>Probability that the remaining $n$ lineages <em>do not</em> coalesce during the remaining time in this population segment.</li>
            </ol>
          </li>
        </ul>
      </li>
      <li>The full density $f(G_i, t_i \vert C)$ is a product of such terms over all populations in the species tree traversed by lineages ancestral to locus $i$. (Example in Eq 9.40, 9.41 for Fig 9.6b).</li>
    </ul>
  </li>
  <li><strong>Log Likelihood for Multi-Locus Data ($X = {X_i}$):</strong>
$l(C) = \sum_{i=1}^L \log \left[ \sum_{G_i} \int_{t_i} f(G_i, t_i \vert C) f(X_i \vert G_i, t_i) dt_i \right]$ (Eq 9.42)
where $f(X_i \vert G_i, t_i)$ is the standard phylogenetic likelihood of sequence alignment $X_i$ given gene tree $G_i$ and its branch lengths (coalescent times) $t_i$.</li>
  <li><strong>ML Estimation:</strong> Conceptually possible, but summation over gene tree topologies $G_i$ and integration over coalescent times $t_i$ is usually intractable.</li>
  <li><strong>Bayesian MCMC Estimation (e.g., BPP program by Rannala &amp; Yang 2003):</strong>
    <ul>
      <li>Joint posterior: $f(C, G, t \vert X) \propto f(C) \prod_{i=1}^L [f(G_i, t_i \vert C) f(X_i \vert G_i, t_i)]$ (Eq 9.43)</li>
      <li>MCMC samples from this posterior, integrating out $G_i$ and $t_i$.</li>
      <li><strong>Algorithm 9.4 (MCMC for estimating $\tau_s$ and $\theta_s$):</strong>
        <ol>
          <li>Update coalescent times (node ages) in each gene tree $G_i$.</li>
          <li>Propose changes to gene tree topologies $G_i$ (e.g., using SPR).</li>
          <li>Update population size parameters $\theta_s$.</li>
          <li>Update species divergence times $\tau_s$. This is complex as it constrains gene tree node ages (“rubber-band” algorithm to adjust gene tree times if a $\tau_s$ proposal violates $t_{coalescence} &lt; \tau_{speciation}$).</li>
          <li>Multiplier move for all coalescent times.</li>
        </ol>
      </li>
    </ul>
  </li>
  <li><strong>Example 9.2 (Hominoid genomic data, Fig 9.7, Table 9.1):</strong> Estimation of divergence times and ancestral population sizes for Human-Chimp-Gorilla-Orangutan using BPP. Ancestral populations ($N_e$ for HC, HCG, HCGO) were much larger than modern human $N_e$.</li>
</ul>

<h3 id="942-species-tree-gene-tree-conflict">9.4.2 Species Tree-Gene Tree Conflict</h3>
<p>(Recap and expansion of §3.1.2)</p>
<ul>
  <li>Biological processes causing gene tree topologies to differ from species tree topology:
    <ol>
      <li><strong>Incomplete Lineage Sorting (ILS):</strong> Due to ancestral polymorphism. Most significant when speciation events are close in time (short internal branches in species tree) and/or ancestral $N_e$ are large.</li>
      <li>Gene duplications and losses.</li>
      <li>Introgression or horizontal gene transfer.</li>
    </ol>
  </li>
  <li>This section focuses on ILS.</li>
  <li><strong>Probability of Mismatch ($P_{SG}$):</strong> Probability that the (true) gene tree topology $G$ differs from species tree $S$.
    <ul>
      <li><strong>Three Species ((A,B)ancestorAB, C)ancestorABC (Fig 9.8):</strong>
$P_{SG} = P(G \neq S) = \frac{2}{3} e^{-(\tau_{ABC}-\tau_{AB})/\theta_{AB}}$ (Eq 9.44)
where $\tau_{ABC}-\tau_{AB}$ is the duration of ancestral species AB, and $\theta_{AB}$ is its population size parameter. $2/3$ is the probability of random joining of 3 lineages in ABC to produce a gene tree discordant with ((A,B),C).
For HCG, $P_{SG} \approx 30\%$.</li>
    </ul>
  </li>
  <li><strong>Anomaly Zone (Fig 9.10):</strong> Regions of species tree parameter space where the most probable gene tree topology is <em>different</em> from the species tree topology.
    <ul>
      <li>Can occur for asymmetrical species trees with very short internal branches.</li>
      <li>E.g., Species tree $(((A,B),C),D)$. If internal branches $(\tau_{ABC}-\tau_{AB})$ and $(\tau_{ABCD}-\tau_{ABC})$ are very short, the gene tree $((A,B),(C,D))$ can be more probable than $(((A,B),C),D)$.</li>
    </ul>
  </li>
  <li><strong>Impact on Inference:</strong>
    <ul>
      <li><strong>Concatenation (Supermatrix):</strong> May converge to an incorrect species tree (the anomalous gene tree) if in the anomaly zone and many loci are used.</li>
      <li><strong>Majority Vote (Gene Tree Summary):</strong> Will also be inconsistent in the anomaly zone.</li>
      <li>Likelihood-based methods (ML or Bayesian) using the multispecies coalescent account for ILS and are consistent.</li>
    </ul>
  </li>
</ul>

<h3 id="943-estimation-of-species-trees">9.4.3 Estimation of Species Trees</h3>
<p>Methods to estimate the species tree topology $S$ and parameters $C$ from multi-locus data.</p>

<h4 id="9431-methods-using-gene-tree-topologies-only">9.4.3.1 Methods Using Gene Tree Topologies Only</h4>
<ul>
  <li>Input: A set of estimated gene tree topologies (one per locus).</li>
  <li>Ignore branch length information and uncertainty in gene tree estimation.</li>
  <li>Examples: Tree-mismatch method, gene tree parsimony (MDC), MPEST.</li>
  <li>Less efficient as they discard branch length information.</li>
</ul>

<h4 id="9432-methods-using-gene-trees-with-branch-lengths">9.4.3.2 Methods Using Gene Trees with Branch Lengths</h4>
<ul>
  <li>Input: Estimated gene trees with node ages (branch lengths).</li>
  <li><strong>Maximum Tree Algorithm (Liu et al. 2010a, STEM program):</strong>
    <ul>
      <li>Assumes a common $\theta$ for all populations.</li>
      <li>Likelihood $f(G,t \vert S, C) = (\frac{2}{\theta})^C e^{-(\frac{2}{\theta})T}$ (Eq 9.45), where $C=\sum (n_i-1)$ is total coalescent events, $T$ is total per-lineage-pair coalescent time.</li>
      <li>MLE for $\theta$: $\hat{\theta} = 2T/C$.</li>
      <li>Substituting $\hat{\theta}$ into likelihood: $L \propto (T/C)^{-C} e^{-C}$. Maximized when $T$ is minimized.</li>
      <li>The ML species tree is the one that implies the largest species divergence times ($\tau_s$) possible, given the constraints imposed by gene tree node ages ($t_{coalescence} \le \tau_{speciation}$). This tree minimizes $T$.</li>
      <li><strong>Algorithm 9.5 (Maximum Tree):</strong> Iteratively joins pairs of species/clades that have the smallest maximum-allowed divergence time (minimum of relevant gene tree coalescent times). Produces an ultrametric species tree.</li>
      <li><strong>Criticism:</strong> Ignores uncertainty in input gene trees.</li>
    </ul>
  </li>
</ul>

<h4 id="9433-singularities-on-the-likelihood-surface">9.4.3.3 Singularities on the Likelihood Surface</h4>
<ul>
  <li>If population sizes ($\theta_s$) are allowed to vary among branches, the multispecies coalescent likelihood $f(G,t \vert C)$ can become infinite for certain parameter values.</li>
  <li>Occurs if an ancestral population is collapsed onto a single coalescent event (branch length $\Delta\tau_P \to 0$ while $\theta_P \to 0$ such that rate $2/\theta_P \to \infty$). Similar to singularity in normal mixture models. (Eq 9.48)</li>
  <li>Not an issue if:
    <ul>
      <li>All $\theta_s$ are assumed equal (as in STEM).</li>
      <li>Sequence alignments are analyzed directly (likelihood averages over gene trees, Eq 9.49).</li>
      <li>Bayesian analysis is used (priors constrain $\theta_s &gt; 0$ and $\tau_s$ to be different).</li>
    </ul>
  </li>
</ul>

<h4 id="9434-methods-using-sequence-alignments">9.4.3.4 Methods Using Sequence Alignments</h4>
<ul>
  <li>Most statistically sound as they use all information and account for gene tree uncertainty.</li>
  <li>Full likelihood (Eq 9.42) or full Bayesian (Eq 9.49) approaches.</li>
  <li><strong>Implementations:</strong>
    <ul>
      <li><strong>BEST (Liu &amp; Pearl 2007; Liu 2008):</strong> Bayesian, uses MrBayes output of gene trees as input and applies importance sampling correction. Assumes common $\theta$. Prone to poor mixing.</li>
      <li><strong>*BEAST (Heled &amp; Drummond 2010):</strong> Bayesian, co-estimates gene trees and species tree simultaneously in one MCMC. More robust.</li>
      <li><strong>BUCKy (Ané et al. 2007; Baum 2007 “Bayesian Concordance Analysis”):</strong>
        <ul>
          <li>Estimates concordance factor for each clade (proportion of genome where clade is true).</li>
          <li>Uses Dirichlet process to cluster loci by shared gene tree topology.</li>
          <li>Does not use multispecies coalescent model for $f(G_i, t_i \vert S,C)$, so potentially prone to anomalous gene tree issues.</li>
        </ul>
      </li>
      <li><strong>SNAPP (Bryant et al. 2012):</strong> Bayesian MCMC for SNP data. Computes species tree likelihood directly from markers, integrating out gene trees.</li>
    </ul>
  </li>
  <li><strong>Example 9.3 (Sceloporus lizards, Fig 9.12):</strong> Species tree inference using BEST and *BEAST from 8 nuclear loci. Results show high posterior support for many clades despite weak/conflicting signal in individual gene trees. BPP used to estimate parameters on the *BEAST species tree.</li>
</ul>

<h3 id="944-migration">9.4.4 Migration</h3>
<p>Incorporating gene flow (migration) into the multispecies coalescent.</p>

<h4 id="9441-definitions-of-migration-rates">9.4.4.1 Definitions of Migration Rates</h4>
<ul>
  <li><strong>Forward Migration Rate ($m_{ij}$ from pop $i$ to $j$):</strong> Proportion of individuals in pop $j$ that are immigrants from pop $i$ in one generation ($m_{ij} = M_{ij}/N_j$, where $M_{ij}$ is number of individuals). This is the definition used here (“backward in time” from coalescent perspective).</li>
  <li><strong>Scaled Migration Rate ($M_{ij}$):</strong> Expected number of immigrant gene copies into population $j$ from population $i$ per generation ($M_{ij} = N_j m_{ij}$). (In some literature, this is $2N_j m_{ij}$ or $4N_j m_{ij}$).</li>
  <li>Alternative coalescent worldview migration rate: used in GENETREE, IMa2. An “i $\to$ j migration” in this view is a real-world migration from j to i.</li>
</ul>

<h4 id="9442-probability-density-of-gene-tree-with-migration-trajectory">9.4.4.2 Probability Density of Gene Tree with Migration Trajectory</h4>
<ul>
  <li><strong>Isolation-with-Migration (IM) Model:</strong> Allows migration between populations after divergence.</li>
  <li><strong>Two Species (Fig 9.13a):</strong> Parameters: $\theta_1, \theta_2, \theta_a$ (population sizes), $\tau$ (divergence time), $M_{12}, M_{21}$ (scaled migration rates).</li>
  <li><strong>Markov Chain for Lineage States (2 sequences per locus, Fig 9.13b):</strong>
    <ul>
      <li>States: $S_{11}$ (both lineages in pop 1), $S_{22}$ (both in pop 2), $S_{12}$ (one in each), $S_1$ (coalesced in pop 1), $S_2$ (coalesced in pop 2).</li>
      <li>Transition Rate Matrix $Q$: (Eq 9.50). Rates depend on $\theta_i$ and $M_{ij}$.
        <ul>
          <li>Coalescence rate $2/\theta_i$ if both in pop $i$.</li>
          <li>Migration rate $m_1 = 4M_{21}/\theta_1$ (for lineage in pop 1 to move to pop 2, backward in time).</li>
          <li>Migration rate $m_2 = 4M_{12}/\theta_2$ (for lineage in pop 2 to move to pop 1, backward in time).</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Gene Tree Density $f(G \vert C)$ (Fig 9.13b):</strong>
$f(G \vert C) = (\text{product of rates for events}) \times \exp(-\text{total rate} \times \text{duration})$
For example, $f(G \vert C) = (\frac{2}{\theta_2}) \cdot m_2^x \cdot m_1^y \cdot e^{-(m_1+m_2)U - (2m_1+2/\theta_1)V - (2m_2+2/\theta_2)W}$ (Eq 9.51, for specific G).</li>
  <li><strong>General Case (Multiple Species/Sequences):</strong> Variable-rate Poisson process. Density is product of rates for all coalescent and migration events, times probability of no other events.</li>
</ul>

<h4 id="9443-inference-using-data-from-only-a-few-genomes">9.4.4.3 Inference Using Data from Only a Few Genomes</h4>
<ul>
  <li><strong>ML for 2 sequences/locus (Fig 9.15):</strong>
    <ul>
      <li>Can analytically integrate out migration history to get $P(t \vert C)$, density of divergence time $t=T_{MRCA}$ between the two sequences. (Eq 9.52)</li>
      <li>Log-likelihood: $l(C) = \sum_h \log \int_0^\infty f(t \vert C) f(X_h \vert t) dt$. (Eq 9.53)</li>
      <li>Feasible for genome-scale data (many loci) if only 2-3 sequences per locus.</li>
    </ul>
  </li>
  <li>Bayesian MCMC for IM models (IM, IMa, MIGRATE) is computationally very intensive, limited to few loci.</li>
</ul>

<h2 id="95-species-delimitation">9.5 Species Delimitation</h2>

<p>Inferring number of species, species boundaries, and discovering new species.</p>

<h3 id="951-species-concept-and-species-delimitation">9.5.1 Species Concept and Species Delimitation</h3>
<ul>
  <li><strong>Biological Species Concept (BSC, Mayr 1942):</strong> Species are groups of actually or potentially interbreeding populations, reproductively isolated from other such groups.
    <ul>
      <li>Common mode: Allopatric speciation.</li>
      <li>Limitations: Asexual species, hybridization.</li>
    </ul>
  </li>
  <li><strong>Phylogenetic/Genealogical Species Concept (PSC, GSC):</strong> Species are basal, exclusive groups of organisms whose members are more closely related to each other than to outsiders, and contain no such exclusive group within.
    <ul>
      <li>Often operationalized as reciprocal monophyly in gene trees.</li>
    </ul>
  </li>
  <li>Species delimitation is important despite definitional controversies. Genetic data increasingly used.</li>
</ul>

<h3 id="952-simple-methods-for-analysing-genetic-data">9.5.2 Simple Methods for Analysing Genetic Data</h3>
<ul>
  <li><strong>Cutoffs:</strong> E.g., “10x rule” (mtDNA divergence between species &gt; 10x within-species polymorphism). Arbitrary.</li>
  <li><strong>Reciprocal Monophyly:</strong> Fails to account for gene tree error and ILS. Low power.</li>
  <li><strong>LRTs using Gene Tree Topologies (Knowles &amp; Carstens 2007; O’Meara 2010):</strong> Compare one- vs. two-species models. Ignores gene tree error.</li>
  <li><strong>STEM-based (Carstens &amp; Dewry 2010; Ence &amp; Carstens 2011 “SpedeSTEM”):</strong> Fit species tree to gene trees by ML, compare delimitation models using AIC. Ignores gene tree error.</li>
  <li><strong>GMYC (Generalized Mixed Yule Coalescent, Pons et al. 2006):</strong> Finds switch point on a single gene tree from coalescent (within-species) to Yule (between-species) process. Ignores ILS and gene tree error.</li>
</ul>

<h3 id="953-bayesian-species-delimitation">9.5.3 Bayesian Species Delimitation</h3>
<ul>
  <li>Uses multispecies coalescent model in a Bayesian framework (Yang &amp; Rannala 2010, BPP program).</li>
  <li><strong>Method:</strong>
    <ul>
      <li>User provides a “guide tree” for populations/subspecies/morphotypes.</li>
      <li>rjMCMC is used to evaluate models corresponding to collapsing (joining) or not collapsing (splitting) internal nodes on the guide tree. Each collapsed state represents a species delimitation scheme.</li>
      <li>Assumes complete isolation after speciation (strict BSC).</li>
      <li>Likelihood on sequence alignments accounts for gene tree uncertainty and ILS.</li>
    </ul>
  </li>
  <li><strong>Models Evaluated (Fig 9.18):</strong> Models differ in number of species (which nodes are collapsed) and species phylogeny (relationships among delimited species).</li>
  <li><strong>rjMCMC Moves (‘Split’ and ‘Join’, Fig 9.19):</strong>
    <ul>
      <li>A ‘split’ move proposes to split a currently merged species (node $i$) back into its two descendant populations ($j,k$ from guide tree), introducing parameters $\tau_i, \theta_j, \theta_k$.</li>
      <li>A ‘join’ move proposes to merge two currently distinct species ($j,k$ whose parent is $i$) into one, removing $\tau_i, \theta_j, \theta_k$.</li>
      <li>Acceptance ratio: (Eq 9.55).</li>
      <li>Mixing can be poor due to strong constraint of gene trees on new $\tau_i$. Modified algorithm (Rannala &amp; Yang 2013) proposes $\tau_i$ first, then adjusts gene trees, improving mixing.</li>
    </ul>
  </li>
</ul>

<h3 id="954-the-impact-of-guide-tree-prior-and-migration">9.5.4 The Impact of Guide Tree, Prior, and Migration</h3>
<ul>
  <li><strong>Guide Tree:</strong> Can be from morphology, mtDNA, or concatenated nuclear data. Incorrect guide tree can lead to over-splitting if it wrongly separates very closely related populations.</li>
  <li><strong>Prior:</strong> Priors on $\tau_s, \theta_s$ can affect posterior model probabilities.</li>
  <li><strong>Migration:</strong> BPP assumes no gene flow.
    <ul>
      <li>Simulation (Zhang et al. 2011, Fig 9.20):
        <ul>
          <li>If migration $M=Nm \ll 1$ (e.g., &lt; 0.1), BPP infers two species (correctly, if they are on path to speciation).</li>
          <li>If $M \gg 1$ (e.g., &gt; 10), BPP infers one species (effectively one panmictic unit).</li>
          <li>Phase change around $M=1$.</li>
        </ul>
      </li>
      <li>Robust to complex population structures like stepping-stones (Fig 9.21) as long as $M$ between directly sampled populations is interpreted.</li>
    </ul>
  </li>
</ul>

<h3 id="955-pros-and-cons-of-bayesian-species-delimitation">9.5.5 Pros and Cons of Bayesian Species Delimitation</h3>
<ul>
  <li><strong>Pros:</strong>
    <ul>
      <li>Uses multi-locus data fully.</li>
      <li>Accounts for ILS and gene tree uncertainty.</li>
      <li>More objective than traditional taxonomy (explicit model and assumptions).</li>
      <li>Can incorporate prior biological information (via guide tree, priors).</li>
      <li>Good power with small amounts of gene flow.</li>
    </ul>
  </li>
  <li><strong>Cons:</strong>
    <ul>
      <li>Assumes neutral evolution (no selection, especially species-specific).</li>
      <li>Models differ in assumptions about isolation, but reticent about causes (reproductive vs. geographic).</li>
      <li>Interpretation of “species” when allopatric populations are genetically divergent but not necessarily reproductively isolated can be ambiguous.</li>
    </ul>
  </li>
</ul>

<h1 id="chapter-10-molecular-clock-and-estimation-of-species-divergence-times">Chapter 10: Molecular Clock and Estimation of Species Divergence Times</h1>

<p>This chapter explores the molecular clock hypothesis, methods for testing it, and likelihood-based approaches for estimating species divergence times, including global and local clock models, and Bayesian methods.</p>

<h2 id="101-overview">10.1 Overview</h2>
<ul>
  <li><strong>Molecular Clock Hypothesis (Zuckerkandl &amp; Pauling 1965):</strong> The rate of DNA or protein sequence evolution is approximately constant over time and among evolutionary lineages.
    <ul>
      <li>Initial observations (1960s): Number of differences between proteins (e.g., hemoglobin, cytochrome c) from different species was roughly proportional to their divergence times.</li>
    </ul>
  </li>
  <li><strong>Clarifications:</strong>
    <ol>
      <li><strong>Stochastic Clock:</strong> “Ticks” (substitutions) arrive randomly, following exponential time intervals under Markov models, not regularly.</li>
      <li><strong>Protein-Specific Rates:</strong> Different proteins/regions evolve at different rates. Each protein has its “own clock.”</li>
      <li><strong>Lineage Specificity:</strong> Rate constancy might hold within a group (e.g., primates) but be violated in broader comparisons (e.g., across vertebrates).</li>
    </ol>
  </li>
  <li><strong>Impact and Controversy:</strong>
    <ul>
      <li><strong>Utility:</strong> If rates are constant, molecular data can be used to reconstruct trees and estimate divergence times.</li>
      <li><strong>Mechanism Debate:</strong> Entwined with neutralist-selectionist debate. Constant rates seemed incompatible with neo-Darwinian selection (species with different life histories should have different selection pressures). Neutral theory (Kimura 1968; King &amp; Jukes 1969) provided a mechanism: rate of evolution = neutral mutation rate ($\mu_0 = \mu f_0$), independent of population size or environment, if $\mu$ and $f_0$ (fraction of neutral mutations) are constant.</li>
    </ul>
  </li>
  <li><strong>Factors Affecting Rates (leading to clock violations):</strong>
    <ul>
      <li><strong>Generation Time:</strong> Shorter generation time $\implies$ more germ-line divisions/year $\implies$ higher substitution rate (e.g., primate slowdown, hominoid slowdown).</li>
      <li><strong>DNA Repair Efficiency:</strong> Less efficient repair $\implies$ higher mutation/substitution rate.</li>
      <li><strong>Body Size:</strong> Negatively correlated with substitution rates (rodents fast, primates intermediate, whales slow). Body size correlates with generation time, metabolic rate, etc.</li>
    </ul>
  </li>
  <li><strong>Molecular Dating and Fossil Record:</strong>
    <ul>
      <li>Molecular clock used to date species divergences often yields dates conflicting with fossil record (e.g., origin of animal phyla much older molecularly than Cambrian explosion fossils).</li>
      <li>Discrepancies due to: incomplete fossil record, misinterpretation of fossils, inaccuracies in early molecular dating (e.g., model misspecification, poor calibration).</li>
      <li>Modern analyses integrating fossils and molecular data yield more consistent estimates.</li>
    </ul>
  </li>
</ul>

<h2 id="102-tests-of-the-molecular-clock">10.2 Tests of the Molecular Clock</h2>

<h3 id="1021-relative-rate-tests">10.2.1 Relative-Rate Tests</h3>
<ul>
  <li><strong>Concept:</strong> Compare evolutionary rates between two ingroup species (A, B) using an outgroup (C) (Fig 10.1).</li>
  <li><strong>Sarich &amp; Wilson (1973):</strong> If clock holds, distance from ancestor O to A ($d_{OA}$) equals distance to B ($d_{OB}$), i.e., $a=b$ in Fig 10.1b. Or, $d_{AC} = d_{BC}$.</li>
  <li><strong>Fitch (1976):</strong> Calculated changes $a = (d_{AB} + d_{AC} - d_{BC})/2$ and $b = (d_{AB} + d_{BC} - d_{AC})/2$. Compared $(a-b)^2/(a+b)$ to $\chi^2_1$. Fails to correct for multiple hits.</li>
  <li><strong>Wu &amp; Li (1985):</strong> Corrected distances for multiple hits (e.g., K80 model). Calculated $d = d_{AC} - d_{BC}$ and its standard error $\text{SE}(d)$. Compared $d/\text{SE}(d)$ to standard normal.</li>
  <li><strong>Tajima (1993):</strong> Non-model-based. Compares counts of site patterns $xyy$ ($m_1$) vs. $xyx$ ($m_2$). Compare $(m_1-m_2)^2/(m_1+m_2)$ to $\chi^2_1$.</li>
  <li><strong>Likelihood Framework (Muse &amp; Weir 1992):</strong>
    <ul>
      <li>Calculate log-likelihood with branch lengths $a, b$ free ($l_1$) and with $a=b$ constrained ($l_0$).</li>
      <li>Test statistic $2\Delta l = 2(l_1 - l_0) \sim \chi^2_1$.</li>
    </ul>
  </li>
</ul>

<h3 id="1022-likelihood-ratio-test-lrt">10.2.2 Likelihood Ratio Test (LRT)</h3>
<ul>
  <li><strong>Felsenstein (1981):</strong> General test for a tree of any size.</li>
  <li><strong>$H_0$ (Clock):</strong> Tree is rooted, $s-1$ parameters (ages of $s-1$ internal nodes). (Fig 10.2a)</li>
  <li><strong>$H_1$ (No Clock):</strong> Tree is unrooted, $2s-3$ parameters (branch lengths). (Fig 10.2b)</li>
  <li>The clock model is nested within the no-clock model by applying $s-2$ equality constraints.</li>
  <li>Test statistic: $2\Delta l = 2(l_1 - l_0) \sim \chi^2_{s-2}$.</li>
  <li><strong>Example 10.1 (Primate 12S rRNA):</strong> $s=6$. $df=4$. $2\Delta l = 18.60$, $P &lt; 0.001$. Clock rejected.</li>
</ul>

<h3 id="1023-limitations-of-molecular-clock-tests">10.2.3 Limitations of Molecular Clock Tests</h3>
<ol>
  <li><strong>Weak Null Hypothesis:</strong> Tests if tips are equidistant from root, not true rate constancy over time. (e.g., rates accelerating/decelerating in all lineages simultaneously would not be rejected).</li>
  <li><strong>Average vs. Constant Rate:</strong> Cannot distinguish a truly constant rate from an average of variable rates within a lineage.</li>
  <li><strong>Lack of Power:</strong> Failure to reject clock might be due to insufficient data, especially for few taxa (e.g., relative-rate test with 3 species). LRT with multiple species is generally powerful.</li>
</ol>

<h3 id="1024-index-of-dispersion-r">10.2.4 Index of Dispersion ($R$)</h3>
<ul>
  <li>$R = \text{Variance}/\text{Mean}$ of number of substitutions among lineages (assuming star tree).</li>
  <li>If clock holds (Poisson process of substitutions), $R=1$. $R&gt;1$ (over-dispersed clock) suggests violation.</li>
  <li>Used more as a diagnostic for selection vs. neutrality than a strict clock test.</li>
  <li>Obsolete due to sensitivity to assumed star phylogeny and availability of more rigorous LRTs.</li>
</ul>

<h2 id="103-likelihood-estimation-of-divergence-times">10.3 Likelihood Estimation of Divergence Times</h2>

<h3 id="1031-global-clock-model">10.3.1 Global Clock Model</h3>
<ul>
  <li>Assumes clock holds for all lineages.</li>
  <li><strong>Procedure:</strong>
    <ol>
      <li>Estimate branch lengths (distances from nodes to tips) from sequence data, typically using ML on a rooted tree topology.</li>
      <li>Use fossil calibrations (node ages known without error) to convert relative distances to absolute geological times and estimate the substitution rate $\mu$.
        <ul>
          <li>Example (Fig 10.3): 5 species. If $t_2, t_4$ are fossil calibrations, estimate $\mu, t_1, t_3$.</li>
          <li>Branch length on tree = rate $\times$ time duration.</li>
          <li>Likelihood $f(X \vert \mu, t_1, t_3; t_2, t_4)$ is calculated via pruning algorithm.</li>
          <li>Optimize $\mu, t_1, t_3$ under constraints (e.g., $t_1 &gt; \max(t_2, t_4)$, $0 &lt; t_3 &lt; t_2$).</li>
        </ul>
      </li>
    </ol>
  </li>
  <li><strong>Issues:</strong>
    <ul>
      <li>Assumed substitution model matters (can affect distance estimates).</li>
      <li>Assumed tree topology matters. Best to use a well-supported (e.g., ML) binary tree.</li>
    </ul>
  </li>
</ul>

<h3 id="1032-local-clock-models-relaxed-clocks">10.3.2 Local Clock Models (Relaxed Clocks)</h3>
<ul>
  <li>Address clock violations by allowing different rates on different parts of the tree.</li>
  <li><strong>Approach:</strong> Assign different rates to branches/clades. Estimate divergence times and rates by ML.
    <ul>
      <li>Example (Fig 10.4, Quartet-Dating): ((a,b),(c,d)). One rate for left (a,b) part, another for right (c,d) part.</li>
      <li>Generalization (Yoder &amp; Yang 2000): Arbitrary number of rates assigned to branches. $k-1$ extra rate parameters if $k$ rates.</li>
    </ul>
  </li>
  <li><strong>Drawback:</strong> Arbitrary assignment of rates. Model can become unidentifiable.</li>
</ul>

<h3 id="1033-heuristic-rate-smoothing-methods">10.3.3 Heuristic Rate-Smoothing Methods</h3>
<p>Attempt to estimate rates and times jointly without <em>a priori</em> rate assignments, by minimizing rate changes across the tree.</p>
<ul>
  <li><strong>Sanderson (1997) Penalized Likelihood:</strong>
    <ul>
      <li>Input: Branch lengths $b_k$ (from no-clock ML or parsimony).</li>
      <li>Minimize: $W(t,r) = \sum_k (r_k - r_{anc(k)})^2$ (penalty for rate changes) (Eq 10.1)</li>
      <li>Subject to: $r_k T_k = b_k$ (rates and time durations $T_k$ must match observed branch lengths) (Eq 10.2)</li>
      <li><strong>Improved Version (Sanderson 2002):</strong> Maximize
$l(t,r,\lambda; X) = \log{f(X\vert t,r)} - \lambda \sum_k (r_k - r_{anc(k)})^2$ (Eq 10.3)
Log-likelihood of data + penalty. $\lambda$ is smoothing parameter (chosen by cross-validation).
$f(X\vert t,r)$ approximated using Poisson for changes on branches.</li>
    </ul>
  </li>
  <li><strong>Yang (2004) Modification:</strong>
    <ul>
      <li>Maximize: $l(t,r,\nu; X) = \log{f(X\vert t,r)} + \log{f(r\vert t,\nu)} + \log{f(\nu)}$ (Eq 10.4)</li>
      <li>$f(X\vert t,r)$: Likelihood using normal approx. to MLEs of branch lengths.</li>
      <li>$f(r\vert t,\nu)$: Prior for rates based on geometric Brownian motion (GBM) model of rate drift (Thorne et al. 1998). Given ancestral rate $r_A$, current rate $r$ has density:
$f(r\vert r_A, t, \nu) = \frac{1}{r\sqrt{2\pi\nu t}} \exp\left{ -\frac{1}{2\nu t} \left(\log\frac{r}{r_A} + \frac{1}{2}\nu t\right)^2 \right}$ (Eq 10.5)
$\nu$ is rate-drift parameter. (Fig 10.5)</li>
      <li>$f(\nu)$: Prior on $\nu$ (e.g., exponential).</li>
    </ul>
  </li>
  <li><strong>Issues with Heuristic Methods:</strong> “Log likelihood” functions are ad hoc (not true likelihoods). Statistical properties uncertain.</li>
</ul>

<h3 id="1034-uncertainties-in-calibrations">10.3.4 Uncertainties in Calibrations</h3>
<ul>
  <li><strong>10.3.4.1 Difficulty of Dating with Uncertain Calibrations:</strong>
    <ul>
      <li>Fossil dating and placement on phylogeny are prone to errors.</li>
      <li>Geological events for calibration also have uncertainties.</li>
      <li>Probabilistic modeling of fossil discovery/dating is ideal but complex.</li>
      <li>For likelihood methods, it’s unclear how to use calibrations specified as distributions (rather than fixed points).</li>
    </ul>
  </li>
  <li><strong>10.3.4.2 Problems with Naïve Likelihood Implementations:</strong>
    <ul>
      <li>Treating fossil minimum bounds as fixed known ages leads to systematic underestimation of older dates if multiple conflicting minimums are used.</li>
      <li>Sanderson’s penalized likelihood with interval constraints $(t_L, t_U)$ on a node $t_C$ makes the model unidentifiable (many rate/time combinations give same fit). At least one point calibration (known age) is needed to avoid this.</li>
      <li>Nonparametric bootstrap on sites, keeping calibrations fixed, fails to account for fossil uncertainty and gives misleadingly narrow CIs.</li>
    </ul>
  </li>
</ul>

<h3 id="1035-dating-viral-divergences">10.3.5 Dating Viral Divergences</h3>
<ul>
  <li>RNA viruses evolve fast; samples collected at different times (heterochronous data) can calibrate the clock.</li>
  <li><strong>Tip-Dating (Rambaut 2000):</strong> Sequences sampled earlier are closer to the root.
    <ul>
      <li>Example (Fig 10.6): 3 sequences $a,b,c$ sampled at $t_a, t_b, 0$. Rate can be estimated as $(d_{ac}-d_{bc})/(t_b-t_a)$.</li>
    </ul>
  </li>
  <li>If clock violated, local clock models can be used, but estimation is harder.</li>
</ul>

<h3 id="1036-dating-primate-divergences">10.3.6 Dating Primate Divergences</h3>
<ul>
  <li><strong>Example (Steiper et al. 2004 data, 5 nuclear loci, 4 species, Fig 10.7):</strong>
    <ul>
      <li>Fix H-C divergence at 7 MYA, Baboon-Macaque at 6 MYA.</li>
      <li><strong>Global Clock ML:</strong> Root age ($t_1$) $\approx 33-34$ MY. Rate $r \approx 6.6 \times 10^{-10}$ subst/site/year. (Table 10.1)</li>
      <li><strong>Local Clock ML (quartet-dating):</strong> Ape rate $r_{ape} \approx 5.4 \times 10^{-10}$, monkey rate $r_{monkey} \approx 8.0 \times 10^{-10}$. Root age similar.</li>
      <li>These ML analyses ignore fossil uncertainty, leading to overly precise CIs.</li>
    </ul>
  </li>
</ul>

<h2 id="104-bayesian-estimation-of-divergence-times">10.4 Bayesian Estimation of Divergence Times</h2>

<h3 id="1041-general-framework">10.4.1 General Framework</h3>
<ul>
  <li>MCMC algorithm developed by Thorne et al. (1998), Kishino et al. (2001) (MULTIDIVTIME), Yang &amp; Rannala (2006) (MCMCTREE), Drummond et al. (2006) (BEAST).</li>
  <li><strong>Joint Posterior:</strong>
$f(t, r, \theta \vert X) \propto f(\theta) f(t\vert \theta) f(r\vert t, \theta) f(X\vert t, r, \theta)$ (Eq 10.6)
where $t$=divergence times, $r$=rates, $\theta$=substitution parameters.
$f(X\vert t,r,\theta)$: Sequence likelihood.
$f(r\vert t,\theta)$: Prior on rates (rate-drift model).
$f(t\vert \theta)$: Prior on divergence times (incorporating fossil calibrations).
$f(\theta)$: Prior on substitution parameters.</li>
  <li>MCMC algorithm samples $(t,r,\theta)$. Marginal posterior for $t$ (i.e., $f(t\vert X)$) obtained from samples. (Eq 10.7)</li>
  <li><strong>MCMC Sketch:</strong>
    <ul>
      <li>Update $t$ (respecting node order constraints).</li>
      <li>Update $r$ (e.g., based on rate-drift model).</li>
      <li>Update $\theta$.</li>
      <li>Global move: Scale all $t_i$ by $c$, all $r_i$ by $1/c$.</li>
    </ul>
  </li>
</ul>

<h3 id="1042-approximate-calculation-of-likelihood">10.4.2 Approximate Calculation of Likelihood</h3>
<ul>
  <li>Exact likelihood $f(X\vert t,r,\theta)$ is computationally expensive.</li>
  <li><strong>Approximation (Thorne et al. 1998; Kishino et al. 2001):</strong>
    <ol>
      <li>Estimate MLEs of branch lengths $\hat{b}$ and their var-cov matrix $V = -H^{-1}$ (from Hessian $H$) from data <em>without</em> clock.</li>
      <li>During MCMC, approximate $\log f(X\vert t,r,\theta)$ by a multivariate normal density for branch lengths $b$ predicted by current $t,r$:
$l(b) \approx l(\hat{b}) + g(\hat{b})^T(b-\hat{b}) + \frac{1}{2}(b-\hat{b})^T H(\hat{b}) (b-\hat{b})$ (Eq 10.8)
If all $\hat{b}_i &gt; 0$, then $g(\hat{b})=0$.
        <ul>
          <li>More accurate if Taylor expansion is on transformed branch lengths (e.g., arcsine). (Fig 10.8)</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h3 id="1043-prior-on-evolutionary-rates">10.4.3 Prior on Evolutionary Rates</h3>
<ul>
  <li><strong>Correlated-Rate Model (Geometric Brownian Motion, GBM):</strong> (Thorne et al. 1998) (Fig 10.5)
    <ul>
      <li>Rate at root $r_{root} \sim \text{Gamma}$.</li>
      <li>Rate $r$ at end of branch of duration $t$, given ancestral rate $r_A$: $\log r \sim N(\log r_A - \frac{1}{2}\nu t, \nu t)$. Density $f(r\vert r_A)$ as in Eq 10.9.</li>
      <li>$\nu$ is rate-drift parameter (prior, e.g., Gamma). Small $\nu \implies$ clock-like.</li>
    </ul>
  </li>
  <li><strong>Independent-Rate Model:</strong> (Drummond et al. 2006; Rannala &amp; Yang 2007)
    <ul>
      <li>Rate $r$ for each branch drawn i.i.d. from a common distribution (e.g., log-normal):
$f(r\vert \mu_r, \sigma_r^2) = \frac{1}{r\sqrt{2\pi\sigma_r^2}} \exp\left{ -\frac{1}{2\sigma_r^2} \left(\log(r/\mu_r) + \frac{1}{2}\sigma_r^2\right)^2 \right}$ (Eq 10.10)
$\mu_r$ is mean rate, $\sigma_r^2$ measures departure from clock.</li>
    </ul>
  </li>
  <li>Bayes factor comparisons between these rate models are sensitive to priors on $\nu$ or $\sigma_r^2$. Robustness of time estimates to rate prior is more important.</li>
</ul>

<h3 id="1044-prior-on-divergence-times-and-fossil-calibrations">10.4.4 Prior on Divergence Times and Fossil Calibrations</h3>
<ul>
  <li>Prior $f(t)$ incorporates fossil information.</li>
  <li><strong>Kishino et al. (2001):</strong> Gamma prior for root age. Uniform Dirichlet to break paths into segments.</li>
  <li><strong>Soft Bounds (Yang &amp; Rannala 2006):</strong> Use arbitrary distributions for calibrations, not just hard min/max bounds.
    <ul>
      <li>Kernel density for node ages based on birth-death-sampling process: $g(t) = \lambda p_1(t)/v_{t_1}$ (Eq 10.11, 10.12)
$P(0,t)$ is prob. lineage at $t$ leaves $\ge 1$ descendant today (Eq 10.14).
If $\lambda=\mu$ (birth=death), $g(t) = (1+\rho\lambda t_1) / [t_1(1+\rho\lambda t)^2]$ (Eq 10.15).
Joint density of $s-2$ node ages (given root $t_1$): $f(t_2, \dots, t_{s-1}) = (s-2)! \prod_{j=2}^{s-1} g(t_j)$ (Eq 10.16)
(Fig 10.10, 10.11 show shapes of $g(t)$).</li>
      <li><strong>Fossil Calibrations $f(t_C)$:</strong> Specified by user (e.g., from Fig 10.9).</li>
      <li>Full prior $f(t) = f_{BD}(t_{-C}\vert t_C) f(t_C)$ (Eq 10.17, 10.18). (Conditional construction).</li>
      <li>Effective prior used by program (after node age constraints) can differ from user-specified prior. Run MCMC without data to check effective prior.</li>
    </ul>
  </li>
</ul>

<h3 id="1045-uncertainties-in-time-estimates">10.4.5 Uncertainties in Time Estimates</h3>
<ul>
  <li><strong>Infinite-Site Theory (Yang &amp; Rannala 2006; Rannala &amp; Yang 2007):</strong>
    <ul>
      <li>As sequence data $\to \infty$, branch lengths are known without error.</li>
      <li>Posterior of times $f(t\vert X)$ converges to a 1D distribution, not a point. Root age $t_1$ has a posterior; other times $t_i$ are linear functions of $t_1$.</li>
      <li>Plot of posterior CI width vs. posterior mean for node ages approaches a straight line (Fig 10.12 “infinite-site plot”). Slope reflects precision of fossil calibrations.</li>
    </ul>
  </li>
  <li><strong>Finite-Site Data (dos Reis &amp; Yang 2013a):</strong> Posterior variance of node age = variance from fossil uncertainty + variance from finite data. CI width approaches infinite-data limit at rate $1/\sqrt{n}$.</li>
  <li>Relaxed clock makes time estimation more complex. Number of loci more important than sites per locus for precision.</li>
</ul>

<h3 id="1046-dating-viral-divergences">10.4.6 Dating Viral Divergences</h3>
<ul>
  <li>Use sampling times of viral sequences to calibrate clock.</li>
  <li>Birth-death-sequential-sampling (BDSS) models (Stadler 2010) provide priors on node ages. Can estimate $R_0$ (basic reproductive number).</li>
  <li>Relaxed clocks can be used if global clock violated. Caution if dating deep events with recent samples.</li>
</ul>

<h3 id="1047-application-to-primate-and-mammalian-divergences">10.4.7 Application to Primate and Mammalian Divergences</h3>
<ul>
  <li><strong>10.4.7.1 Primate Data (Steiper et al., Table 10.1):</strong>
    <ul>
      <li>4 species, 5 nuclear loci. JC69 and HKY85+$\Gamma_5$. Global clock, independent rates, correlated rates.</li>
      <li>Soft bounds for H-C (7MYA) and Baboon-Macaque (6MYA) calibrations. Max root age 60MYA.</li>
      <li>Posterior mean root age $t_1 \approx 33$ MY across models. CIs much wider than ML CIs.</li>
    </ul>
  </li>
  <li><strong>10.4.7.2 Mammalian Divergence Times (dos Reis &amp; Yang 2013a, Fig 10.13, 10.14, 10.15):</strong>
    <ul>
      <li>36 species, mtDNA (1st+2nd codon pos). HKY85+$\Gamma_5$. Correlated rates. 24 min, 14 max fossil calibrations.</li>
      <li>Approximate likelihood (arcsine transform) very similar to exact.</li>
      <li>Infinite-site plot (Fig 10.15) shows $R^2=0.516$, indicating significant contribution from sequence data uncertainty (not yet at infinite-data limit).</li>
    </ul>
  </li>
</ul>

<h2 id="105-perspectives">10.5 Perspectives</h2>
<ul>
  <li>Confounding of time and rate is greatest obstacle.</li>
  <li>Relaxing clock is tricky. Multi-locus analysis and multiple calibrations are key.</li>
  <li>Probabilistic modeling of fossil record to get objective priors for calibrations is a promising direction.</li>
</ul>

<h1 id="chapter-11-neutral-and-adaptive-protein-evolution">Chapter 11: Neutral and Adaptive Protein Evolution</h1>

<p>This chapter discusses the roles of natural selection in the evolution of protein-coding genes, focusing on methods to detect positive (Darwinian) selection.</p>

<h2 id="111-introduction">11.1 Introduction</h2>
<ul>
  <li><strong>Adaptive Evolution:</strong> The ultimate source of morphological, behavioral, and physiological adaptations, species divergences, and evolutionary innovations.</li>
  <li><strong>Role of Natural Selection:</strong> While ubiquitous in shaping organismal traits, its role in gene/genome evolution is more debated.</li>
  <li><strong>Neutral Theory (Kimura 1968; King &amp; Jukes 1969):</strong> Claims most observed molecular variation (within and between species) is due to random fixation of mutations with little fitness effect, not natural selection.</li>
  <li><strong>$d_N/d_S$ Ratio ($\omega$):</strong> A key measure of selective pressure at the protein level.
    <ul>
      <li>$d_N$: nonsynonymous substitution rate (changes amino acid).</li>
      <li>$d_S$: synonymous substitution rate (does not change amino acid).</li>
      <li>The synonymous rate is used as a benchmark for the neutral mutation rate.</li>
      <li><strong>Interpreting $\omega$:</strong>
        <ul>
          <li>$\omega = 1$ ($d_N = d_S$): Neutral evolution (nonsynonymous mutations fixed at same rate as synonymous ones).</li>
          <li>$\omega &lt; 1$ ($d_N &lt; d_S$): Purifying (negative) selection (deleterious nonsynonymous mutations are removed, reducing their fixation rate).</li>
          <li>$\omega &gt; 1$ ($d_N &gt; d_S$): Positive (Darwinian) selection (advantageous nonsynonymous mutations are favored and fixed at a higher rate).</li>
        </ul>
      </li>
      <li>A significantly higher $d_N$ than $d_S$ is evidence for adaptive protein evolution.</li>
    </ul>
  </li>
  <li><strong>Noncoding DNA:</strong> Detecting adaptive evolution is harder due to lack of a clear neutral benchmark like $d_S$.</li>
  <li><strong>Limitations of Pairwise $\omega$:</strong> Averaging $d_N$ and $d_S$ over whole genes and long evolutionary times rarely detects positive selection because it’s often episodic (affecting few sites for short periods).</li>
  <li><strong>Chapter Focus:</strong> Codon models in a phylogenetic context to detect positive selection on specific lineages or sites. Primarily ML and LRT methods.</li>
</ul>

<h2 id="112-the-neutral-theory-and-tests-of-neutrality">11.2 The Neutral Theory and Tests of Neutrality</h2>

<h3 id="1121-the-neutral-and-nearly-neutral-theories">11.2.1 The Neutral and Nearly Neutral Theories</h3>
<ul>
  <li><strong>Selection Coefficient ($s$):</strong> Measures relative fitness of a new mutant allele $a$ vs. wild-type $A$. Fitnesses $AA:1, Aa:1+s, aa:1+2s$.
    <ul>
      <li>$s &lt; 0$: Negative selection.</li>
      <li>$s = 0$: Neutral.</li>
      <li>$s &gt; 0$: Positive selection.</li>
    </ul>
  </li>
  <li><strong>Fate of Mutation:</strong> Determined by interaction of selection and random genetic drift.
    <ul>
      <li>Effective population size $N_e$. Key parameter is $N_e s$.</li>
      <li>If $\vert N_e s \vert \gg 1$: Selection dominates.</li>
      <li>If $\vert N_e s \vert \approx 0$: Drift dominates (mutation is effectively neutral).</li>
    </ul>
  </li>
  <li><strong>Neutral Theory (Kimura 1968; King &amp; Jukes 1969):</strong> Proposed to explain high levels of allozyme polymorphism.
    <ul>
      <li><strong>Claims/Predictions:</strong>
        <ol>
          <li>Most mutations are deleterious and removed by purifying selection.</li>
          <li>Substitution rate = neutral mutation rate ($\mu_0 = \mu \times f_0$, where $\mu$ is total mutation rate, $f_0$ is fraction of neutral mutations). If $\mu_0$ is constant, molecular clock holds.</li>
          <li>Functionally important genes/regions evolve slower (smaller $f_0$). Negative correlation between functional importance and substitution rate.</li>
          <li>Within-species polymorphism and between-species divergence are two phases of the same neutral process.</li>
          <li>Morphological evolution is driven by selection; neutral theory concerns molecular level.</li>
        </ol>
      </li>
    </ul>
  </li>
  <li><strong>Nearly Neutral Theory (Ohta 1973, 1992):</strong> Allows for slightly deleterious or slightly advantageous mutations whose fate is influenced by both drift and selection (i.e., $\vert N_e s \vert$ is small but not zero). Dynamics depend on $N_e, s$. (Fig 11.1 illustrates different theories).</li>
</ul>

<h3 id="1122-tajimas-d-statistic">11.2.2 Tajima’s $D$ Statistic</h3>
<ul>
  <li>Compares two estimators of $\theta = 4N_e\mu$ under the infinite-sites model (each mutation at a new site).
    <ol>
      <li>$\hat{\theta}<em>S = S / (l \cdot a_n)$: Based on number of segregating sites $S$ in a sample of $n$ sequences of length $l$. $a_n = \sum</em>{i=1}^{n-1} 1/i$. (Watterson 1975)</li>
      <li>$\hat{\theta}_\pi = \pi$: Average number of pairwise differences between sequences. (Tajima 1983)</li>
    </ol>
  </li>
  <li><strong>Tajima’s $D$:</strong>
$D = \frac{\hat{\theta}<em>\pi - \hat{\theta}_S}{\text{SE}(\hat{\theta}</em>\pi - \hat{\theta}_S)}$ (Eq 11.1)</li>
  <li><strong>Interpretation under Neutrality:</strong> $E(D)=0$. Significant deviation suggests departure from strict neutrality.
    <ul>
      <li>$D &lt; 0$: Excess of low-frequency variants (singletons inflate $\hat{\theta}_S$). Consistent with purifying selection or population expansion.</li>
      <li>$D &gt; 0$: Excess of intermediate-frequency variants. Consistent with balancing selection or population shrinkage.</li>
    </ul>
  </li>
</ul>

<h3 id="1123-fu-and-lis-d-and-fay-and-wus-h-statistics">11.2.3 Fu and Li’s $D$, and Fay and Wu’s $H$ Statistics</h3>
<p>Based on the site frequency spectrum (SFS): $(s_1, s_2, \dots, s_{n-1})$, where $s_j$ is number of sites where $j$ sequences carry the mutant allele. Requires outgroup to infer ancestral state.</p>
<ul>
  <li><strong>Fu and Li’s $D$ (1993):</strong> Distinguishes internal ($\eta_I$) and external ($\eta_E$, singletons) mutations on the genealogy.
$D_{FL} = \frac{\eta_I - (a_n-1)\eta_E}{\text{SE}(\eta_I - (a_n-1)\eta_E)}$ (Eq 11.2)
Deleterious mutations tend to be recent (external).</li>
  <li><strong>Fay and Wu’s $H$ (2000):</strong> Compares intermediate-frequency variants ($\hat{\theta}<em>\pi$) with high-frequency derived variants ($\hat{\theta}_H$).
$\hat{\theta}_H = \sum</em>{i=1}^{n-1} \frac{2s_i i^2}{n(n-1)}$ (Eq 11.3)
$H = \hat{\theta}_\pi - \hat{\theta}_H$.
Negative $H$ indicates excess of high-frequency derived variants, a signature of <strong>genetic hitchhiking</strong> (selective sweep of a linked beneficial mutation carrying neutral variants to high frequency).</li>
</ul>

<h3 id="1124-mcdonald-kreitman-mk-test-and-estimation-of-selective-strength">11.2.4 McDonald-Kreitman (MK) Test and Estimation of Selective Strength</h3>
<ul>
  <li><strong>Neutral Theory Prediction:</strong> Ratio of nonsynonymous to synonymous polymorphisms within a species should equal ratio of nonsynonymous to synonymous fixed differences between species.</li>
  <li><strong>MK Test (1991):</strong> Uses a $2 \times 2$ contingency table (Table 11.1):
| Type of Change       | Fixed (Between Spp) | Polymorphic (Within Sp) |
|———————-|———————|————————-|
| Replacement ($d_N$)  | $F_N$               | $P_N$                   |
| Silent ($d_S$)       | $F_S$               | $P_S$                   |
Test for independence (e.g., Fisher’s exact test).</li>
  <li><strong>Interpretation:</strong>
    <ul>
      <li>Significant excess of $F_N$ relative to $P_N$ (i.e., $F_N/F_S &gt; P_N/P_S$) suggests positive selection driving replacement fixations.</li>
      <li>Significant excess of $P_N$ relative to $F_N$ suggests slightly deleterious replacement mutations segregating within species but removed before fixation.</li>
    </ul>
  </li>
  <li><strong>Poisson Random Field (PRF) Theory (Sawyer &amp; Hartl 1992):</strong> Extends MK test to estimate parameters of selection strength, assuming free recombination within gene. Uses full SFS. Powerful if multiple loci analyzed.</li>
</ul>

<h3 id="1125-hudson-kreitman-aquade-hka-test">11.2.5 Hudson-Kreitman-Aquade (HKA) Test</h3>
<ul>
  <li><strong>Hudson et al. (1987):</strong> Tests neutral prediction that polymorphism within species and divergence between species are correlated across multiple unlinked loci.</li>
  <li>Loci with high mutation rates should show high polymorphism AND high divergence.</li>
  <li>Goodness-of-fit test statistic $X^2$ based on deviations from expected values for $S_A^i, S_B^i, D_i$ (polymorphisms in spp A, B; divergence) at locus $i$. (Eq 11.4)</li>
  <li>Null model has $L+2$ parameters. $df = 2L-2$.</li>
</ul>

<h2 id="113-lineages-undergoing-adaptive-evolution-omega-on-branches">11.3 Lineages Undergoing Adaptive Evolution ($\omega$ on Branches)</h2>

<p>Phylogenetic methods to detect positive selection on specific branches using $d_N/d_S = \omega$.</p>

<h3 id="1131-heuristic-methods">11.3.1 Heuristic Methods</h3>
<ul>
  <li>Early methods, often based on pairwise comparisons or ancestral sequence reconstruction (ASR).</li>
  <li><strong>Messier &amp; Stewart (1997):</strong> Lysozyme evolution. Used parsimony ASR, calculated $d_N, d_S$ per branch. Identified primate colobine ancestral branch with $\omega &gt; 1$.</li>
  <li><strong>Zhang et al. (1997):</strong> Fisher’s exact test on counts of S/N sites and S/N differences per branch (from ASR). Addresses small sample size concerns of normal approximation for $d_N-d_S$.</li>
  <li><strong>Zhang et al. (1998):</strong> Pairwise $d_N, d_S$. Fit synonymous ($b_S$) and nonsynonymous ($b_N$) branch lengths separately using least squares. Test $b_N &gt; b_S$ for specific branches. Avoids ASR errors.</li>
  <li><strong>Limitations:</strong> ASR errors, failure to correct for multiple hits (in counting methods), assumptions of normal approximation.</li>
</ul>

<h3 id="1132-likelihood-method">11.3.2 Likelihood Method</h3>
<ul>
  <li>Analyze all sequences jointly on a phylogeny using codon substitution models (§2.4). Averages over ancestral states.</li>
  <li><strong>Branch Models (Yang 1998a):</strong> Allow $\omega$ to vary among branches.
    <ul>
      <li><strong>One-ratio model:</strong> Single $\omega$ for all branches.</li>
      <li><strong>Free-ratio model:</strong> Independent $\omega$ for each branch. Too many parameters for large trees.</li>
      <li><strong>Two-ratio (or few-ratio) model:</strong> Assign branches <em>a priori</em> to foreground (test) and background categories, each with its own $\omega$.
        <ul>
          <li>LRT compares one-ratio model ($H_0: \omega_0=\omega_1$) vs. two-ratio model ($H_1: \omega_0 \neq \omega_1$). $df=1$.</li>
          <li>Can also test $H_0: \omega_1=1$ vs. $H_1: \omega_1 &gt; 1$ (fixed $\omega_0$).</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Likelihood Calculation:</strong> Similar to standard phylogenetic likelihood (§4.2), but different $Q$ matrices (due to different $\omega$’s) used for transition probabilities on different branches.
    <ul>
      <li>Example (Fig 11.2): ASPM gene. Model 0 (one $\omega$). Model 1 (three $\omega$’s: $\omega_H, \omega_C, \omega_O$).</li>
    </ul>
  </li>
  <li><strong>Caveats:</strong>
    <ol>
      <li><strong>A Priori Specification:</strong> Foreground lineages must be specified <em>before</em> seeing the data (or results from an initial analysis). Post-hoc testing inflates Type I error.</li>
      <li><strong>$\omega &gt; 1$ is for Positive Selection:</strong> Variation in $\omega$ alone (e.g., foreground $\omega$ &gt; background $\omega$, but both &lt; 1) is not sufficient evidence for positive selection, could be relaxation of constraint. Need to show foreground $\omega &gt; 1$.</li>
    </ol>
  </li>
</ul>

<h2 id="114-amino-acid-sites-undergoing-adaptive-evolution-omega-at-sites">11.4 Amino Acid Sites Undergoing Adaptive Evolution ($\omega$ at Sites)</h2>

<p>Models allowing $\omega$ to vary among amino acid sites.</p>

<h3 id="1141-three-strategies">11.4.1 Three Strategies</h3>
<ol>
  <li><strong>Focus on Functionally Important Sites:</strong> Use external (e.g., structural) information to identify candidate sites <em>a priori</em>. Assign different $\omega$ to these sites vs. others. Test if $\omega_{candidate} &gt; 1$. (e.g., Hughes &amp; Nei 1988 MHC ARS analysis).</li>
  <li><strong>Site-by-Site $\omega$ Estimation:</strong> Estimate $\omega$ for each site individually.
    <ul>
      <li>Fitch et al. (1997), Suzuki &amp; Gojobori (1999): Parsimony ASR, count S/N changes per site.</li>
      <li>Massingham &amp; Goldman (2005): Site-wise LRT (SLR test). Model with per-site $\omega$ vs. $\omega=1$.</li>
      <li><strong>Problem:</strong> Infinite parameters. Bayesian/EB approaches better.</li>
    </ul>
  </li>
  <li><strong>Statistical Distribution for $\omega$ Across Sites (Random-Site Models):</strong> Assume $\omega_h$ at site $h$ is a random variable from a distribution $f(\omega)$. Test if this distribution includes a class with $\omega &gt; 1$. (Nielsen &amp; Yang 1998; Yang et al. 2000).</li>
</ol>

<h3 id="1142-likelihood-ratio-test-of-positive-selection-under-random-site-models">11.4.2 Likelihood Ratio Test of Positive Selection under Random-Site Models</h3>
<ul>
  <li>Probability of data at site $h$: $f(x_h) = \int_0^\infty f(\omega) f(x_h\vert \omega) d\omega \approx \sum_{k=1}^K p_k f(x_h\vert \omega_k)$ (Eq 11.7)
(Average likelihood over the distribution of $\omega$). Discrete approximation used.</li>
  <li>Synonymous rate assumed constant across sites; only $d_N$ varies.</li>
  <li>Correct scaling of $Q$ matrices for different $\omega_k$ is important.</li>
  <li><strong>Commonly Used Model Pairs for LRT (Table 11.2):</strong>
    <ul>
      <li><strong>M1a (neutral) vs. M2a (selection):</strong>
        <ul>
          <li>M1a: Two site classes $p_0$ (proportion) with $\omega_0 \in (0,1)$ and $p_1=1-p_0$ with $\omega_1=1$. (2 params: $p_0, \omega_0$).</li>
          <li>M2a: Three site classes $p_0$ with $\omega_0 \in (0,1)$, $p_1$ with $\omega_1=1$, and $p_2=1-p_0-p_1$ with $\omega_2 \ge 1$. (4 params: $p_0, p_1, \omega_0, \omega_2$).</li>
          <li>LRT: $2\Delta l$. Null distribution is complex (boundary issues), $\chi^2_2$ often too conservative.</li>
        </ul>
      </li>
      <li><strong>M7 (beta) vs. M8 (beta &amp; $\omega_s$):</strong> (Preferred test)
        <ul>
          <li>M7: $\omega$ follows a beta distribution $B(p,q)$ restricted to $(0,1)$. (2 params: $p,q$). (Fig 11.3 shows beta shapes).</li>
          <li>M8: Mixture of beta $B(p,q)$ (proportion $p_0$) and an additional class $\omega_s \ge 1$ (proportion $p_1=1-p_0$). (4 params: $p_0, p, q, \omega_s$).</li>
          <li>LRT: $2\Delta l \sim \chi^2_2$ (again, often conservative).</li>
        </ul>
      </li>
      <li>M3 (discrete) vs. M0 (one-ratio): Tests variability in $\omega$, not specifically positive selection.</li>
    </ul>
  </li>
</ul>

<h3 id="1143-identification-of-sites-under-positive-selection">11.4.3 Identification of Sites Under Positive Selection</h3>
<ul>
  <li>If LRT (e.g., M7 vs M8) is significant, identify sites with high posterior probability of being in the $\omega_s &gt; 1$ class.</li>
  <li><strong>Naïve Empirical Bayes (NEB):</strong> Use MLEs of parameters in $f(\omega_k \vert  x_h) = \frac{p_k f(x_h\vert \omega_k)}{\sum_j p_j f(x_h\vert \omega_j)}$. (Eq 11.9)</li>
  <li><strong>Bayes Empirical Bayes (BEB) (Yang et al. 2005):</strong> Accounts for uncertainty in MLEs of parameters of $f(\omega)$ by integrating over their prior. More reliable for smaller datasets.</li>
  <li>Hierarchical full Bayesian (Huelsenbeck &amp; Dyer 2004) also possible.</li>
</ul>

<h3 id="1144-positive-selection-at-the-human-mhc">11.4.4 Positive Selection at the Human MHC</h3>
<ul>
  <li>Analysis of 192 human MHC alleles (Yang &amp; Swanson 2002) (Table 11.3).</li>
  <li>Tree estimated by NJ. Branch lengths from M0 (one-ratio $\hat{\omega}=0.612$).</li>
  <li>M2a: suggests 8.4% sites with $\hat{\omega}_2=5.389$. M8: suggests ~8.5% sites with $\hat{\omega}_s=5.079$.</li>
  <li>LRTs (M1a vs M2a, M7 vs M8) highly significant.</li>
  <li>Posterior probabilities $P(\omega_k \vert  x_h)$ identify sites likely under positive selection (Fig 11.4).</li>
  <li>Most identified sites fall in Antigen Recognition Site (ARS) groove (Fig 11.5).</li>
</ul>

<h2 id="115-adaptive-evolution-affecting-particular-sites-and-lineages">11.5 Adaptive Evolution Affecting Particular Sites and Lineages</h2>

<h3 id="1151-branch-site-test-of-positive-selection">11.5.1 Branch-Site Test of Positive Selection</h3>
<ul>
  <li>Detects positive selection at specific sites along specific (foreground) lineages. (Yang &amp; Nielsen 2002; Yang et al. 2005; Zhang et al. 2005).</li>
  <li><strong>Model A (Alternative Hypothesis, Table 11.4):</strong>
    <ul>
      <li>Background lineages: Sites are class 0 ($0 &lt; \omega_0 &lt; 1$) or class 1 ($\omega_1 = 1$).</li>
      <li>Foreground lineages: Some sites from class 0 and 1 may switch to class 2a or 2b, both with $\omega_2 \ge 1$.</li>
      <li>Proportions $p_0, p_1$ for background site classes. Parameters: $p_0, p_1, \omega_0, \omega_2$.</li>
    </ul>
  </li>
  <li><strong>Null Hypothesis:</strong> Model A with $\omega_2=1$ fixed. (3 params: $p_0, p_1, \omega_0$).</li>
  <li><strong>LRT:</strong> $2\Delta l$. Null distribution is 50:50 mixture of 0 and $\chi^2_1$.</li>
  <li>More power than branch test or site test alone. Requires <em>a priori</em> specification of foreground branches. NEB/BEB can identify sites.</li>
</ul>

<h3 id="1152-other-similar-models">11.5.2 Other Similar Models</h3>
<ul>
  <li><strong>Clade Models (Forsberg &amp; Christiansen 2003; Bielawski &amp; Yang 2004):</strong>
    <ul>
      <li>Branches <em>a priori</em> divided into clades. $\omega$ varies among clades (and site classes).</li>
      <li>Model C (Table 11.5): Site classes 0 ($\omega_0&lt;1$) and 1 ($\omega_1=1$) common to all clades. Site class 2 has different $\omega$ values for different clades ($\omega_{2,clade1}, \omega_{2,clade2}, \dots$).</li>
    </ul>
  </li>
  <li><strong>Switching Model (Guindon et al. 2004):</strong> $\omega$ at a site can switch between values over time (along tree) via a hidden Markov chain. Does not require <em>a priori</em> partitioning of branches.</li>
</ul>

<h3 id="1153-adaptive-evolution-in-angiosperm-phytochromes">11.5.3 Adaptive Evolution in Angiosperm Phytochromes</h3>
<ul>
  <li>Example of branch-site test (Alba et al. 2000 data, Fig 11.6).</li>
  <li>Test for positive selection on branch separating phytochrome A and C/F subfamilies (gene duplication).</li>
  <li>One-ratio model M0: $\hat{\omega}=0.089$.</li>
  <li>Branch model (2 ratios): $\hat{\omega}<em>{foreground}=0.016, \hat{\omega}</em>{background}=0.090$. Not significantly better than M0. No evidence of branch-wide $\omega &gt; 1$.</li>
  <li>Branch-site test (Model A vs. Model A with $\omega_2=1$): $2\Delta l = 19.88$, $P \approx 4 \times 10^{-6}$. Strong evidence for positive selection. (Table 11.6)</li>
  <li>Suggests ~11% sites evolved under positive selection ($\hat{\omega}_2=131.1$) along the foreground branch. BEB identifies 27 such sites.</li>
</ul>

<h2 id="116-assumptions-limitations-and-comparisons">11.6 Assumptions, Limitations, and Comparisons</h2>

<h3 id="1161-assumptions-and-limitations-of-current-methods">11.6.1 Assumptions and Limitations of Current Methods</h3>
<ol>
  <li><strong>Substitution Models, Not Mutation-Selection Explicitly:</strong> $\omega$ contrasts substitution rates. Less sensitive to neutral evolution details at silent sites. Not ideal for detecting selection on silent sites.</li>
  <li><strong>Simplistic Codon Models:</strong> Assume same $\omega$ for all AA changes. Real AA substitution patterns are complex. Incorporating AA properties improves fit but not dramatically; defining positive selection is harder.</li>
  <li><strong>Conservative Tests:</strong> Branch models (average $\omega$ over sites) and site models (average $\omega$ over branches) have low power. Branch-site tests are better for episodic selection.</li>
  <li><strong>Synonymous Rate Variation:</strong> Most site models assume constant $d_S$. Extensions allowing $d_S$ to vary exist but impact on $d_N$ inference is debatable. BEB with M2a/M8 robust.</li>
  <li><strong>Recombination:</strong> Current models assume one tree. Intragenic recombination can mislead LRTs (false positives). Methods for simultaneous detection of recombination and selection are needed.</li>
  <li><strong>Sequence Divergence Levels:</strong>
    <ul>
      <li>Too similar: Little information.</li>
      <li>Too divergent: Saturation of $d_S$, alignment errors, different codon usage. These can all lead to false positives. Alignment quality is critical.</li>
    </ul>
  </li>
</ol>

<h3 id="1162-comparison-of-methods-for-detecting-positive-selection">11.6.2 Comparison of Methods for Detecting Positive Selection</h3>
<ul>
  <li><strong>Phylogenetic $\omega$-based tests vs. Population Genetic Neutrality Tests:</strong>
    <ol>
      <li><strong>Data Type:</strong> $\omega$ tests need divergent sequences (between species). Neutrality tests for population samples or closely related species (infinite-sites model).</li>
      <li><strong>Evidence Strength:</strong> $\omega &gt; 1$ is strong evidence for positive selection. Neutrality test rejection is open to multiple interpretations (selection, demography, linkage).</li>
      <li><strong>Statistical Power:</strong> $\omega$ tests (on species data) often more powerful for detecting repeated selective sweeps than neutrality tests (on population data), even at low divergence (Zhai et al. 2009). Due to transient nature of sweeps.</li>
    </ol>
  </li>
</ul>

<h2 id="117-adaptively-evolving-genes">11.7 Adaptively Evolving Genes</h2>
<p>Categories of genes often found under positive selection using $\omega$ tests:</p>
<ol>
  <li><strong>Host-Pathogen Arms Race:</strong> Host defense/immunity genes (MHC, CD45, plant R-genes, TRIM5$\alpha$). Pathogen surface/capsid proteins, toxins. (Red Queen hypothesis).</li>
  <li><strong>Sexual Reproduction:</strong> Proteins involved in sperm-egg recognition, male/female reproduction. (Sexual conflict, speciation).</li>
  <li><strong>Gene Duplication &amp; Neofunctionalization:</strong> One copy maintains original function, other acquires new function under positive selection (DAZ, chorionic gonadotropin, RNases).
    <ul>
      <li><strong>Experimental Verification:</strong> Statistical tests generate hypotheses. Functional assays (site-directed mutagenesis, chimeric proteins) needed to confirm adaptive role of specific AA changes (e.g., TRIM5$\alpha$ patch, AGPase allostery).</li>
      <li><strong>Regulatory vs. Structural Genes:</strong> Debate on primary drivers of adaptation. Codon models primarily target structural (protein-coding) genes. Both are important.</li>
    </ul>
  </li>
</ol>

<h1 id="chapter-12-simulating-molecular-evolution">Chapter 12: Simulating Molecular Evolution</h1>

<p>This chapter provides an introduction to computer simulation techniques, also known as stochastic simulation or Monte Carlo simulation, as applied to molecular evolution.</p>

<h2 id="121-introduction">12.1 Introduction</h2>
<ul>
  <li><strong>Definition:</strong> Computer simulation is a virtual experiment mimicking a physical/biological process on a computer to study its properties. It’s particularly useful for complex systems intractable analytically. Random numbers are a key feature.</li>
  <li><strong>Uses of Simulation:</strong>
    <ol>
      <li><strong>Validation:</strong> Validating theories or program implementations when analytical methods are complex.</li>
      <li><strong>Method Comparison:</strong> Comparing different analytical methods, especially for robustness when underlying assumptions are violated.</li>
      <li><strong>Education:</strong> Gaining intuition about a system by observing its behavior under a model.</li>
      <li><strong>Basis of Modern Statistics:</strong> Forms the foundation for computation-intensive methods like bootstrapping, importance sampling, and Markov chain Monte Carlo (MCMC).</li>
    </ol>
  </li>
  <li><strong>Caveats:</strong>
    <ul>
      <li>Simulation is experimentation; requires careful design and analysis.</li>
      <li><strong>Limitation:</strong> Only a small portion of parameter space can typically be examined. Behavior in unexplored regions might differ. Avoid over-generalization.</li>
      <li>Analytical results are generally superior as they apply to all parameter values.</li>
    </ul>
  </li>
  <li><strong>Chapter Goal:</strong> Introduce basic simulation techniques.</li>
</ul>

<h2 id="122-random-number-generator">12.2 Random Number Generator</h2>
<ul>
  <li><strong>Random Numbers:</strong> Random variables drawn from the uniform distribution $U(0,1)$. Fundamental for computer simulation.
    <ul>
      <li>Used to simulate random events with given probabilities (Fig 12.1a).</li>
      <li>Basis for generating random variables from other distributions (Fig 12.1b).</li>
    </ul>
  </li>
  <li><strong>Hardware Random Number Generators:</strong>
    <ul>
      <li>Use “unpredictable” physical processes (e.g., coin flips, quantum phenomena like photonic emission).</li>
      <li>Too slow for general computer simulation. Used for cryptographic keys or seeding pseudo-random generators.</li>
    </ul>
  </li>
  <li><strong>Pseudo-Random Number Generator (PRNG):</strong>
    <ul>
      <li>A mathematical algorithm producing a sequence of numbers that <em>appear</em> random but are entirely deterministic given an initial “seed”.</li>
      <li><strong>Multiplication-Congruential Method:</strong> A common PRNG.
        <ul>
          <li>$A_i = c A_{i-1} \pmod M$ (Eq 12.1)</li>
          <li>$u_i = A_i / M$ (Eq 12.2)</li>
          <li>$A_0$: seed (initial integer value).</li>
          <li>$c$: multiplier (integer).</li>
          <li>$M$: modulus (integer, often $2^d$ where $d$ is number of bits in an integer type, e.g., $2^{31}, 2^{32}, 2^{64}$).</li>
          <li>$A_i$ is the remainder when $c A_{i-1}$ is divided by $M$.</li>
          <li>$u_i$ is the pseudo-random number in $[0,1)$.</li>
          <li>The sequence $A_i$ (and thus $u_i$) is periodic. The goal is to choose $M, c, A_0$ to make the period very long and the sequence statistically “random-like.”</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Assessing PRNG Quality:</strong>
    <ul>
      <li>Generated numbers should be indistinguishable from true $U(0,1)$ draws.</li>
      <li>Statistical tests for mean ($1/2$), variance ($1/12$), lack of autocorrelation, etc.</li>
      <li>It’s generally not advisable to design one’s own PRNG; use well-tested library functions (e.g., <code class="language-plaintext highlighter-rouge">rand()</code> in C/Perl, though quality varies).</li>
    </ul>
  </li>
  <li><strong>Seeding PRNGs:</strong>
    <ul>
      <li>Using the same seed always produces the same sequence (useful for debugging).</li>
      <li>For multiple independent simulation replicates, different seeds are needed.</li>
      <li><strong>Wall-clock time:</strong> <code class="language-plaintext highlighter-rouge">time()</code> function can provide a seed. Unsafe for parallel jobs starting simultaneously (might get same seed).</li>
      <li><strong>/dev/urandom (UNIX):</strong> A file providing nearly true random numbers from environmental noise. Good for seeding PRNGs robustly.</li>
    </ul>
  </li>
</ul>

<h2 id="123-generation-of-discrete-random-variables">12.3 Generation of Discrete Random Variables</h2>

<h3 id="1231-inversion-method-for-sampling-from-a-general-discrete-distribution">12.3.1 Inversion Method for Sampling from a General Discrete Distribution</h3>
<ul>
  <li><strong>Setup:</strong> Discrete random variable $X$ takes values $x_1, x_2, \dots$ with probabilities $p_i = P(X=x_i)$, where $\sum p_i = 1$. (Eq 12.3)</li>
  <li><strong>Cumulative Distribution Function (CDF):</strong> $F_i = P(X \le x_i) = p_1 + \dots + p_i$. (Eq 12.4)</li>
  <li><strong>Inversion Method:</strong>
    <ol>
      <li>Generate $u \sim U(0,1)$.</li>
      <li>Find $i$ such that $F_{i-1} &lt; u \le F_i$ (where $F_0=0$).</li>
      <li>Set $X = x_i$.</li>
    </ol>
  </li>
  <li>This “inverts” the CDF: $X = F^{-1}(u)$.</li>
  <li><strong>Efficiency:</strong> Number of comparisons depends on ordering of $p_i$. For $k$ categories, on average, it takes $\sum_{j=1}^k j p_j’$ comparisons if $p_j’$ is prob of $j^{th}$ category in the <em>ordered list</em>. Best to order categories from highest to lowest $p_i$.
    <ul>
      <li>Example: Nucleotides T,C,A,G with probs 0.1, 0.2, 0.3, 0.4.
        <ul>
          <li>Order T,C,A,G: average 2.6 comparisons.</li>
          <li>Order G,A,C,T: average 1.9 comparisons.</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h3 id="1232-the-alias-method-for-sampling-from-a-discrete-distribution">12.3.2 The Alias Method for Sampling from a Discrete Distribution</h3>
<ul>
  <li>Efficient for many categories and many samples, after an initial setup cost.</li>
  <li>Requires only one comparison per random variable generated, irrespective of number of categories $n$.</li>
  <li><strong>Basis:</strong> Any discrete distribution $P = (p_1, \dots, p_n)$ can be expressed as an equiprobable mixture of $n$ two-point distributions $q^{(m)}$:
$p_i = \frac{1}{n} \sum_{m=1}^n q_i^{(m)}$, for all $i$. (Eq 12.5)
Each $q^{(m)}$ is non-zero for at most two values of $i$.</li>
  <li><strong>Simulation:</strong>
    <ol>
      <li>(Setup) Construct the $n$ distributions $q^{(m)}$ (Table 12.1 shows an example).</li>
      <li>Generate $u \sim U(0,1)$, set $m = \lfloor nu \rfloor + 1$.</li>
      <li>Sample from $q^{(m)}$ (which requires one comparison as it’s a two-point distribution).</li>
    </ol>
  </li>
  <li>Useful for sampling from multinomial distribution.</li>
</ul>

<h3 id="1233-discrete-uniform-distribution">12.3.3 Discrete Uniform Distribution</h3>
<ul>
  <li>Takes $n$ possible values, each with probability $1/n$.</li>
  <li>To sample $x \in {1, 2, \dots, n}$: Generate $u \sim U(0,1)$, set $x = \lfloor nu \rfloor + 1$.</li>
  <li>Used for:
    <ul>
      <li>Generating root sequence under JC69/K80 (equal base frequencies).</li>
      <li>Nonparametric bootstrap (sampling sites with replacement from an alignment of length $l$: pick site index $\lfloor lu \rfloor + 1$).</li>
      <li>Sampling a random pair $(i,j)$ from $1, \dots, n$.</li>
      <li>Generating random permutations.</li>
    </ul>
  </li>
</ul>

<h3 id="1234-binomial-distribution">12.3.4 Binomial Distribution</h3>
<ul>
  <li>$X \sim \text{bino}(n,p)$: number of successes in $n$ independent trials, probability of success $p$.</li>
  <li><strong>Simulation Method 1 (Direct):</strong> Simulate $n$ Bernoulli trials. For each, generate $u \sim U(0,1)$; if $u&lt;p$, count success. Sum successes.</li>
  <li><strong>Simulation Method 2 (Inversion):</strong> Calculate probabilities $p_x = \binom{n}{x} p^x (1-p)^{n-x}$ for $x=0, \dots, n$. (Eq 12.6). Then sample from this $(n+1)$-category discrete distribution using inversion. More efficient if many samples needed from same binomial.</li>
</ul>

<h3 id="1235-the-multinomial-distribution">12.3.5 The Multinomial Distribution</h3>
<ul>
  <li>Generalization of binomial: $k$ possible outcomes per trial, probabilities $p_1, \dots, p_k$.</li>
  <li>$MN(n; p_1, \dots, p_k)$: counts $n_1, \dots, n_k$ for each outcome in $n$ trials. $\sum n_i = n$.</li>
  <li><strong>Simulation:</strong> Sample $n$ times from the $k$-category discrete distribution $(p_1, \dots, p_k)$, and count occurrences of each category. Alias method efficient if $k$ large.</li>
  <li>Sequence data under i.i.d. models follow a multinomial distribution (site patterns are categories).</li>
</ul>

<h3 id="1236-the-poisson-distribution">12.3.6 The Poisson Distribution</h3>
<ul>
  <li>$X \sim \text{Poisson}(\lambda)$ if $P(X=x) = e^{-\lambda} \lambda^x / x!$, for $x=0,1,\dots$. (Eq 12.7)</li>
  <li>Mean $E(X)=\lambda$, Variance $V(X)=\lambda$.</li>
  <li><strong>Algorithm 12.1 (Inversion Method for Poisson):</strong>
    <ol>
      <li>Generate $u \sim U(0,1)$.</li>
      <li>Set $x=0$, $F = p_0 = e^{-\lambda}$.</li>
      <li>If $u &lt; F$, set $X=x$, stop.</li>
      <li>$x \to x+1$. Update $p_x = p_{x-1} \cdot \lambda/x$. $F \to F+p_x$. (Using $p_{k+1} = p_k \lambda/(k+1)$ and $F_x = \sum_{j=0}^x p_j$, so $F_{x+1}=F_x+p_{x+1}$) (Eq 12.8)</li>
      <li>Go to step 3.
        <ul>
          <li>Number of comparisons $1+X$. Can be slow if $\lambda$ is large. Reordering values or pre-calculating CDF can help for multiple samples.</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h3 id="1237-the-composition-method-for-mixture-distributions">12.3.7 The Composition Method for Mixture Distributions</h3>
<ul>
  <li>If $X$ has a mixture distribution $f = \sum_{i=1}^m p_i f_i$. (Eq 12.9)</li>
  <li><strong>Composition Method:</strong>
    <ol>
      <li>Sample a component index $i$ from the discrete distribution $(p_1, \dots, p_m)$.</li>
      <li>Sample $X$ from the chosen component distribution $f_i$.</li>
    </ol>
  </li>
  <li>Example: I+$\Gamma$ model. Sample if site is invariable ($p_0$) or gamma-distributed ($1-p_0$). If gamma, then sample from gamma.</li>
</ul>

<h2 id="124-generation-of-continuous-random-variables">12.4 Generation of Continuous Random Variables</h2>

<h3 id="1241-the-inversion-method">12.4.1 The Inversion Method</h3>
<ul>
  <li>If $X$ has CDF $F(x)$, then $U=F(X) \sim U(0,1)$.</li>
  <li>If $F^{-1}(u)$ is analytically available:
    <ol>
      <li>Generate $u \sim U(0,1)$.</li>
      <li>Set $X = F^{-1}(u)$.</li>
    </ol>
  </li>
  <li><strong>Examples:</strong>
    <ol>
      <li><strong>Uniform $X \sim U(a,b)$:</strong> $F(x)=(x-a)/(b-a)$. $F^{-1}(u) = a + u(b-a)$.</li>
      <li><strong>Exponential $X \sim \text{Exp}(\text{mean}=\theta)$:</strong> $F(x)=1-e^{-x/\theta}$. $F^{-1}(u) = -\theta \log(1-u)$. Since $1-u \sim U(0,1)$ if $u \sim U(0,1)$, can use $X = -\theta \log(u)$.</li>
    </ol>
  </li>
</ul>

<h3 id="1242-the-transformation-method">12.4.2 The Transformation Method</h3>
<ul>
  <li>If $X=h(Y)$ and $Y$ is easier to simulate, simulate $Y$ then transform. Inversion is a special case ($Y \sim U(0,1), h=F^{-1}$).</li>
  <li><strong>Normal $N(\mu, \sigma^2)$:</strong> If $Z \sim N(0,1)$, then $X = \mu + Z\sigma \sim N(\mu, \sigma^2)$.</li>
  <li><strong>Gamma $G(n,\beta)$ for integer $n$:</strong> If $Y_j \sim \text{Exp}(1)$ i.i.d., then $X = \frac{1}{\beta}\sum_{j=1}^n Y_j \sim G(n,\beta)$. (Eq 12.10)</li>
</ul>

<h3 id="1243-the-rejection-method">12.4.3 The Rejection Method</h3>
<ul>
  <li>Used when $F^{-1}$ is intractable.</li>
  <li><strong>Simple Rejection (from Uniform Envelope, Fig 12.2a):</strong>
    <ul>
      <li>Assume $f(x)$ is defined on $(a,b)$ and $f(x) \le M$.</li>
      <li><strong>Algorithm 12.2:</strong>
        <ol>
          <li>Generate $x^{\ast} \sim U(a,b)$ and $y^{\ast} \sim U(0,M)$. This samples a point $(x^{\ast}, y^{\ast})$ uniformly from rectangle $[a,b] \times [0,M]$.</li>
          <li>If $y^{\ast} &lt; f(x^{\ast})$ (point is under curve $f(x)$), accept $X=x^{\ast}$. Otherwise, reject and go to Step 1.</li>
        </ol>
      </li>
    </ul>
  </li>
  <li><strong>General Rejection (using Envelope Function $g(x)$, Fig 12.2b):</strong>
    <ul>
      <li>Need a “proposal” or “envelope” density $g(x)$ from which it’s easy to sample.</li>
      <li>Need a constant $M$ such that $f(x)/g(x) \le M$ for all $x$ (i.e., $M g(x)$ encloses $f(x)$). (Eq 12.11)</li>
      <li><strong>Algorithm 12.3:</strong>
        <ol>
          <li>Generate $x^{\ast} \sim g(x)$. Generate $u \sim U(0,1)$. Set $y^{\ast} = u M g(x^{\ast})$. (This samples $(x^{\ast}, y^{\ast})$ from under $M g(x)$).</li>
          <li>If $y^{\ast} &lt; f(x^{\ast})$ (or equivalently, if $u &lt; f(x^{\ast})/(M g(x^{\ast}))$), accept $X=x^{\ast}$. Otherwise, reject and go to Step 1.</li>
        </ol>
      </li>
      <li><strong>Acceptance Probability:</strong> $P_{accept} = 1/M$. (Eq 12.12). Want $M$ close to 1 (tight envelope).</li>
    </ul>
  </li>
  <li><strong>Example: Generating $N(0,1)$ using Exponential Envelope:</strong>
    <ul>
      <li>Target $f(x) = \frac{2}{\sqrt{2\pi}} e^{-x^2/2}$ for $x \ge 0$ (absolute value of normal).</li>
      <li>Proposal $g(x) = e^{-x}$ for $x \ge 0$ (Exponential with mean 1).</li>
      <li>$M = \sqrt{2e/\pi} \approx 1.3155$. $P_{accept} = 1/M \approx 0.76$.</li>
      <li><strong>Algorithm 12.4 (Standard Normal):</strong>
        <ol>
          <li>Generate $x^{\ast}$ from Exp(1) using $x^{\ast} = -\log u_1$. Generate $u_2 \sim U(0,1)$.</li>
          <li>If $u_2 &lt; e^{-(x^{\ast}-1)^2/2}$ (equivalent to $y^{\ast} &lt; f(x^{\ast})$ using Eq 12.15), accept $x^{\ast}$. Else go to 1.</li>
          <li>Generate $u_3 \sim U(0,1)$. If $u_3 &lt; 0.5$, set $X = -x^{\ast}$. Else $X=x^{\ast}$.</li>
        </ol>
      </li>
    </ul>
  </li>
</ul>

<h3 id="1244-generation-of-a-standard-normal-variate-using-the-polar-method">12.4.4 Generation of a Standard Normal Variate using the Polar Method</h3>
<ul>
  <li><strong>Box-Muller Transform (Algorithm 12.5):</strong>
    <ul>
      <li>Based on: If $X,Y \sim N(0,1)$ i.i.d., their polar coordinates $(R, \Theta)$ have $R^2 = X^2+Y^2 \sim \text{Exp}(\text{mean}=2)$ and $\Theta \sim U(0, 2\pi)$, independently. (Eq 12.18, 12.19)
        <ol>
          <li>Generate $u_1, u_2 \sim U(0,1)$.</li>
          <li>Set $r^2 = -2\log u_1$ (Exponential with mean 2). Set $\theta = 2\pi u_2$.</li>
          <li>$x = \sqrt{r^2} \cos\theta = \sqrt{-2\log u_1} \cos(2\pi u_2)$.
$y = \sqrt{r^2} \sin\theta = \sqrt{-2\log u_1} \sin(2\pi u_2)$. (Eq 12.20)</li>
        </ol>
      </li>
      <li>Generates two $N(0,1)$ variates. Sine/cosine are expensive.</li>
    </ul>
  </li>
  <li><strong>Polar Method (Marsaglia, Algorithm 12.6):</strong> Avoids sine/cosine.
    <ol>
      <li>Generate $(v_1, v_2)$ uniformly within the unit circle $v_1^2+v_2^2 \le 1$.
a. Generate $u_1, u_2 \sim U(0,1)$. Set $v_1 = 2u_1-1, v_2 = 2u_2-1$. (Uniform in $[-1,1]^2$ square).
b. If $s = v_1^2+v_2^2 &gt; 1$, reject $(v_1,v_2)$ and go to 1a. (Now $(v_1,v_2)$ is uniform in unit circle).</li>
      <li>$x = \sqrt{-2\log s/s} \cdot v_1$.
$y = \sqrt{-2\log s/s} \cdot v_2$.
        <ul>
          <li>Uses $s=R^2 \sim U(0,1)$ and $\cos\Theta = v_1/\sqrt{s}, \sin\Theta = v_2/\sqrt{s}$. (Eq 12.21)</li>
          <li>Rejection in step 1c has probability $1-\pi/4 \approx 0.215$. Average 1.273 iterations for step 1.</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h3 id="1245-gamma-beta-and-dirichlet-variables">12.4.5 Gamma, Beta, and Dirichlet Variables</h3>
<ul>
  <li><strong>Gamma $G(\alpha, \beta)$:</strong> Density $f(x; \alpha, \beta) = \frac{\beta^\alpha}{\Gamma(\alpha)} e^{-\beta x} x^{\alpha-1}$. (Eq 12.22)
    <ul>
      <li>Specialized algorithms exist (e.g., Ziggurat).</li>
    </ul>
  </li>
  <li><strong>Beta $\text{beta}(p,q)$:</strong> Density $f(x; p,q) = \frac{1}{B(p,q)} x^{p-1}(1-x)^{q-1}$. (Eq 12.23)
    <ul>
      <li>Generate $Y_1 \sim G(p,1)$ and $Y_2 \sim G(q,1)$. Then $X = Y_1/(Y_1+Y_2) \sim \text{beta}(p,q)$. (Eq 12.24)</li>
    </ul>
  </li>
  <li><strong>Dirichlet $\text{Dir}(\alpha_1, \dots, \alpha_K)$:</strong> Density $f(x; \alpha) = \frac{\Gamma(\sum \alpha_i)}{\prod \Gamma(\alpha_i)} \prod x_i^{\alpha_i-1}$. (Eq 12.25)
    <ul>
      <li>Generate $Y_i \sim G(\alpha_i, 1)$ independently for $i=1, \dots, K$.</li>
      <li>Set $X_i = Y_i / \sum_j Y_j$. Then $(X_1, \dots, X_K) \sim \text{Dir}(\alpha_1, \dots, \alpha_K)$.</li>
    </ul>
  </li>
  <li>R functions: <code class="language-plaintext highlighter-rouge">runif, rnorm, rgamma, rbeta</code>.</li>
</ul>

<h2 id="125-simulation-of-markov-processes">12.5 Simulation of Markov Processes</h2>

<h3 id="1251-simulation-of-the-poisson-process">12.5.1 Simulation of the Poisson Process</h3>
<ul>
  <li>Homogeneous Poisson process with rate $\lambda$. $N(t_0)$ = number of events in $[0,t_0]$. $N(t_0) \sim \text{Poisson}(\lambda t_0)$. (Eq 12.26)</li>
  <li>Waiting times $S_k$ between events are i.i.d. $\text{Exp}(\lambda)$.</li>
  <li><strong>Algorithm 12.7 (Simulate Path until $t_0$):</strong>
    <ol>
      <li>$t=0, N=0$.</li>
      <li>Generate $s \sim \text{Exp}(\lambda)$ (i.e., $s = -(1/\lambda)\log u$).</li>
      <li>$t \leftarrow t+s$. If $t &gt; t_0$, stop.</li>
      <li>$N \leftarrow N+1$. Record event time $s_N = t$.</li>
      <li>Go to Step 2.</li>
    </ol>
  </li>
  <li>Alternative: Generate $N(t_0) \sim \text{Poisson}(\lambda t_0)$. Then generate $N(t_0)$ event times as i.i.d. $U(0, t_0)$ and sort them.</li>
</ul>

<h3 id="1252-simulation-of-the-nonhomogeneous-poisson-process">12.5.2 Simulation of the Nonhomogeneous Poisson Process</h3>
<ul>
  <li>Rate function $\lambda(t)$. Number of events in $[0,t_0]$ is $\text{Poisson}(\int_0^{t_0} \lambda(s)ds)$.</li>
  <li><strong>Thinning Algorithm (Algorithm 12.8):</strong>
    <ul>
      <li>Requires an upper bound $\lambda_U \ge \lambda(t)$ for all $t \in [0,t_0]$. (Eq 12.28)
        <ol>
          <li>$t=0, N=0$.</li>
          <li>Generate $s \sim \text{Exp}(\lambda_U)$. $t \leftarrow t+s$. If $t &gt; t_0$, stop.</li>
          <li>Generate $u_2 \sim U(0,1)$. If $u_2 \le \lambda(t)/\lambda_U$, accept event: $N \leftarrow N+1$, record $s_N=t$.</li>
          <li>Go to Step 2.</li>
        </ol>
      </li>
      <li>Inefficient if $\lambda(t) \ll \lambda_U$. Can break $[0,t_0]$ into subintervals with tighter $\lambda_{U,i}$.</li>
    </ul>
  </li>
  <li><strong>Inversion Method (if CDF of waiting times is tractable):</strong>
    <ul>
      <li>CDF of time $x$ to next event, given last event at $s$: $F_s(x) = 1 - \exp(-\int_s^{s+x} \lambda(y)dy)$. (Eq 12.29)</li>
      <li>Example: $\lambda(t) = 1/(t+a)$. $F_s(x) = x/(x+s+a)$. Inverse $x = F_s^{-1}(u) = (s+a)u/(1-u)$. (Eq 12.30-32)</li>
    </ul>
  </li>
</ul>

<h3 id="1253-simulation-of-discrete-time-markov-chains">12.5.3 Simulation of Discrete-Time Markov Chains</h3>
<ul>
  <li>States $1, \dots, S$. Transition matrix $P={p_{ij}}$. (Eq 12.33)</li>
  <li>Given current state $X_t=i$, next state $X_{t+1}$ is sampled from discrete distribution $(p_{i1}, \dots, p_{iS})$. Repeat for $m$ steps.</li>
  <li>For large $m$, can use $m$-step transition matrix $P^{(m)} = P^m$. (Eq 12.34)
    <ul>
      <li>If $P=U\Lambda U^{-1}$ (diagonalization, $\Lambda=\text{diag}(\lambda_k)$), then $P^m = U\Lambda^m U^{-1}$. (Eq 12.35, 36)</li>
    </ul>
  </li>
  <li><strong>Example 12.2 (K80 nucleotide model):</strong> Simulate evolution over $m$ years.
    <ul>
      <li>$P$ for one year (Eq 12.37). Calculate $P^m$ (Eq 12.38, 39) and sample from its rows.</li>
    </ul>
  </li>
</ul>

<h3 id="1254-simulation-of-continuous-time-markov-chains">12.5.4 Simulation of Continuous-Time Markov Chains</h3>
<ul>
  <li>Rate matrix $Q={q_{ij}}$. Rate of leaving state $i$ is $q_i = -q_{ii} = \sum_{j \ne i} q_{ij}$.</li>
  <li><strong>Algorithm 12.9 (Gillespie-type algorithm):</strong>
    <ol>
      <li>$t=0$, initial state $i=X(0)$.</li>
      <li>Generate waiting time $s \sim \text{Exp}(q_i)$.</li>
      <li>$t \leftarrow t+s$. If $t &gt; t_0$, stop.</li>
      <li>Sample new state $j$ from discrete distribution $(q_{i1}/q_i, \dots, q_{iS}/q_i)$ (for $j \ne i$). Set $i \leftarrow j$.</li>
      <li>Go to Step 2.
        <ul>
          <li>This simulates the jump chain and waiting times.</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h2 id="126-simulating-molecular-evolution">12.6 Simulating Molecular Evolution</h2>

<h3 id="1261-simulation-of-sequences-on-a-fixed-tree">12.6.1 Simulation of Sequences on a Fixed Tree</h3>
<ul>
  <li><strong>12.6.1.1 Method 1: Multinomial Sampling of Site Patterns:</strong>
    <ul>
      <li>Assumes sites are i.i.d. (includes +$\Gamma$ models).</li>
      <li>Calculate probability $p_k$ for each of $4^s$ site patterns (using phylogenetic likelihood algorithm, Ch 4).</li>
      <li>Sample $N_{sites}$ times from this multinomial distribution to get site pattern counts.</li>
      <li>Feasible for small trees ($s \le 4$ or $5$). Efficient with alias method.</li>
    </ul>
  </li>
  <li><strong>12.6.1.2 Method 2: Evolving Sequences Along Tree Branches (SEQ-GEN, EVOLVER):</strong>
    <ol>
      <li>Generate root sequence (from equilibrium frequencies $\pi_j$).</li>
      <li>For each branch of length $t$:
        <ul>
          <li>Calculate $P(t) = e^{Qt}$.</li>
          <li>For each site, if current nucleotide is $i$, sample next nucleotide from row $i$ of $P(t)$.</li>
        </ul>
      </li>
      <li>Repeat recursively down the tree. Final tip sequences are the data.</li>
    </ol>
  </li>
  <li><strong>12.6.1.3 Method 3: Simulating Waiting Times (Jump Chain):</strong>
    <ul>
      <li>Variation of Method 2. Evolve along branches using Algorithm 12.9 (simulate jumps and waiting times).</li>
      <li>Advantage: No need to calculate $P(t)$. Useful for complex models (indels, rearrangements) where total rate of all events can be calculated.</li>
    </ul>
  </li>
  <li><strong>12.6.1.4 Simulation under JC69 and K80:</strong>
    <ul>
      <li>Substitution process is Poisson.</li>
      <li>Can generate total number of changes $N_{subst} \sim \text{Poisson}(l \lambda t)$ for a branch of length $t$ with $l$ sites, rate $\lambda$.</li>
      <li>Assign $N_{subst}$ changes to random sites.</li>
      <li>For each change, pick new nucleotide type based on model (e.g., $1/3$ for JC69; based on $\kappa$ for K80).</li>
    </ul>
  </li>
  <li><strong>12.6.1.5 Simulation under More Complex Models:</strong>
    <ul>
      <li><strong>Partition Models (Fixed-Site Heterogeneity):</strong> e.g., different genes/codon positions have different rates/parameters. Simulate each partition separately using Methods 1-3, then combine.</li>
      <li><strong>Mixture Models (Random-Site Heterogeneity, e.g., +$\Gamma$):</strong>
        <ul>
          <li>For each site, sample its rate $r_h$ from the distribution (e.g., gamma).</li>
          <li>Then simulate evolution for that site using $P(t \cdot r_h)$.</li>
          <li>If discrete gamma, sample rate class for each site first, then simulate all sites in same class together.</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h3 id="1262-simulation-of-random-trees">12.6.2 Simulation of Random Trees</h3>
<ul>
  <li><strong>Coalescent Model:</strong> Generate waiting times $T_j \sim \text{Exp}(\binom{j}{2})$, randomly join lineages. (Chapter 9)</li>
  <li><strong>Birth-Death Process Model:</strong> (e.g., Yule) Node ages are order statistics from a kernel density (Eq 10.11). Generates trees with clock.</li>
  <li>Can simulate rate drift on tree (e.g., GBM from §10.4.3) to get non-clock trees.</li>
  <li>Or, sample random topologies, then sample branch lengths from arbitrary distributions (e.g., exponential, gamma).</li>
</ul>

<h2 id="127-validation-of-the-simulation-program">12.7 Validation of the Simulation Program</h2>
<ul>
  <li>Standard debugging techniques: modular testing, isolate problems.</li>
  <li>Test simple cases with known analytical answers.</li>
  <li>Print intermediate variable values to check correctness.</li>
  <li>Common error: Forcing root sequence to be a specific observed sequence instead of drawing from equilibrium distribution.</li>
</ul>]]></content><author><name>Haogao Gu</name><email>work@guhaogao.com</email></author><category term="Book notes" /><category term="Molecular evolution" /><category term="Statistics" /><summary type="html"><![CDATA[We decide to read the book Molecular Evolution: A Statistical Approach by Ziheng Yang, to gether on a weekly basis. Contents in this summary involve AI-generated text.]]></summary></entry><entry><title type="html">Paper digest: Coalescent with reassortment</title><link href="https://guhaogao.com/posts/2025-01-15-coalescent_with_reassortment" rel="alternate" type="text/html" title="Paper digest: Coalescent with reassortment" /><published>2025-01-15T00:00:00+08:00</published><updated>2025-01-15T00:00:00+08:00</updated><id>https://guhaogao.com/posts/coalescent_with_reassorment</id><content type="html" xml:base="https://guhaogao.com/posts/2025-01-15-coalescent_with_reassortment"><![CDATA[<h2 id="bayesian-inference-of-reassortment-networks-reveals-fitness-benefits-of-reassortment-in-human-influenza-viruses-by-muller-et-al-on-pnas-2020"><a href="https://www.pnas.org/doi/10.1073/pnas.1918304117">Bayesian inference of reassortment networks reveals fitness benefits of reassortment in human influenza viruses</a> by Muller et al. on PNAS, 2020.</h2>

<h2 id="joint-inference-of-migration-and-reassortment-patterns-for-viruses-with-segmented-genomes-by-ugnė-stolz-tanja-stadler-nicola-f-müller-and-timothy-g-vaughan-on-molecular-biology-and-evolution-2021"><a href="https://academic.oup.com/mbe/article/39/1/msab342/6454099">Joint Inference of Migration and Reassortment Patterns for Viruses with Segmented Genomes</a> by <em>Ugnė Stolz, Tanja Stadler, Nicola F Müller, and Timothy G Vaughan</em> on Molecular Biology and Evolution, 2021.</h2>

<ul>
  <li>This paper is about Structured Coalescent with Reassortment (SCORE).</li>
  <li>This work was built upon the previous work of <a href="https://www.pnas.org/doi/10.1073/pnas.1918304117">Müller et al. 2020</a>, which is the unstructured coalescent with reassortment model.</li>
  <li>Reassortment is well known in influenza viruses. Reassortment events have clear boundaries in the genome, in comparison to recombination.</li>
  <li><strong>Intuitively</strong>, migration and reassortment are closely related, as reassortment can only occur when two different strains co-infect the same host.</li>
</ul>

<h3 id="methods">Methods</h3>]]></content><author><name>Haogao Gu</name><email>work@guhaogao.com</email></author><category term="Paper digest" /><category term="Coalescent theory" /><summary type="html"><![CDATA[Bayesian inference of reassortment networks reveals fitness benefits of reassortment in human influenza viruses by Muller et al. on PNAS, 2020.]]></summary></entry><entry><title type="html">Paper digest: More structured coalescent papers: on Erik M. Volz’s work</title><link href="https://guhaogao.com/posts/2025-01-10-Structured_coalescent4" rel="alternate" type="text/html" title="Paper digest: More structured coalescent papers: on Erik M. Volz’s work" /><published>2025-01-12T00:00:00+08:00</published><updated>2025-01-12T00:00:00+08:00</updated><id>https://guhaogao.com/posts/Structured_coalescent4</id><content type="html" xml:base="https://guhaogao.com/posts/2025-01-10-Structured_coalescent4"><![CDATA[<p>Back on 2012, <a href="https://scholar.google.com/citations?user=cp2B1yUAAAAJ&amp;hl=en">Eric M. Volz</a> had</p>

<h2 id="complex-population-dynamics-and-the-coalescent-under-neutrality-by-eric-m-volz-on-genetics-2012"><a href="https://academic.oup.com/genetics/article/190/1/187/6063310">Complex Population Dynamics and the Coalescent Under Neutrality</a> by <em>Eric M. Volz</em> on Genetics, 2012.</h2>

<h2 id="summary">Summary</h2>

<ul>
  <li>In this paper, Erik showed how to derive the rate of coalescence, as well as the likelihood of a gene genealogy with heterochronous sampling and labeled taxa, and how to simulate a coalescent tree conditional on a complex demographic history.</li>
</ul>

<ol>
  <li><strong>A New Coalescent Framework:</strong> The paper develops a coalescent model for populations with complex, non-linear dynamics described by deterministic systems of arbitrary dimensions. It handles:
    <ul>
      <li><strong>Varying Birth and Death Rates:</strong> Unlike standard coalescent models, it doesn’t assume constant rates. Birth and death rates can be any differentiable function of time and the state of the system.</li>
      <li><strong>Structured Populations:</strong> It accounts for population structure (multiple “demes”) where gene copies can reproduce within and across demes, and migration can occur.</li>
      <li><strong>Large Sample Fractions:</strong> The model can handle scenarios where a significant portion of the population is sampled, which is often the case in epidemiological studies.</li>
    </ul>
  </li>
  <li><strong>Derivation of Coalescent Rate Under Birth-death Process:</strong>
    <ul>
      <li>The rate of coalescence (λ<sub>2</sub>) for two lineages is $\frac{1}{Y({s})}$ under Kingman coalescent.</li>
      <li>Under a birth–death process with varying rates. It shows that λ<sub>2</sub> is not simply the inverse of the population size (1/Y), but rather a function of both population size and the time-varying birth rate: $λ_2(s) = 2f(s)/Y^2(s)$.</li>
      <li>The birth rate $f(t)=\beta X(t)Y(t)$ correspond to $\beta SI$ in the SIR model.</li>
      <li>In traditional Birth-Death model, $f(t)=cY(t)$, where $c$ is a constant, such as exponential growth.</li>
      <li>The birth rate of a singe copy is $f(t, Y)/Y(t)$, it is both time ($f(t, Y)$) and state ($Y(t)$) dependent.</li>
      <li>Classical solutions, such as $\lambda_2(s) \propto 1/Y(s)$, appear as special cases when births are strictly proportional to population size.</li>
      <li>The coalescent rate is under BD model, in Moran’s style:</li>
    </ul>

    <p>\(F(s) = \int_0^s f(\tau) \, d\tau,\\
 \Lambda_2(s) = \sum_{j=1}^{\lfloor F(s) \rfloor} \frac{\sigma^2_M(j)}{\overline{Y}(j)}.\)</p>
    <ul>
      <li>After some steps we reached:</li>
    </ul>

\[\lambda_A(s) = \left( \frac{A(s)}{2} \right) \frac{2f(s)}{Y^2(s)}.\]
  </li>
  <li><strong>Bias in Skyline Estimators:</strong> It demonstrates that non-parametric estimators of N<sub>e</sub>, such as the skyline plot, can be biased when birth rates are not proportional to population size. This is particularly relevant in scenarios like “Faster Than Exponential” (FTE) or “Slower Than Exponential” (STE) growth, which can occur during epidemics.</li>
  <li><strong>Number of Lineages Through Time (NLFT):</strong> The paper explores the relationship between the NLFT and population dynamics. It shows that the NLFT is sensitive to the history of birth rates, not just population size, leading to potentially counterintuitive interpretations of tree shapes.</li>
  <li><strong>Structured Populations:</strong> It extends the coalescent to structured populations with concurrent birth, death, and migration processes. It derives a master equation for the rate of coalescence in such scenarios.
    <ul>
      <li>Note that in the structured coalescent model in this paper, Gene copies may reproduce both <strong>within and across</strong> demes. Consequently, two gene copies in different demes may coalesce without being preceded by a migration event (which may be too simplistic for some scenarios).</li>
      <li>TOO many formulas, I will skip them here.</li>
    </ul>
  </li>
  <li><strong>Simulation and Likelihood:</strong> The paper presents methods for simulating coalescent trees and calculating the likelihood of a gene genealogy conditional on a complex demographic history, including structured populations.</li>
</ol>]]></content><author><name>Haogao Gu</name><email>work@guhaogao.com</email></author><category term="Paper digest" /><category term="Coalescent theory" /><category term="Phylogenetics" /><summary type="html"><![CDATA[Back on 2012, Eric M. Volz had]]></summary></entry><entry><title type="html">Paper digest: Genomic Inference of Transmission History (Non structured coalescent methods)</title><link href="https://guhaogao.com/posts/2025-01-10-genomic-inference-transmission-history" rel="alternate" type="text/html" title="Paper digest: Genomic Inference of Transmission History (Non structured coalescent methods)" /><published>2025-01-10T00:00:00+08:00</published><updated>2025-01-10T00:00:00+08:00</updated><id>https://guhaogao.com/posts/Genomic-inference-transmission-history</id><content type="html" xml:base="https://guhaogao.com/posts/2025-01-10-genomic-inference-transmission-history"><![CDATA[<p>This post focuses on several papers using <strong>non-structured</strong> coalescent methods to infer transmission history from genomic data.</p>

<h1 id="genomic-infectious-disease-epidemiology-in-partially-sampled-and-ongoing-outbreaks-by-xavier-didelot-et-al-on-molecular-biology-and-evolution-2017"><a href="https://academic.oup.com/mbe/article/34/4/997/2919386?login=true">Genomic Infectious Disease Epidemiology in Partially Sampled and Ongoing Outbreaks</a> by <em>Xavier Didelot et al.</em> on Molecular Biology and Evolution, 2017.</h1>

<p>Transphylo (R package) was introduced in this paper.</p>

<h1 id="bayesian-reconstruction-of-transmission-within-outbreaks-using-genomic-variants-by-nicola-de-maio-et-al-on-plos-computational-biology-2018"><a href="https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1006117">Bayesian reconstruction of transmission within outbreaks using genomic variants</a> by <em>Nicola De Maio et al.</em> on PLOS Computational Biology, 2018.</h1>]]></content><author><name>Haogao Gu</name><email>work@guhaogao.com</email></author><category term="Paper digest" /><category term="Phylogenetics" /><summary type="html"><![CDATA[This post focuses on several papers using non-structured coalescent methods to infer transmission history from genomic data.]]></summary></entry><entry><title type="html">Paper digest: More structured coalescent papers: on Nicola F. Muller and Nicola De Maio</title><link href="https://guhaogao.com/posts/2025-01-04/structured-coalescent3" rel="alternate" type="text/html" title="Paper digest: More structured coalescent papers: on Nicola F. Muller and Nicola De Maio" /><published>2025-01-04T00:00:00+08:00</published><updated>2025-01-11T00:00:00+08:00</updated><id>https://guhaogao.com/posts/2025-01-04/Sturctured_coalescent3</id><content type="html" xml:base="https://guhaogao.com/posts/2025-01-04/structured-coalescent3"><![CDATA[<p>I wanted to get in more details about the structured coalescent model, here I record some notes when I read related papers.</p>

<h1 id="overview">Overview</h1>
<p>Firstly there is a review paper on phylogeographic inference on 2010, then I will go through some papers on structured coalescent models.</p>

<p>Structured coalescent papers we studied here are mainly from two authors:</p>
<ul>
  <li><a href="https://muellerlab.io">Nicola F. Muller</a>, who developed <a href="https://taming-the-beast.org/tutorials/Mascot-Tutorial/">MASCOT</a>.</li>
  <li><a href="https://scholar.google.at/citations?user=5qarsrQAAAAJ&amp;hl=en">Nicola De Maio</a>, who developed <a href="https://taming-the-beast.org/tutorials/SCOTTI-Tutorial/">SCOTTI</a>.</li>
</ul>

<h1 id="papers">Papers</h1>

<h2 id="three-roads-diverged-routes-to-phylogeographic-inference-by-erik-w-bloomquist-et-al-on-trends-in-ecology--evolution-2010"><a href="https://www.sciencedirect.com/science/article/pii/S0169534710001965?via%3Dihub">Three roads diverged? Routes to phylogeographic inference</a> by <em>Erik W. Bloomquist</em> et al. on Trends in Ecology &amp; Evolution, 2010.</h2>

<p>This is a summative review paper on phylogeographic inference methods.</p>

<h3 id="nested-clade-phylogeographic-analysis-ncpa-a-comparative-approach">Nested clade phylogeographic analysis (NCPA), a comparative approach</h3>

<ul>
  <li>A method to integrate <strong>molecular genealogy</strong> (often a haplotype tree) and <strong>geographic information</strong> in a single framework. Its main goal is to infer <strong>historical processes</strong> that shaped the geographic distribution of genetic variation—things like range expansions, fragmentations, or isolation by distance—using only single-locus (or sometimes multi-locus) sequence data.</li>
  <li>The Three-Step Workflow
    <ul>
      <li><strong>Haplotype Tree or Network Construction</strong>: You start by building a haplotype tree or haplotype network from your molecular data (e.g., DNA sequences). Various methods can be used (parsimony, statistical parsimony, median-joining, etc.).</li>
      <li><strong>Nesting Clades</strong>: Once you have the haplotype tree, you “nest” clades in a hierarchical manner:
        <ul>
          <li>The most closely related haplotypes form the first (1‐step) clade.</li>
          <li>Groups of 1‐step clades form the 2‐step clade, and so on, up to the entire tree.</li>
          <li>This step is somewhat subjective and follows a set of guidelines by Templeton.</li>
        </ul>
      </li>
      <li><strong>Statistical Tests &amp; Interpretation</strong>:
        <ul>
          <li>For each clade, you measure how broadly it is geographically distributed relative to its genetic diversity.</li>
          <li>A permutation test is used to assess statistical significance (does this clade appear more geographically “spread out” than expected by chance?).</li>
          <li>Finally, you use an “inference key” (a decision flowchart) to interpret patterns (e.g., “range expansion,” “isolation by distance,” “fragmentation,” etc.).</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Criticisms:
    <ul>
      <li><strong>High False-Positive Rate</strong>
        <ul>
          <li>Multiple studies (e.g., Knowles &amp; Maddison; Panchal &amp; Beaumont) showed that single-locus NCPA tends to over‐detect “significant” phylogeographic patterns, suggesting many false positives.</li>
          <li>One reason is that multiple clades in the nested design are tested, but the method did not adequately correct for multiple testing (Type I error accumulation).</li>
        </ul>
      </li>
      <li><strong>Pipeline Nature &amp; Overconfidence</strong>
        <ul>
          <li>NCPA is a sequential pipeline:
            <ul>
              <li>Build or infer a single haplotype tree.</li>
              <li>Nest the clades.</li>
              <li>Do a permutation test and interpret.</li>
            </ul>
          </li>
          <li>Errors or uncertainty in earlier stages (e.g., how the tree is constructed or how clades are nested) are not carried forward—thus each subsequent step can overstate confidence in the final inferences.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Modern model-based</strong> (particularly Bayesian or coalescent) methods are now preferred, because they:
    <ul>
      <li>They Incorporate Geography More Rigorously
        <ul>
          <li>Some methods directly model <strong>migration rates</strong> or <strong>dispersal kernels</strong> in continuous or discrete space.</li>
          <li>They can handle <strong>population size</strong> changes, gene flow, barriers, and other complexities.</li>
        </ul>
      </li>
      <li>They Are Statistically Formal
        <ul>
          <li>By specifying an explicit <strong>probabilistic model</strong> of evolution + geography, one can <strong>estimate</strong> parameters (e.g., migration rates, times of divergence) and <strong>compare</strong> models via likelihood or Bayesian posterior probabilities.</li>
        </ul>
      </li>
      <li>Joint Inference
        <ul>
          <li>Many modern approaches <strong>jointly</strong> infer genealogies, demographic parameters, and geographic patterns, thus <strong>avoiding</strong> the pipeline problem where each step is conditionally fixed.</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h3 id="spatial-diffusion-approach">Spatial diffusion approach</h3>

<ol>
  <li><strong>Model‐Based Spatial Diffusion</strong>
    <ul>
      <li>Unlike traditional “population‐based” spatial coalescent models, <strong>phylogenetic diffusion</strong> focuses on the <strong>ancestral history of a particular sample</strong> of molecular sequences.</li>
      <li>It treats <strong>location</strong> as a trait evolving along the branches of a <strong>time‐calibrated phylogeny</strong>, using <strong>continuous‐time Markov chains (CTMC)</strong>.</li>
      <li>This permits a <em>probabilistic</em> reconstruction of when and where the ancestors of sampled sequences existed, often implemented in <strong>BEAST</strong>.</li>
    </ul>
  </li>
  <li><strong>Discrete vs. Continuous Spatial Models</strong>
    <ul>
      <li><strong>Discrete diffusion</strong>: Each lineage “jumps” among a set of discrete locations. It can handle many possible states (locations), but each additional location increases the number of rate parameters.</li>
      <li><strong>Continuous diffusion</strong>: Lineages move in a continuous spatial landscape (e.g., coordinates modeled via Brownian motion or more flexible “relaxed random walks”).</li>
      <li>These approaches can incorporate <strong>geographical context</strong>, such as distance‐dependent dispersal or environmental barriers, and handle <strong>rate heterogeneity</strong> over the phylogeny (relaxed clock style).</li>
    </ul>
  </li>
  <li><strong>Bayesian Statistical Framework</strong>
    <ul>
      <li><strong>Bayesian</strong> methods naturally account for over‐parameterization by placing <strong>priors</strong> on migration rates (e.g., distance‐informed priors).</li>
      <li>They can also perform <strong>Bayesian Stochastic Search Variable Selection (BSSVS)</strong> to identify only those migration rates essential to explain the data, reducing complexity.</li>
      <li>This framework yields <strong>posterior distributions</strong> reflecting uncertainty in both <strong>phylogenetic</strong> and <strong>geographic</strong> estimates.</li>
    </ul>
  </li>
  <li><strong>Advantages &amp; Use Cases</strong>
    <ul>
      <li>More <strong>realistic</strong> than simplistic or purely heuristic (parsimony) ancestral reconstructions.</li>
      <li><strong>Accommodates</strong> uncertainty in tree topology, branch lengths, and location histories.</li>
      <li>Useful in <strong>epidemiology</strong> (e.g., viral outbreaks), <strong>biogeography</strong> (e.g., island studies, animal movement), and any case where one wants to see <strong>how lineages spread</strong> over space and time.</li>
    </ul>
  </li>
</ol>

<ul>
  <li>Overall, this <strong>spatial diffusion approach</strong> integrates <em>time‐scaled phylogenies</em> with <em>spatial movement models</em> to infer how sampled lineages have dispersed geographically. It sidesteps full “population‐based” modeling in favor of <strong>direct ancestral locations</strong> for the sequences under study, offering a flexible, Bayesian way to reconstruct <strong>spatial histories</strong> in evolutionary and epidemiological research.</li>
</ul>

<h3 id="population-genetics-approach">Population genetics approach</h3>

<ul>
  <li>The population genetics approach to phylogeography is dominated by methods based on the structured-coalescent framework, which models evolutionary trees as <strong>random draws</strong> from population-level processes like selection, migration, population size changes, and recombination.</li>
  <li><img src="https://ars.els-cdn.com/content/image/1-s2.0-S0169534710001965-gr1.jpg" alt="" /></li>
</ul>

<h3 id="comparing-mugration-and-structured-coalescent-from-chatgpt">Comparing mugration and structured coalescent (From ChatGPT):</h3>
<ul>
  <li><strong>Mugration models</strong> treat location as a discrete trait evolving along a single phylogenetic tree via a continuous‐time Markov chain (CTMC). They do not explicitly model different populations (demes) and their internal coalescent events.</li>
  <li><strong>Structured coalescent</strong> approaches like MASCOT and SCOTTI explicitly model how lineages coalesce within demes (or hosts) and migrate or transmit between demes (or hosts). They incorporate population sizes, migration (transmission) rates, and the coalescent process in each deme.</li>
  <li>
    <p>In other words, mugration is essentially a <em>trait-substitution</em> model for location, whereas structured coalescent models the <em>population-genetic</em> process of coalescence within and between subpopulations.</p>

    <table>
      <thead>
        <tr>
          <th><strong>Aspect</strong></th>
          <th><strong>Mugration Model</strong></th>
          <th><strong>Structured Coalescent Model (e.g. MASCOT, SCOTTI)</strong></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><strong>Level of modeling</strong></td>
          <td>Per‐lineage <em>trait substitution</em> (no explicit coalescent events in each location).</td>
          <td>Full coalescent with population subdivision: genealogies form via coalescence <em>within</em> demes, migration/transmission <em>between</em> demes.</td>
        </tr>
        <tr>
          <td><strong>Population sizes &amp; demes</strong></td>
          <td>Not modeled; “location” is just a discrete character.</td>
          <td>Each deme (or host) has an <em>effective population size</em>. Coalescent rates depend on deme sizes.</td>
        </tr>
        <tr>
          <td><strong>Migration</strong></td>
          <td>A simple CTMC of jumps between states along a single phylogeny.</td>
          <td>Migration/transmission events between demes/hosts are part of the <em>structured coalescent process</em> that generates genealogies.</td>
        </tr>
        <tr>
          <td><strong>Inferred quantities</strong></td>
          <td>- Location states at ancestral nodes<br />- Rate matrix of location changes</td>
          <td>- Demic or host‐level coalescent parameters (population sizes)<br />- Migration/transmission rates<br />- Full distribution of genealogies with demic assignment for each lineage.</td>
        </tr>
        <tr>
          <td><strong>Typical usage</strong></td>
          <td>Reconstructing <strong>discrete phylogeography</strong>: “Where did the lineages come from and how often did they move among locations?”</td>
          <td>Understanding <strong>population structure</strong>, <strong>host–pathogen</strong> dynamics, or <strong>transmission chains</strong> with explicit coalescent modeling.</td>
        </tr>
      </tbody>
    </table>
  </li>
</ul>

<h2 id="new-routes-to-phylogeography-a-bayesian-structured-coalescent-approximation-by-nicola-de-maio-et-al-on-plos-genetics-2015"><a href="https://journals.plos.org/plosgenetics/article?id=10.1371/journal.pgen.1005421">New Routes to Phylogeography: A Bayesian Structured Coalescent Approximation</a> by <em>Nicola De Maio et al.</em> on PLOS Genetics, 2015.</h2>

<h3 id="abstract">Abstract</h3>
<ul>
  <li>In this paper, we show that inference of migration rates and root locations based on <strong>discrete trait</strong> models is extremely unreliable and sensitive to biased sampling.</li>
  <li>BASTA (BAyesian STructured coalescent Approximation): a approach implemented in BEAST2 that combines the accuracy of methods based on the structured coalescent with the computational efficiency required to handle more than just few populations.</li>
</ul>

<h3 id="background">Background</h3>

<ul>
  <li>Use of the discrete trait analysis (DTA), such as <em>mugration</em>, entails a number of assumptions that are unusual or inappropriate when applied to the migration of lineages between geographic locations, for example
    <ol>
      <li>the relative size of subpopulations drifts over time, such that subpopulations can become lost (extinct) or fixed (the sole remaining subpopulation) instead of being constrained, e.g. by local competition,</li>
      <li>sample sizes across subpopulations are proportional to their relative size.</li>
    </ol>
  </li>
</ul>

<h3 id="methods">Methods</h3>
<ul>
  <li><img src="/files/2024-12-28-structured-coalescent/Screenshot%202025-01-03%20at%2019.38.43.webp" alt="" /></li>
</ul>

<h4 id="the-structured-coalescent">The Structured Coalescent</h4>
<ul>
  <li>Key assumptions:
    <ul>
      <li>Demes are stable in size, with their effective sizes defined by vector $\theta$.</li>
      <li>Migration occurs at a constant rate over time, defined by matrix $f$.</li>
      <li>No substructure within demes.</li>
      <li>No fitness differences between individuals.</li>
      <li>Within demes, individuals are sampled at random.</li>
      <li>However, no assumptions are made about the total sample size nor the relative sample sizes per deme.</li>
    </ul>
  </li>
  <li>$f_{a,b}$ is the <em>forwards-in-time</em> migration rate matrix, and conventionally $m_{b,a}$ is the <em>backwards-in-time</em> migration rate matrix. Both specifying migration of individuals from deme $a$ to deme $b$. Specifically, $m_{b,a}=f_{a,b}\theta_a/\theta_b$.</li>
  <li>
    <p>Recall that in <a href="https://guhaogao.com/posts/2025-01-03/structured-coalescent2">MultiTypeTree (MTT) for Structured coalescent</a>:</p>

    <ul>
      <li>
        <p>The posterior distribution of the parameters is:</p>

\[P(T, M, \mu, m, \theta \mid S, t_I, L) \propto P(S \mid T, t_I, \mu) P(T, M \mid t_I, L, m, \theta) P(\mu) P(m) P(\theta).\]
      </li>
      <li><strong>Components</strong>:
        <ol>
          <li>The first term, $P(S \mid T, t_I, \mu)$, is the likelihood of the sequences given the genealogy and substitution model, computed using Felsenstein’s pruning algorithm.</li>
          <li>The second term, $P(T, M \mid t_I, L, m, \theta)$, represents the probability density of the genealogy and migration history under the structured coalescent, given the migration matrix and effective population sizes.</li>
          <li>The third term is the prior distribution of the parameters, potentially factored as independent priors for $\mu$, $m$, and $\theta$.</li>
        </ol>
      </li>
      <li>
        <p>To calculate $P(T, M \mid t_I, L, m, \theta)$, the sequence of $B$ time intervals between successive events (coalescence, sampling, or migration) is considered, starting from the most recent sample back to the root. For a haploid population:</p>

\[P(T, M \mid t_I, L, m, \theta) = \prod_{i=1}^B L_i,\]

        <p>where:</p>

\[L_i = \exp \left[ 
-\tau_i \sum_{d \in D} \left( 
\binom{k_{i,d}}{2} \frac{1}{\theta_d} + k_{i,d} \sum_{d' \in D, d' \neq d} m_{dd'}
\right) \right] E_i,\]

        <p>and:</p>
        <ul>
          <li>$k_{i,d}$ is the number of lineages in deme $d$ during interval $i$.</li>
          <li>$E_i$ is the contribution of the event ending interval $i$:</li>
        </ul>

\[E_i =
\begin{cases}
1 &amp; \text{if it is a sampling event}, \\
m_{dd'} &amp; \text{if it is a migration event from } d \text{ to } d', \\
\frac{1}{\theta_d} &amp; \text{if it is a coalescence event in deme } d.
\end{cases}\]
      </li>
    </ul>
  </li>
</ul>

<h4 id="discrete-trait-analysis">Discrete Trait Analysis</h4>

<ul>
  <li><strong>Key Idea</strong>:</li>
  <li>Treats a lineage’s “location” as a <strong>discrete trait</strong> (analogous to nucleotides) evolving along an unstructured coalescent tree.</li>
  <li>Uses <strong>Felsenstein’s pruning algorithm</strong> to integrate over all trait histories (migration paths) very efficiently.</li>
  <li><strong>Model</strong>:</li>
  <li>The prior on the tree often assumes a <strong>single, unstructured</strong> population.</li>
  <li>“Migration” is just a constant‐rate Markov chain, unrelated to actual subpopulation sizes.</li>
  <li><strong>Sampling fraction $\propto$ subpopulation size is assumed</strong>.</li>
  <li><strong>Pros</strong>:</li>
  <li>Fast and straightforward to implement (common in BEAST’s “discrete phylogeography”).</li>
  <li><strong>Cons</strong>:</li>
  <li>Can produce <strong>biased</strong> results if real subpopulation sizes or migration strongly influence tree shape, or if sampling intensity does not match relative deme size.
    <ul>
      <li>Allows “loss” or “resurrection” of demes in unrealistic ways.</li>
    </ul>
  </li>
  <li>Comparison to MTT:
    <ul>
      <li>In <strong>Discrete Trait Analysis (DTA)</strong>, the <em>migration rates</em> do <strong>not</strong> shape the branching times or topology of the genealogy; instead, the genealogical prior is (for the most part) an <strong>unstructured coalescent</strong> (or some other simple tree prior), and “migration” is just treated as a <strong>discrete‐character substitution</strong> process on that fixed genealogy.</li>
      <li>
        <p>Hence, in DTA:
\(P(T,\mu,f,\theta \;\big|\; S,t_I,L)
\;\;\propto\;\;
\underbrace{P(L \mid T, t_I, f)}_{\substack{\text{location-likelihood via discrete}\\\text{trait (migration) “substitutions”}}}
\;
\times
\underbrace{P(S \mid T, t_I, \mu)}_{\substack{\text{sequence-likelihood via}\\\text{molecular substitutions}}}
\;
\times
\underbrace{P(T \mid t_I,\theta)}_{\substack{\text{unstructured coalescent}\\\text{prior on the tree}}}
\;
\times
P(\mu,f,\theta),\)</p>

        <p>the “tree prior” $\smash{P(T\mid t_I,\theta)}$ <strong>does not</strong> depend on the migration parameters $f$.</p>
      </li>
      <li>
        <p>By contrast, in a <strong>MultiTypeTree (MTT)</strong> or <strong>structured coalescent</strong> model, migration <strong>does</strong> directly affect the genealogy: if lineages in the same deme coalesce faster, or if migration rates are low, that changes how quickly lineages coalesce and thus reshapes the branching pattern and times of the tree.</p>
      </li>
      <li>
        <p>So in MTT (structured coalescent):</p>

        <p>\(P(T, M, \mu, m, \theta \;\big|\; S,t_I,L)
\;\;\propto\;\;
\underbrace{P(S \mid T, t_I, \mu)}_{\text{sequence-likelihood}}
\;
\times
\underbrace{P(T, M \mid t_I,L,m,\theta)}_{\substack{\text{structured coalescent prior}\\\text{(tree \textit{and} migration events)}}}
\;
\times
P(\mu)\,P(m)\,P(\theta),\)
the genealogical prior $\smash{P(T,M\mid t_I,L,m,\theta)}$ <strong>does</strong> depend on $m$ (migration rates) and $\theta$, because migration directly changes how/when lineages coalesce and how the tree is shaped.</p>
      </li>
    </ul>
  </li>
  <li>Again, for DTA,
    <ul>
      <li>one concern is that the assumption that sampling intensity is proportional to subpopulation size leads to biased estimates of migration rates when this assumption is not met (PMID: <a href="http://www.ncbi.nlm.nih.gov/pubmed/22190015">22190015</a>, PMID: <a href="http://www.ncbi.nlm.nih.gov/pubmed/24586153">24586153</a>).</li>
      <li>Second, ignoring the population structure when calculating the probability of the coalescent tree could lead to bias or lost power. For example, when migration rates are very low, one expects very long branches close to the root. This interdependency between the shape and branch lengths of the genealogy and the migration process is ignored by DTA, which could reduce accuracy.</li>
    </ul>
  </li>
</ul>

<h4 id="basta">BASTA</h4>

<ul>
  <li>Overall:
    <ol>
      <li>BASTA integrates over migration histories in a simpler way (treating lineages’ locations as partially independent and discretizing time in sub-intervals).</li>
      <li>BASTA still allows coalescence rates to depend on whether lineages are in the same deme (unlike DTA).</li>
      <li>Because it approximates the exact (and complex) structured‐coalescent integral, it is computationally cheaper than MTT while retaining more accuracy than DTA.</li>
    </ol>
  </li>
  <li>
    <p>BASTA Posterior</p>

\[P(T, \mu, m, \theta \mid S, t_I, L)
\;\;\propto\;\;
\underbrace{P(S \mid T, t_I, \mu)}_{\text{sequence likelihood}}
\;\times\;
\underbrace{P(T \mid t_I, L, m, \theta)}_{\substack{\text{structured coalescent} \\ \text{(approx.)}}}
\;\times\;
P(\mu, m, \theta).\]

    <ul>
      <li>$S$: sequence data</li>
      <li>$T$: the genealogy (topology + branch lengths)</li>
      <li>$\mu$: mutation/substitution parameters</li>
      <li>$m$: migration rates</li>
      <li>$\theta$: set of effective population sizes for each deme</li>
      <li>$L$: tip locations</li>
      <li>$t_I$: sampling times (if heterochronous)</li>
    </ul>
  </li>
  <li>
    <p>In <strong>MTT</strong>, the genealogy $T$ and the <em>explicit</em> migration events $M$ appear:</p>

\[P(T, M, \mu, m, \theta \;\mid\; S, t_I, L)
\;\;\propto\;\;
P(S \mid T, t_I, \mu)
\;\times\;
\underbrace{P(T, M \mid t_I, L, m, \theta)}_{\text{structured coalescent prior (exact)}}
\;\times\;
P(\mu)\,P(m)\,P(\theta).\]

    <ul>
      <li>MTT attempts to <strong>fully</strong> sample each lineage’s migration path in the genealogy, which becomes computationally expensive for large datasets or many demes.</li>
    </ul>
  </li>
  <li>
    <p>BASTA’s Approximation</p>

    <ol>
      <li><strong>Independent Migration</strong>: By writing</li>
    </ol>

\[P(d_l = d, d_{l'} = d \mid t) \approx P(d_l = d \mid t) P(d_{l'} = d \mid t),\]

    <p>we ignore any correlation among lineages’ locations (e.g., limited carrying capacity, correlated environment, etc.).</p>

    <ol>
      <li>
        <p><strong>Discrete Subintervals</strong>: Instead of integrating exactly over time, evaluations are performed at only two points (start/end) per interval, assuming probabilities are constant across each half-interval.</p>
      </li>
      <li>
        <p><strong>Matrix Exponential</strong>: The update</p>
      </li>
    </ol>

\[P_{l, \alpha_i} = P_{l, \alpha_{i-1}} e^{\tau_i \mathbf{m}}\]

    <p>is standard for a continuous-time Markov chain, but applying it only at interval boundaries omits any subtle interactions that might occur mid-interval.</p>
  </li>
  <li>
    <p>Why It Makes BASTA Faster</p>

    <ul>
      <li><strong>Exact MTT</strong>: Must consider <strong>every</strong> possible lineage location at every moment — this grows combinatorially with number of lineages/demes.</li>
      <li><strong>BASTA</strong>:
        <ol>
          <li>Uses <strong>matrix exponentials</strong> to update each lineage’s location probabilities over sub-intervals.</li>
          <li>Approximates that lineages migrate independently within those sub-intervals.</li>
          <li><strong>Only</strong> updates location probabilities at discrete time points (start/end of sub-intervals), skipping continuous integration.</li>
        </ol>
      </li>
      <li>Skipping a full enumeration of migration paths drastically reduces computation. BASTA still incorporates subpopulation structure into coalescent rates (unlike DTA, which ignores it altogether).</li>
    </ul>
  </li>
</ul>

<h3 id="simulation-and-results">Simulation and results</h3>

<ul>
  <li>DTA overestimates migration rates when sampling intensity does not match subpopulation size.</li>
  <li>DTA Under-represents Uncertainty.</li>
  <li>DTA have lowest accuracy in estimating root locations.</li>
</ul>

<h2 id="scottiefficient-reconstruction-of-transmission-within-outbreaks-with-the-structured-coalescent-by-nicola-de-maio-et-al-on-plos-computational-biology-2016"><a href="https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1005130">SCOTTI:Efficient Reconstruction of Transmission within Outbreaks with the Structured Coalescent</a> by <em>Nicola De Maio et al.</em> on PLOS Computational Biology, 2016.</h2>

<h3 id="abstract-1">Abstract</h3>
<ul>
  <li>This study demonstrates SCOTTI (Structured COalescent Transmission Tree Inference), for modelling each host as a distinct population, and transmissions between hosts as migration events.</li>
  <li>Some example scenario for transmission: <img src="/files/2024-12-28-structured-coalescent/Screenshot%202025-01-04%20at%2020.45.01.webp" alt="" /></li>
</ul>

<h3 id="introduction">Introduction</h3>
<ul>
  <li>A very good section, particularly the second and third paragraph, revisiting how others reconstruct transmission events and limitation. Should re-read sometime later.</li>
  <li>Outbreaker (<a href="https://pubmed.ncbi.nlm.nih.gov/24465202/">PMID: 24465202</a>) was compared to SCOTTI. Outbreaker did not model within-host diversity.</li>
  <li>One <strong>limitation</strong> of SCOTTI: do not model transmission bottlenecks.</li>
  <li>I found may references of this paper can be quite useful, e.g.,
    <ul>
      <li>About misleading inference if <strong>NOT</strong> modeling within-host diversity:
        <ul>
          <li>Worby CJ, Lipsitch M, Hanage WP. Within-host bacterial diversity hinders accurate reconstruction of transmission networks from genomic distance data. PLoS Comput Biol. 2014; 10:e1003549. doi: 10. 1371/journal.pcbi.1003549 PMID: 24675511</li>
          <li>Romero-Severson E, Skar H, Bulla I, Albert J, Leitner T. Timing and order of transmission events is not directly reflected in a pathogen phylogeny. Molecular biology and evolution. 2014; 31(9):2472–2482. doi: 10.1093/molbev/msu179 PMID: 24874208</li>
        </ul>
      </li>
      <li>Other works considering within-host diversity, but did not considered unsampled infections:
        <ul>
          <li>Ypma RJ, van Ballegooijen WM, Wallinga J. Relating phylogenetic trees to transmission trees of infectious disease outbreaks. Genetics. 2013; 195(3):1055–1062. doi: 10.1534/genetics.113.154856 PMID: 24037268</li>
          <li>Didelot X, Gardy J, Colijn C. Bayesian inference of infectious disease transmission from whole-genome sequence data. Molecular biology and evolution. 2014; 31(7):1869–1879. doi: 10.1093/molbev/msu121 PMID: 24714079</li>
          <li>Hall M, Woolhouse M, Rambaut A. Epidemic reconstruction in a phylogenetics framework: transmission trees as partitions of the node set. PLoS Comput Biol. 2015; 11(12):e1004613. doi: 10.1371/journal.pcbi.1004613 PMID: 26717515</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><img src="/files/2024-12-28-structured-coalescent/Screenshot%202025-01-05%20at%2017.01.04.webp" alt="" /></li>
</ul>

<h3 id="methods-1">Methods</h3>

<ul>
  <li>
    <p>SCOTTI aims to reconstruct who infected whom and when in a scenario with multiple potential hosts (populations). This is done by:</p>

    <ul>
      <li>Inferring a phylogeny $T$ (the genealogy of the sampled pathogen sequences).</li>
      <li>Tracing how lineages “migrate” (or “transmit”) between different hosts over time.</li>
      <li>Estimating parameters like:
        <ul>
          <li>Mutation/substitution parameters $\mu$ for the pathogen.</li>
          <li>Migration (transmission) rate $m$ among hosts.</li>
          <li>Within‐host population sizes $N_e$.
​</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>The approximate structured coalescent model is based on BASTA.
    <ul>
      <li>To include the epidemiological data (host exposure time), introduction time ($d_i$) and removal time ($d_r$) were considered for each host. $[d_r, d_i]$ is the time interval when the host can host any lineage. The model assumes that $d_i$ and $d_r$ are provided for each host.</li>
      <li>$\vec{E}$ is the collection of exposure times.</li>
      <li>The number of hosts/populations $n_D$ is not fixed, but estimated within a specified range.</li>
      <li>Migration rate $m$ is assumed the same between each pair of hosts for the time that they are both exposed to.</li>
      <li>All demes have the same and constant effective population size $N_e$.</li>
      <li>This means that we assume that transmission is a <em>priori</em> equally likely between any pair of exposed hosts, and that all hosts have equal, and constant, within-host pathogen evolution dynamics.</li>
      <li>Equal population sizes and migration rates can be relaxed for known contact networks.</li>
    </ul>
  </li>
  <li>Note that every sample have only one representative sequence, rather than a set of sequences representing the within-host haplotype diversity. <strong>Deep sequencing data is not utilized in this example study</strong>.</li>
  <li>
    <p>A bit about $P_{l,\alpha_{i},d}$, the probability that lineage $l$ is in host (deme) $d$ at time $\alpha_{i}$:</p>

\[P_{l, \alpha_i, d} = P_{l, \alpha_{i-1}, d} \underbrace{\left( \frac{1}{D_i} + \frac{D_i - 1}{D_i} e^{-\tau_i m} \right)}_{\text{Case 1: was in } d} + \left(1 - P_{l, \alpha_{i-1}, d}\right) \underbrace{\left( \frac{1}{D_i} - \frac{1}{D_i} e^{-\tau_i m} \right)}_{\text{Case 2: was not in } d},\]

    <p>simply adds these two scenarios:</p>

    <ol>
      <li>If it was <strong>already in</strong> $d$ at $\alpha_{i-1}$, the chance it stays or “effectively returns” to $d$ by $\alpha_i$.</li>
      <li>If it was <strong>not in</strong> $d$, the chance it migrates (at least once) into $d$ by $\alpha_i$.</li>
    </ol>

    <p>Notice:</p>

    <ul>
      <li>$\frac{1}{D_i} + \frac{D_i - 1}{D_i} e^{-\tau_i m} = e^{-\tau_i m} \times 1+(1-e^{-\tau_i m})\times \frac{1}{D_i}$ = Probability of “remain in host $d$” over $\tau_i$.</li>
      <li>$\frac{1}{D_i} - \frac{1}{D_i} e^{-\tau_i m} = \frac{1}{D_i}\left(1 - e^{-\tau_i m}\right)$ = Probability of “migrate from a different host into $d$” at least once.</li>
    </ul>
  </li>
  <li>
    <p>Simulation Setup</p>

    <ol>
      <li><strong>Two Fixed Transmission Histories</strong>
        <ul>
          <li><strong>Transmission History 1</strong>: 20 UK farms infected with FMDV in 2001 (from [15]).</li>
          <li><strong>Transmission History 2</strong>: HIV outbreak (1980–1983) involving one male index case and multiple partners (from [8]).</li>
        </ul>
      </li>
      <li><strong>Within-Host Coalescent Model</strong>
        <ul>
          <li>Each infected host is modeled with a <strong>constant effective population size</strong> $N_e$.</li>
          <li>Lineages within a host coalesce according to a standard coalescent at rate $\tfrac{1}{N_e}$.</li>
        </ul>
      </li>
      <li><strong>Transmission Bottlenecks (Simulated, Not Modeled by SCOTTI/Outbreaker)</strong>
        <ul>
          <li><strong>Weak Bottleneck</strong> ($\sim N_e$ generations of drift):
            <ul>
              <li>Two lineages have $\approx 63\%$ chance of coalescing; effectively <strong>larger</strong> fraction of the donor population survives in the recipient.</li>
            </ul>
          </li>
          <li><strong>Strong Bottleneck</strong> ($\sim 100N_e$ generations of drift):
            <ul>
              <li>Two lineages almost surely coalesce; effectively <strong>smaller</strong> fraction of the donor population passes on.</li>
            </ul>
          </li>
        </ul>
      </li>
      <li><strong>Simulation Settings</strong>
        <ul>
          <li>Factors varied:
            <ol>
              <li><strong>Weak vs Strong Bottleneck</strong></li>
              <li><strong>Transmission History 1 vs 2</strong></li>
              <li><strong>One vs Two Samples per Host</strong></li>
              <li><strong>First vs Second Transmission History</strong> (the authors label them “history 1” or “history 2”; they also mention “first vs second” might relate to repeated usage).</li>
            </ol>
          </li>
          <li>Each factor has <strong>two</strong> levels, giving $2 \times 2 \times 2 \times 2 = 8$ <strong>groups of scenarios</strong>.</li>
        </ul>
      </li>
      <li><strong>Further Variants per Scenario</strong>
        <ul>
          <li>For each of these 8 scenarios (“base”), they also define <strong>eight</strong> sub-scenarios (the base + 7 variants), leading to <strong>64 distinct</strong> simulation settings:
            <ul>
              <li><strong>Long infection</strong>: 5× longer intervals than usual ($\approx 10N_e$ generations).</li>
              <li><strong>Abundant genetic</strong>: Alignment length = 15,000 bp (instead of 1,500 bp).</li>
              <li><strong>Early sampling</strong>: Samples at 5% of the infection interval.</li>
              <li><strong>Late sampling</strong>: Samples at the end of infection.</li>
              <li><strong>Few missing</strong>: One unobserved host.</li>
              <li><strong>Many missing</strong>: Three unobserved hosts.</li>
              <li><strong>Inaccurate epi</strong>: SCOTTI is given a broader exposure interval than the true one.</li>
            </ul>
          </li>
        </ul>
      </li>
      <li><strong>Number of Datasets</strong>
        <ul>
          <li>Each of the <strong>64</strong> scenario/variant combinations is replicated <strong>100 times</strong>, resulting in <strong>6,400 total simulated datasets</strong> (64 × 100).</li>
        </ul>
      </li>
      <li><strong>HKY Substitution Model</strong>
        <ul>
          <li>All simulations use an <strong>HKY</strong> nucleotide substitution model with:
            <ul>
              <li>$\kappa = 3 \times 10^{-3}$ substitution rate per base <strong>per $N_e$ generations</strong> (unless otherwise stated).</li>
              <li><strong>Uniform</strong> nucleotide frequencies.</li>
            </ul>
          </li>
          <li>SCOTTI and Outbreaker are both run <strong>using the HKY model</strong> for inferring the phylogeny from the simulated alignments.</li>
        </ul>
      </li>
      <li><strong>Methods Used for Inference</strong>
        <ul>
          <li><strong>SCOTTI</strong>:
            <ul>
              <li>Approximates structured coalescent with possible nonsampled hosts (0–2) and runs up to $10^6$ MCMC iterations.</li>
            </ul>
          </li>
          <li><strong>Outbreaker</strong>:
            <ul>
              <li>Also uses HKY, but typically can only handle <strong>one sample per host</strong>.</li>
            </ul>
          </li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h3 id="results">Results</h3>

<ul>
  <li>The accuracy of SCOTTI remains consistently high,with the noticeable exception 
of the case in which sampling occurs very early in infection.</li>
  <li>As we increase the within-host genetic variability, we achieve this by reducing the effect of the transmission bottleneck and increasing the within-host effective population size. We notice that the accuracy of the point estimate of SCOTTI goes remarkably down. However, calibration remains at acceptable levels.</li>
  <li>However, providing two samples per host increases the accuracy. This supports the idea that, if available, many sequences from each host could provide sufficient information. Deep sequencing from each host could also provide sufficient information.</li>
  <li>SCOTTI can investigate a dataset of 50 hosts and 2 samples per host in 1-2 hours using a single processor.</li>
</ul>

<h2 id="the-structured-coalescent-and-its-approximations-by-nicola-f-müller-et-al-on-molecular-biology-and-evolution-2017"><a href="https://academic.oup.com/mbe/article/34/11/2970/3896419">The Structured Coalescent and Its Approximations</a> by Nicola F. Müller <em>et al.</em> on Molecular Biology and Evolution, 2017.</h2>

<h3 id="abstract-2">Abstract</h3>
<ul>
  <li>We present <strong>an exact numerical solution</strong> to the structured coalescent that does not require the inference of migration histories. Although this solution is computationally unfeasible for large data sets, it clarifies the assumptions of previously developed approximate methods and allows us to provide an improved approximation to the structured coalescent.</li>
</ul>

<h3 id="introduction-1">Introduction</h3>
<ul>
  <li><em>Mugration</em> assumes the migration process to be independent of the tree generating process. In other words, it is assumed that the shape of a phylogeny is not in any way influenced by the migration process.</li>
  <li>Structured coalescent requires the state (or location) of any ancestral lineage in the phylogeny at any time to be inferred.</li>
  <li>Marginialization approaches (seek to marginalize over all possible migration histories by treating lineage states probabilistically instead of using MCMC based sampling) allows for the analysis of larger data sets.
    <ul>
      <li>SISCO (<a href="https://academic.oup.com/genetics/article/190/1/187/6063310">Volz 2012</a>)</li>
      <li>BASTA (<a href="https://journals.plos.org/plosgenetics/article?id=10.1371/journal.pgen.1005421">De Maio 2015</a>)</li>
    </ul>
  </li>
  <li>ESCO is the exact structured coalescent.
    <ul>
      <li>It requires solving a number of differential equations that is proportional to the “number of different states” to the power of the “number of coexisting lineages”, $m^n$.</li>
    </ul>
  </li>
  <li>MASCO is the marginal lineage states approximation of the structured coalescent.
    <ul>
      <li>Reduce the number of differential equations that have to be solved between events to the “number of states” times “number of lineages”, but ignores any correlations between lineages.</li>
    </ul>
  </li>
  <li>SISCO (state independence approximation of the structured coalescent) requires the additional assumption (compared to MASCO) that the state of a lineage evolves independently of the coalescent process between events.
    <ul>
      <li>This means that changes in the probabilities of lineages being in a certain state are only dependent on the migration rates, and are completely independent of other lineages in the phylogeny.</li>
    </ul>
  </li>
</ul>

<h3 id="methods-2">Methods</h3>

<p>The methods part is <strong>phenomenal</strong>, I don’t know it is because I have read so many papers on structured coalescent, or it is just well written. It clearly demonstrated how the interval probability, colaescence probability, and sampling probability are calculated, for ESCO, MASCO, and SISCO.</p>

<p>You shold refer back to the original paper, and the associated supplementary material, for the details.</p>

<h2 id="mascot-parameter-and-state-inference-under-the-marginal-structured-coalescent-approximation-by-nicola-de-maio-et-al-on-bioinformatics-2018"><a href="https://academic.oup.com/bioinformatics/article/34/22/3843/5001387">MASCOT: parameter and state inference under the marginal structured coalescent approximation</a> by <em>Nicola De Maio et al.</em> on Bioinformatics, 2018.</h2>

<h3 id="abstract-3">Abstract</h3>

<p>This study extended the previous work by calculating the probability of the state of the internal nodes of the phylogenetic tree, and now the method can handle larger datasets, including 433 H3N2 sequences from five locations.</p>

<h3 id="methods-3">Methods</h3>

<ul>
  <li>They used the backwards/forwards algorithm to calculate the probability of the state of the internal nodes. First going backwards in time, reaching the root, then going forwards, comparing and scaling the backwards probability for internal nodes then we get the full probability of the state of the internal nodes.</li>
  <li><img src="/files/2024-12-28-structured-coalescent/Screenshot%202025-01-09%20at%2018.58.52.png" alt="" /></li>
</ul>

<h3 id="results-1">Results</h3>

<ul>
  <li>With backward/forward algorithm, accuracy for internal node state probability is improved.</li>
</ul>

<h3 id="discussion">Discussion</h3>

<ul>
  <li>Insights for Future Studies:
    <ul>
      <li>Incorporating Explicit Sampling:
        <ul>
          <li>Future methods could explicitly incorporate sampling of migration histories or the number of state changes, using algorithms like those of Minin and Suchard (2007, 2008).</li>
          <li>This would ensure probabilistic consistency with forward state probability equations.</li>
        </ul>
      </li>
      <li>Parameter Reduction:
        <ul>
          <li>Inferring all migration rates and population sizes for large datasets is computationally intensive. Strategies include:
            <ul>
              <li>Bayesian Search Variable Selection (Lemey et al., 2009): To select influential variables.</li>
              <li>Generalized Linear Models (GLMs) (Lemey et al., 2014): To model migration rates based on covariates, reducing the need to infer all migration rate parameters.</li>
            </ul>
          </li>
        </ul>
      </li>
      <li>Large datasets pose computational challenges.
        <ul>
          <li>A suggested approximation:
\(\sum_{k=1, k\ne i}^n \approx \sum_{k=1}^m,\)
where lineages share the same transition probabilities.</li>
          <li>This approach reduces the number of ordinary differential equations (ODEs) that need to be solved.</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h2 id="inferring-time-dependent-migration-and-coalescence-patterns-from-genetic-sequence-and-predictor-data-in-structured-populations"><a href="https://academic.oup.com/ve/article/5/2/vez030/5549805">Inferring time-dependent migration and coalescence patterns from genetic sequence and predictor data in structured populations</a></h2>

<ul>
  <li>MSCOT-GLM: This paper further extends the MASCOT with GLM to infer the predictors for time-varying migration rates and effective population sizes, using predictor data (like travel pattern, weekly cases).</li>
  <li>Similar to DTA-GLM (<a href="https://journals.plos.org/plospathogens/article?id=10.1371/journal.ppat.1003932">Lemey et al. 2014</a>). In DTA (mugration), since the migration process is independently modelled with the coalescent process, thus the transmission dynamics in different sub-populations cannot be quantified.</li>
  <li>Similar to DTA-GLM, MSCOT-GLM define the migration rates, and effective population size, as log-linear combinations of coefficients, indicators and time varying predictors.</li>
</ul>

<h3 id="methods-4">Methods</h3>

<ul>
  <li>
    <p>Instead of inferring the effective population size $N_e(t)$ of state $a$ at time $t$ directly, we define it as a linear combination of $c$ different predictors $p_{N_e}(t)$, coefficients $\beta_{N_e}$, and indicators $\sigma_{N_e}$:</p>

\[N_e^a(t) = \beta_{N_e} \exp \left( \sum_{i=1}^c \beta_{N_e}^i \sigma_{N_e}^i p_{N_e^a}^i(t) \right).\]
  </li>
  <li>The coefficients $\beta^{i}_{N_e}$ use normal priors.</li>
  <li>The indicators $\sigma_{N_e}^i$ can be 0 or 1, indicating whether the predictor is used in the model.</li>
  <li>The number of cases when $\sigma_{N_e}^i =1$ is distributed as a given prior distribution. Typically, the prior favors a smaller number of active predictors.</li>
  <li>The outside $\beta_{N_e}$ is the overall scaling factor, if every indicator is $0$, then the effective population size is $\beta_{N_e}$.</li>
  <li>Similar for migration rates.</li>
</ul>

<h3 id="results-2">Results</h3>
<ul>
  <li>Seems can correctly infer the coefficients for the predictors, under simulation.</li>
  <li>Seems that for indicators are poorer.</li>
  <li>They did not showed the inffered time-varying effective population size in Figure 3, instead they only show the weekly new cases. I am curious.</li>
  <li>I thought that before this paper, the $N_e$ is assumed constant in MASCOT?</li>
</ul>

<h3 id="discussion-1">Discussion</h3>

<ul>
  <li>Similar GLM approaches as presented here could be applied to inform birth, death, migration, and sampling rates through time for structured birth-death models (<a href="https://royalsocietypublishing.org/doi/10.1098/rstb.2012.0198">Stadler and Bonhoeffer 2013</a>; <a href="https://academic.oup.com/mbe/article/33/8/2102/2578541">Kuhnert et al. 2016</a>).</li>
</ul>

<h2 id="mascot-skyline-integrates-population-and-migration-dynamics-to-enhance-phylogeographic-reconstructions-by-nicola-f-muller-et-al-on-biorxiv-2024"><a href="https://www.biorxiv.org/content/10.1101/2024.03.06.583734v2">MASCOT-Skyline integrates population and migration dynamics to enhance phylogeographic reconstructions</a> by Nicola F. Muller et al. on bioRxiv, 2024.</h2>

<ul>
  <li>The <strong>spatial</strong> and <strong>temporal</strong> transmission dynamics should be inferred simultaneously.</li>
  <li><strong>MASCOT-Skyline</strong> allows us to jointly infer spatial and temporal transmission dynamics of infectious diseases using Markov chain Monte Carlo inference.</li>
  <li>Skyline and skygrid methods are non-parametric methods to estimate the effective population size through time.</li>
</ul>

<h3 id="methods-5">Methods</h3>

<ul>
  <li>TODO</li>
</ul>

<h3 id="results-3">Results</h3>

<ul>
  <li>Nonparametric population dynamics and migration patterns can be recovered from phylogenetic trees</li>
  <li>Assumptions about the population dynamics drive ancestral state reconstruction in structured coalescent models</li>
  <li>Population structure biases population dynamic inference</li>
  <li>Sampling bias impacts ancestral state reconstructions</li>
  <li>Modeling population size dynamics is necessary to reconstruct migration rates
    <ul>
      <li>Although migration rates can be predicted using GLM (<a href="#inferring-time-dependent-migration-and-coalescence-patterns-from-genetic-sequence-and-predictor-data-in-structured-populations">previous paper</a>), this still relies on the models’ ability to quantify migration rates accurately.</li>
    </ul>
  </li>
</ul>

<hr />]]></content><author><name>Haogao Gu</name><email>work@guhaogao.com</email></author><category term="Paper digest" /><category term="Coalescent theory" /><category term="Phylogenetics" /><summary type="html"><![CDATA[I wanted to get in more details about the structured coalescent model, here I record some notes when I read related papers.]]></summary></entry><entry><title type="html">Paper digest: Efficient Bayesian inference under the structured coalescent (Timothy G. Vaughan et al., 2014)</title><link href="https://guhaogao.com/posts/2025-01-03/structured-coalescent2" rel="alternate" type="text/html" title="Paper digest: Efficient Bayesian inference under the structured coalescent (Timothy G. Vaughan et al., 2014)" /><published>2025-01-03T00:00:00+08:00</published><updated>2025-01-03T00:00:00+08:00</updated><id>https://guhaogao.com/posts/2025-01-03/Sturctured_coalescent2</id><content type="html" xml:base="https://guhaogao.com/posts/2025-01-03/structured-coalescent2"><![CDATA[<p>This is the paper for MultiTypeTree.</p>

<blockquote>
  <p>In this article, we present a new MCMC sampler capable of sampling from posterior distributions over structured trees: timed phylogenetic trees in which lineages are associated with the distinct subpopulation in which they lie. The sampler includes a set of MCMC proposal functions that offer significant mixing improvements over a previously published method.</p>
</blockquote>

<p>Vaughan, T. G., et al. (2014). Efficient Bayesian inference under the structured coalescent. <em>Bioinformatics</em>. <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC4207426/">Link</a></p>

<h2 id="introduction">Introduction</h2>
<ul>
  <li>Two MCMC schemes have been proposed for the structured coalescent:
    <ul>
      <li>The first is the method developed by Beerli and Felsenstein (Beerli, 2006; Beerli and Felsenstein, 1999, 2001), implemented in the software package Migrate-n. This approach uses a single proposal function that updates the structured tree by dissolving a randomly selected edge and drawing a new edge through simulation from the structured coalescent, conditioned on the remaining edges.</li>
      <li>The second scheme, proposed by Ewing et al. (2004), employs a set of simple and efficient proposal functions focused exclusively on migration events within the structured genealogy. Combined with methods for exploring the space of unstructured trees (Drummond et al., 2002), Ewing et al. demonstrated that this MCMC algorithm can not only jointly infer structured trees and migration parameters but also leverage serially sampled data to estimate absolute migration rates.</li>
    </ul>
  </li>
  <li>These two methods are slow. In this article, the authors present a new set of MCMC proposal functions (or ‘operators’) designed to efficiently utilize serially sampled sequence data for inferring the complete structured tree and associated model parameters, including mutation rates, within the structured coalescent framework.</li>
</ul>

<h2 id="mathematical-background">Mathematical Background</h2>

<h3 id="definitions">Definitions</h3>

<ul>
  <li>A structured tree $\mathcal{T}$ of n leaves is a fully resolved, rooted and timed phylogenetic tree. $\mathcal{T}=(V, E, \mathbf{t}, M)$. $V$ is the set of nodes, $E$ is the set of edges, $\mathbf{t}$ is the vector of node times, and $M$ is the set of migration events. The demes are represented by a set $D$.</li>
  <li>The final element in $\mathcal{T}$ is the one that is unique to structured trees and is defined by $M = \lbrace\varphi_{\langle i,j \rangle} \mid \langle i,j \rangle \in E\rbrace$, where each function $\varphi_{\langle i,j \rangle} : [t_i, t_j] \to D$ is piecewise constant and defined such that $\varphi_{\langle i,j \rangle}(t)$ is the type associated with the time $t$ on edge $\langle i,j \rangle \in E$. Such a tree is illustrated in Figure 1.
    <ul>
      <li><img src="https://cdn.ncbi.nlm.nih.gov/pmc/blobs/8f32/4207426/97b8727277f5/btu201f1p.jpg" alt="" /></li>
    </ul>
  </li>
</ul>

<h3 id="bayseian-inference-framework">Bayseian inference framework</h3>

<ul>
  <li>Sampled individuals are represented by the set $I$, the aligned sequences by the set $S = \lbrace s_i \vert i \in I\rbrace$, the sampling dates by the set $\mathbf{t}_I = \lbrace\mathbf{t}_i \vert i \in I\rbrace$, $\mathbf{t}_Y$ is the vector of internal node times, and the sampling locations by the set $L = \lbrace l_i \vert i \in I\rbrace$. In addition to the parameters of primary interest, $m$ and $\theta$, $\mu$ the nucleotide substitution rate matrix, and $M$ the migration history of lineages in the tree, i.e., the timing, source, sink, and lineage involved in each migration event.
    <ul>
      <li>
        <p>Formally, the target of inference is the posterior distribution of the parameters given the data:</p>

\[P(E, \mathbf{t}_Y, M, \mu, m, \theta \mid S, \mathbf{t}_I, L) 
\propto P_F(S \mid E, \mathbf{t}, \mu) P(E, \mathbf{t}_Y, M \mid \mathbf{t}_I, L, m, \theta) P(\mu, m, \theta).\]
      </li>
      <li>
        <p>The first term is the phylogenetic tree likelihood, the second term is the structured coalescent likelihood, and the third term is the prior distribution of the parameters.</p>
      </li>
    </ul>
  </li>
</ul>

<h3 id="the-structured-coalescent-probability-density">The structured coalescent probability density</h3>
<ul>
  <li>
    <p>The probability density of a structured tree:</p>

\[P(E, t_Y, M \mid t_I, L, m, \theta) = 
\exp \left[
-\sum_{\alpha=1}^B \tau_\alpha 
\sum_{d \in D}
\left(
\binom{k_{\alpha,d}}{2} \frac{1}{\theta_d} 
+ k_{\alpha,d} 
\sum_{d' \in D \setminus \lbrace d \rbrace} m_{dd'}
\right)
\right]
\times 
(m_{dd'})^{v^m_{dd'}}
\left(\frac{1}{\theta_d}\right)^{v^c_d}.\]

    <ul>
      <li>The exponential term is the probability of waiting time for the first event to happen</li>
      <li>Times the probability of the actual events (migrations/coalescences) that do occur.</li>
    </ul>
  </li>
  <li>Heterochronous (Serial) Sampling
    <ul>
      <li>The model allows leaf nodes (samples) at different times, which are “sampling events.”</li>
      <li>The formula extends standard structured coalescent approaches to handle tips sampled at multiple points in time (rather than all at the present).</li>
    </ul>
  </li>
  <li>
    <p>There is another formulation from <a href="https://journals.plos.org/plosgenetics/article?id=10.1371/journal.pgen.1005421">New Routes to Phylogeography: A Bayesian Structured Coalescent Approximation</a> by <em>Nicola De Maio et al.</em> on PLOS Genetics, 2015, which I think is more intuitive.</p>

    <ol>
      <li><strong>Basic Idea</strong><br />
In the structured coalescent, lineages can:
        <ul>
          <li><strong>Coalesce</strong> within the same deme (subpopulation).</li>
          <li><strong>Migrate</strong> from one deme to another.</li>
          <li><strong>Be sampled</strong> at known times (for heterochronous datasets).</li>
        </ul>

        <p>We divide the entire time span (from root to present) into consecutive intervals $\tau_i$.<br />
Each interval ends when an event <strong>actually</strong> occurs (coalescence, migration, or sampling).</p>
      </li>
      <li><strong>Two Components per Interval</strong><br />
For each interval $i$ of length $\tau_i$, the probability contribution $L_i$ has:
        <ol>
          <li>An <strong>exponential term</strong> for waiting time during $\tau_i$.</li>
          <li>A <strong>multiplier</strong> $E_i$ for “which event occurs” at the end of $\tau_i$.</li>
        </ol>

        <p>Thus:
\(L_i 
  \;=\; 
  \exp\!\Bigl[
    -\,\tau_i 
    \sum_{d\in D} \Bigl(
      \binom{k_{i,d}}{2} \,\tfrac{1}{\theta_d}
      \;+\;
      k_{i,d} \sum_{d'\neq d} m_{dd'}
    \Bigr)
  \Bigr]
  \;\times\;
  E_i,\)
where:</p>
        <ul>
          <li>$k_{i,d}$ is the number of lineages in deme $d$ during interval $i$.</li>
          <li>$\theta_d$ is the scaled population size for deme $d$.</li>
          <li>$m_{dd’}$ is the rate of migration from deme $d’$ to $d$.</li>
        </ul>
      </li>
      <li><strong>Interpreting the Exponential Term</strong>
        <ul>
          <li>$\exp[-(\text{total rate}) \times \tau_i]$ is the probability that <strong>no</strong> coalescence or migration events happen before $\tau_i$.</li>
          <li>The total rate is the sum of <strong>coalescent rates</strong> ($\binom{k_{i,d}}{2}\,\frac{1}{\theta_d}$) and <strong>migration rates</strong> ($k_{i,d}\,\sum_{d’\neq d} m_{dd’}$) across all demes $d$.</li>
        </ul>
      </li>
      <li><strong>Event Probability Factor $(E_i)$</strong><br />
After waiting $\tau_i$ with no events, <strong>one</strong> event happens at the end of interval $i$.
        <ul>
          <li><strong>Coalescence</strong> in deme $d$ adds a factor $\tfrac{1}{\theta_d}$.</li>
          <li><strong>Migration</strong> from $d’$ to $d$ adds a factor $m_{dd’}$.</li>
          <li><strong>Sampling</strong> contributes a factor of 1 (it does not arise from a “rate” in the same sense, but rather is determined by the sampling design).</li>
        </ul>
      </li>
      <li><strong>Multiplying Over All Intervals</strong><br />
We typically write the full likelihood for the entire genealogy as the product of the $L_i$ factors across intervals $i = 1, 2, \dots, B$:
\(P(\text{structured tree}) 
  \;=\; 
  \prod_{i=1}^B L_i.\)
This product describes both:
        <ol>
          <li>The waiting times (no events) in each interval.</li>
          <li>The specific type of event that ends each interval.</li>
        </ol>
      </li>
      <li><strong>Why It Works</strong>
        <ul>
          <li><strong>Poisson Process Logic</strong>: Coalescent and migration follow Poisson processes. The probability of no event over $\tau_i$ is an exponential.</li>
          <li><strong>Single Event at Interval End</strong>: We account for the single event by multiplying the appropriate rate parameter (or 1 for sampling).</li>
          <li><strong>Structured Constraint</strong>: Coalescence only occurs when lineages share the same deme. Migration changes deme assignment. Sampling is taken as known.</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<h2 id="mcmc-sampling-algorithm">MCMC Sampling Algorithm</h2>

<ul>
  <li><strong>Structured Tree Operators</strong>: Operators adapted from Drummond et al. (2002) include:
    <ul>
      <li>Wilson-Balding Move: Adjusts subtree attachment.</li>
      <li>Subtree Exchange Move: Switches subtree connections.</li>
      <li>Node Height Shifting Move: Adjusts internal node heights.</li>
      <li>Tree Height Scaling Move: Scales overall tree height.</li>
    </ul>
  </li>
</ul>

<h2 id="implementation-and-application">Implementation and application</h2>

<ul>
  <li>The authors then validate the performance of the model using simulated data.
    <ul>
      <li>
        <p><strong>Inference from Simulated Data</strong>: The implemented MCMC sampler was tested using simulated data to validate its ability to recover evolutionary and demographic parameters accurately under known conditions.</p>
      </li>
      <li><strong>Data Simulation Procedure</strong>:
        <ol>
          <li>A structured coalescent model was defined with specific types ($D$), immigration rate matrix ($m$), and population size vector ($\theta$).</li>
          <li>A <strong>128-taxon structured coalescent tree</strong> was simulated using the MASTER tool, with leaf node times spread across $t = 0, 1, 2, 3$, and leaf types distributed evenly across $D$.</li>
          <li>A <strong>2 kb nucleotide sequence</strong> was evolved along the tree using the HKY substitution model ($\mu_0 = 0.005$ substitutions/site/unit time).</li>
          <li>MCMC sampling used log-normal prior distributions ($\ln \mathcal{N}(0, 4)$) for parameters $\kappa$, $\mu_0$, $m$, and $\theta$, with $10^8$ MCMC steps and an effective sample size (ESS) of 1164 for the slowest-mixing parameter.</li>
        </ol>
      </li>
      <li><strong>Table 1</strong>: Shows <strong>95% HPD coverage fractions</strong> for inferred parameters ($\theta$, $m$, $\mu_0$, $\kappa$) across different structured population models with 2, 3, and 4 demes.
        <ul>
          <li>High coverage percentages were observed for most parameters in simpler models (2 or 3 demes).</li>
          <li>In the 4-deme model, non-zero elements of $m$ were reliably estimated, but increasing the number of demes reduced the overall signal strength.</li>
        </ul>
      </li>
      <li><strong>Insights</strong>:
        <ul>
          <li>Increasing the number of demes without increasing data negatively impacts inference accuracy.</li>
          <li>For datasets with <strong>128 taxa</strong>, the method performs well for up to <strong>3–4 demes</strong>, beyond which additional constraints on the model are necessary for reliable inference. This limitation arises when estimating all migration rates with non-informative priors.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>
    <p>They also compare the performance of their operators with the existing methods, concluding that the ‘effective sample rate’ (ESR) is higher.</p>
  </li>
  <li>Finally, they apply the model to a real dataset of global flu epidemics.
    <ul>
      <li><img src="/files/2024-12-28-structured-coalescent/Screenshot%202025-01-03%20at%2018.57.17.png" alt="" /></li>
    </ul>
  </li>
</ul>

<hr />]]></content><author><name>Haogao Gu</name><email>work@guhaogao.com</email></author><category term="Paper digest" /><category term="Coalescent theory" /><category term="Phylogenetics" /><summary type="html"><![CDATA[This is the paper for MultiTypeTree.]]></summary></entry><entry><title type="html">Course notes: coalescent theory and structured coalescent basics</title><link href="https://guhaogao.com/posts/2024-12-28/Structured_coalescent" rel="alternate" type="text/html" title="Course notes: coalescent theory and structured coalescent basics" /><published>2024-12-28T00:00:00+08:00</published><updated>2025-01-02T00:00:00+08:00</updated><id>https://guhaogao.com/posts/2024-12-28/Sturctured_coalescent</id><content type="html" xml:base="https://guhaogao.com/posts/2024-12-28/Structured_coalescent"><![CDATA[<p>I wanted to get in more details about the structured coalescent model, here I record some notes when I watch introductory videos.</p>

<h1 id="coalescent-quick-recap">Coalescent quick recap</h1>

<p>It is a series of short <a href="https://www.youtube.com/playlist?list=PLXbnX6Ihecnmngifb2E_L3nqwR2tiLcTu">Youtube videos by Scott Roy</a>.</p>

<ul>
  <li>Coalescent is about mathematically trace back in time to find a appropriate tree shape / genealogy that can explain the observed data.</li>
  <li>Geometric Series Summation: $\sum_{i=0}^{\infty}{r^i} = \frac{1}{1-r}$ (note that $0&lt;r&lt;1$, and r can be a probability of coalescence). So that $\sum_{i=0}^{\infty}{(1-p)^i} = \frac{1}{p}$.</li>
  <li>Time for $n=2$ individuals to coalescence is a classic waiting problem:
\(P(t)=(\frac{N-1}{N})^{t-1}\frac{1}{N}\\
E(t)=\frac{1}{\frac{1}{N}}=N\)</li>
  <li>
    <p>Expected waiting time for coalescence (discrete):</p>

\[\begin{align*}
E[t] &amp;= 1p+2p(1-p)+3p(1-p)^2+... \\
&amp;=\sum_{i=0}^{\infty}{(i+1)p(1-p)^i} =\sum_{i=1}^{\infty}{ip(1-p)^i} =\sum_{i=0}^{\infty}{ip(1-p)^i}\\
&amp;=\sum_{i=0}^{\infty}{ip(1-p)^i} + \sum_{i=0}^{\infty}{1p(1-p)^i}\\
&amp;=(1-p)\sum_{i=0}^{\infty}{ip(1-p)^{i-1}}+p\sum_{i=0}^{\infty}{(1-p)^i}\\
&amp;=(1-p)E[t]+p\frac{1}{p}\\
&amp;=\frac{1}{p}
\end{align*}\]
  </li>
  <li>Time for $n&gt;2$ individuals to coalescence:
    <ul>
      <li>First coalescence:</li>
    </ul>

\[E(t)=\frac{1}{\frac{n\choose2}{N}}=\frac{N}{n\choose2}\]

    <ul>
      <li>Second coalescence:</li>
    </ul>

\[E(t)=\frac{N}{n-1\choose2}\]

    <ul>
      <li>Third coalescence:</li>
    </ul>

\[E(t)=\frac{N}{n-2\choose2}\]

    <ul>
      <li>…</li>
      <li>Such that the coalescence time is getting longer for deep branches.</li>
    </ul>
  </li>
  <li>
    <p>To jointly model mutation process and coalescent process, we need to consider the mutation rate $\mu$ and coalescent rate $\lambda$. The expected number of mutations before the first coalescence is:</p>

\[\begin{align*}
E(mut)&amp;=\frac{\mu}{\lambda}\\
&amp;=\frac{n\mu}{n\frac{n\choose2}{N}}\\
&amp;=\frac{2N\mu}{n-1}.
\end{align*}\]

    <p>As a result, the expected number of mutations increases backwards in time (as $n$ is decreasing).</p>
  </li>
  <li><a href="https://www.youtube.com/watch?v=fi5Vd83NA4U&amp;list=PLXbnX6Ihecnmngifb2E_L3nqwR2tiLcTu&amp;index=13">Coalescent frequency site distribution</a> can be obtained as a neutral model for genetic variation. Comparing the observed FSD with the expected FSD can help to infer the selection pressure.</li>
  <li><a href="https://www.youtube.com/watch?v=rHRojlmcM8I&amp;list=PLXbnX6Ihecnmngifb2E_L3nqwR2tiLcTu&amp;index=14&amp;pp=iAQB">The expected number of singletons</a> and <a href="https://www.youtube.com/watch?v=inTcOOq18ko&amp;list=PLXbnX6Ihecnmngifb2E_L3nqwR2tiLcTu&amp;index=18&amp;pp=iAQB">the expected ratio between the number of singletons and the number of SNPs</a> surprisingly can be represented by simple formulas, after canceling out the terms. These can be useful for inferring evolutionary history.</li>
  <li>The probability of particular coalescent tree shapes can also be calculated, often also resulted in simple formulas, as exampled <a href="https://www.youtube.com/watch?v=R9Sp6P1ENeo&amp;list=PLXbnX6Ihecnmngifb2E_L3nqwR2tiLcTu&amp;index=17&amp;pp=iAQB">here</a>.</li>
  <li>There is also ways to work out the probability and expected tree lengths for <strong>coalescent subdivisions</strong>, as exampled <a href="https://www.youtube.com/watch?v=LCbpXCHdtTk&amp;list=PLXbnX6Ihecnmngifb2E_L3nqwR2tiLcTu&amp;index=23">here</a>. After getting the formula numerically, we can easily tell what will happen e.g. if migration rates is much higher than the coalescent rate (or vice versa).</li>
</ul>

<h1 id="coalescent-theory-by-john-wakeley-on-a-workshop-second-bangalore-school-on-population-genetics-and-evolution">Coalescent theory by John Wakeley on a workshop (Second Bangalore School on Population Genetics and Evolution)</h1>
<p>This is a quite old series of lectures, but should be relevant.</p>

<h2 id="basic-probability-theory"><a href="https://www.youtube.com/watch?v=lMegBoAG2zM&amp;list=PL04QVxpjcnji2WV8QIB63JfpzJP_1zecC&amp;index=6">Basic Probability theory</a></h2>

<ul>
  <li>
    <p>Using an example from a Nature paper on 2001: <a href="https://www.nature.com/articles/35057149">A map of human genome sequence variation containing 1.42 million single nucleotide polymorphisms</a>, where they sampled 12027 loci, with each loci spanning ~500bp. They get a summarized table of the number of SNPs in different frequency classes. The data can be used to infer the demographic history of human populations. One need to use a random model to explain the observed data.</p>

    <table>
      <thead>
        <tr>
          <th>#SNPs</th>
          <th>#loci</th>
          <th>Proportion of loci</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>0</td>
          <td>8796</td>
          <td>0.731</td>
        </tr>
        <tr>
          <td>1</td>
          <td>2247</td>
          <td>0.187</td>
        </tr>
        <tr>
          <td>2</td>
          <td>668</td>
          <td>0.056</td>
        </tr>
        <tr>
          <td>3</td>
          <td>214</td>
          <td>0.018</td>
        </tr>
        <tr>
          <td>4</td>
          <td>102</td>
          <td>0.008</td>
        </tr>
      </tbody>
    </table>
  </li>
  <li>In this lesson, he recalled concepts of probability theory, including expectation, variance, Bernoulli/Binomial random variables. In a Wright-Fisher model, the number of copies of a particular allele in a population is a binomial random variable. The expected number of copies of a particular allele in a population is $2Np$, and the variance is $2Np(1-p)$.</li>
  <li>$Binomial(n,p) \approx Poisson(np)$ when $n$ is large and $p$ is small, and $np$ becomes \(\lambda\). $P(K=k)=\frac{\lambda^k}{k!}e^{-\lambda}$, $E(K)=\lambda$, $Var(K)=\lambda$.</li>
  <li>Geometric random variable (waiting time of Binomial trials) has $P(K=k)=(1-p)^{k-1}p$, $E(K)=\frac{1}{p}$, $Var(K)=\frac{1-p}{p^2}$.</li>
  <li>Exponential random variable (waiting time of Poisson events) has $P(K=k)=\lambda e^{-\lambda k}$, $E(K)=\frac{1}{\lambda}$, $Var(K)=\frac{1}{\lambda^2}$.</li>
</ul>

<h2 id="gene-genealogies-and-coalescent-processes"><a href="https://www.youtube.com/watch?v=lo864lPyszg&amp;list=PL04QVxpjcnji2WV8QIB63JfpzJP_1zecC&amp;index=9">Gene genealogies and coalescent processes</a></h2>

<ul>
  <li>A starting example in this lesson is a Nature paper from Li Heng in 2011: <a href="https://www.nature.com/articles/nature10231">Inference of human population history from individual whole-genome sequences</a>. They estimate the effective population size of human populations using the coalescent theory. They also modeled recombination in the coalescent process.</li>
  <li>Some measures of variations:
    <ul>
      <li>$S$: number of segregating sites.</li>
      <li>$\pi$: Nucleotide diversity: average pairwise difference.</li>
      <li>$Z_i$: (Unfolded) Site frequency spectrum, number of sites with $i$ copies of mutant.</li>
      <li>$\eta_i$: Folded Site frequency spectrum: number of polymorphic sites where the less-frequent (minor allele) allele has frequency $i$.</li>
    </ul>
  </li>
  <li>The coalescent, notations:
    <ul>
      <li>Sample size: $n$.</li>
      <li>Population size: $N$.</li>
    </ul>
  </li>
  <li>Number of generations to a coalescent event: $P(G=g)=(1- \frac{n\choose2}{2})^{g-1}\frac{n\choose2}{2}$ as a geometric random variable. Or $f_{T_{n}}(t)={n\choose2}e^{-{n\choose2}t}$ as an exponential random variable, where one unit of time is $N$ generations.</li>
  <li>Expected Number of Segregating Sites:
    <ul>
      <li>$E[S]=\sum_{i=2}^{n}i\cdot E[T_i]\cdot \theta$:
        <ul>
          <li>$i$: Number of lineages in a coalescent interval.</li>
          <li>$E[T_i]$: Expected coalescent time for $i$ lineages, $\frac{2}{i(i-1)}$, note that this is in units of $N$ generations.</li>
          <li>$\theta$: Scaled mutation rate.</li>
        </ul>
      </li>
      <li>Simplified formula: $E[S]=\theta \sum_{i=2}^{n}\frac{1}{i-1}=\theta \sum_{i=1}^{n}\frac{1}{i}$.</li>
    </ul>
  </li>
  <li>Expected total number of mutations:
    <ul>
      <li>$K$ follows a Poisson distribution with mean $\frac{\theta}{2}$, where $\theta = 4N_e\mu$ is the scaled mutation rate.</li>
      <li>$P(K = k \mid \theta) = \frac{\left(\frac{\theta}{2}\right)^k e^{-\frac{\theta}{2}}}{k!}$
        <ul>
          <li>Describes the probability of observing $k$ mutations.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Number of Mutations Between Two Sequences ($K_2$)
    <ul>
      <li>Coalescent Time Distribution:
        <ul>
          <li>The coalescent time $T_2$ follows an exponential distribution with mean $1$ (in coalescent units): $f_{T_2}(t) = e^{-t}.$</li>
        </ul>
      </li>
      <li>Conditional Probability of Mutations Given $T_2$:
        <ul>
          <li>
            <p>$K_2$ (number of mutations) follows a Poisson distribution conditioned on $T_2$, with mean $\frac{\theta t}{2}\times 2$:</p>

\[P(K_2 = k \mid T_2 = t) = \frac{\left(\theta t\right)^k e^{-\theta t}}{k!}.\]
          </li>
          <li>
            <p>Describes the probability of observing $k$ mutations, given coalescent time $T_2 = t$.</p>
          </li>
        </ul>
      </li>
      <li>Unconditional Probability of Mutations:
        <ul>
          <li>
            <p>Marginalizing over all possible $T_2$ values, the probability of $K_2 = k$ is:</p>

\[P(K_2 = k) = \int_0^\infty f_{T_2}(t) \cdot P(K_2 = k \mid T_2 = t) \, dt.\]
          </li>
          <li>
            <p>Combines the exponential distribution of $T_2$ with the Poisson mutation process.</p>
          </li>
        </ul>
      </li>
      <li>
        <p>Resulting Probability:</p>

\[P(K_2 = k) = \left(\frac{\theta}{\theta + 1}\right)^{k} \cdot \frac{1}{\theta + 1}\]
      </li>
      <li>$\theta$: Scaled mutation rate ($4N_e\mu$).</li>
      <li>Can be viewed as a geometric distribution with parameter $\frac{1}{\theta + 1}$ (waiting problem for multiple mutations and a final coalescent).</li>
    </ul>
  </li>
</ul>

<h2 id="gene-genealogies-with-recombination"><a href="https://www.youtube.com/watch?v=NYYtDmiMB9Q&amp;list=PL04QVxpjcnji2WV8QIB63JfpzJP_1zecC">Gene genealogies with recombination</a></h2>

<ul>
  <li>Recall the the expected number of segregating sites: $E[S]=\theta \sum_{i=1}^{n}\frac{1}{i}$.</li>
  <li>Note that the expected nucleotide diversity $\pi$ is the average pairwise difference, which is $E[\pi]=\theta$, which is the same as the expected number of segregating sites when $n=2$.</li>
  <li>Expected site frequency spectrum: $E[Z_i]=\frac{\theta}{i}$.</li>
  <li>Tajima’s D compares two estimates of genetic diversity to infer deviations caused by selection, demographic events, or other evolutionary processes.</li>
  <li>Recombination complicates coalescent theory because it causes different parts of the genome to have different genealogies, breaking the simple tree-like structure of the standard coalescent process.
    <ul>
      <li><img src="/files/2024-12-28-structured-coalescent/Screenshot%202024-12-31%20at%2021.53.07.webp" alt="" /></li>
    </ul>
  </li>
  <li>
    <p>Covariance Between Coalescent Times ($T_1, T_2$):</p>

\[\text{Cov}[T_1, T_2] = \frac{\rho + 18}{\rho^2 + 13\rho + 18}\]

    <ul>
      <li>$T_1, T_2$: Coalescent times for two loci.</li>
      <li>$\rho = 4N_e r$: Scaled recombination rate.</li>
    </ul>
  </li>
  <li><strong>Sequential Markov Coalescent (SMC)</strong>, is a computationally efficient approximation to the full <strong>Ancestral Recombination Graph (ARG)</strong>. The SMC framework models the genealogy of sequences along a genome, incorporating recombination to simulate how local genealogies change sequentially along the genome.
    <ul>
      <li>Instead of modeling the entire recombination history, the SMC assumes a Markovian process for genealogies along the genome.</li>
      <li>Along the genome, recombination causes the genealogical tree to “switch” to a new topology at certain points.</li>
      <li>These switches happen at recombination breakpoints and are shown in the diagram as transitions between trees.</li>
    </ul>
  </li>
  <li><strong>Identity by Descent (IBD)</strong> occurs when two or more genetic segments in different individuals are inherited from a common ancestor without any intervening recombination or mutation. These segments are identical because they have been directly passed down through generations from the same ancestor.</li>
  <li>IBD can also be view distributed along a genome:
    <ul>
      <li><img src="/files/2024-12-28-structured-coalescent//Screenshot%202024-12-31%20at%2023.47.12.webp" alt="" /></li>
    </ul>
  </li>
  <li>We can also model within the IBD segment, giving a focal point:
    <ul>
      <li><img src="/files/2024-12-28-structured-coalescent/Screenshot%202025-01-01%20at%2000.34.56.webp" alt="" /></li>
    </ul>
  </li>
</ul>

<h2 id="structured-coalescent"><a href="https://www.youtube.com/watch?v=avSea13o5Gs&amp;t=16s">Structured coalescent</a></h2>
<ul>
  <li>Non-exchangeability of lineages in structured populations:
    <ul>
      <li>In structured populations, lineages are not exchangeable because they are more likely to coalesce with lineages from the same subpopulation.</li>
      <li>This non-exchangeability affects the coalescent process and the genealogies of sequences.</li>
    </ul>
  </li>
  <li>He revisit the Markov chain model, specified with a <em>transition probability matrix</em>.
    <ul>
      <li>This matrix describes the probability of transitioning between states (generations) in the Markov chain, with each $P$ representing the probability of transitioning from one state (generation with $i$ lineages) to another state (generation $i-1$ lineages).</li>
    </ul>
  </li>
  <li>Recall that, based on Wright–Fisher (discrete‐generation) model, $P(i \to i-1) = \frac{\binom{i}{2}}{2N} \prod_{k=2}^{i-1} \left(1 - \frac{k}{2N}\right)$ is the probability that, in the next generation, exactly one pair of the $i$ current lineages coalesces (merges), resulting in $i−1$ distinct ancestral lineages (all the others do not coalesce).
    <ul>
      <li>If we multiply this by $2N \to\infty$, we get $i\choose2$, this result in the coalescent rate in the time scale of $2N$ generations.</li>
    </ul>
  </li>
  <li>Wright’s Island Model:
    <ul>
      <li>Notations:
        <ul>
          <li>$D$: demes (subpopulations).</li>
          <li>$N$: deme size</li>
          <li>$m$: migration probability (equally likely to every other deme).</li>
        </ul>
      </li>
      <li>When $n=2$, the instantaneous transition matrix (for how long does it take to coalesce) can be derived:
        <ul>
          <li>State 1: both lineages are in the same deme.</li>
          <li>State 2: lineages are in different demes.</li>
          <li>State 3: lineage coalesced.</li>
          <li><img src="/files/2024-12-28-structured-coalescent/image.webp" alt="" /></li>
        </ul>
      </li>
      <li>If $m\to0$ in this matrix, we can ignore the $m^2$ terms, then we have:
        <ul>
          <li><img src="/files/2024-12-28-structured-coalescent/Screenshot%202025-01-01%20at%2017.52.01.webp" alt="" /></li>
        </ul>
      </li>
      <li>
        <p>It can be further simplified to the below matrix, if multiplied by $2N$:</p>

\[Q =
\begin{bmatrix}
-M - 1 &amp; M &amp; 1 \\
\frac{M}{D - 1} &amp; -\frac{M}{D - 1} &amp; 0 \\
0 &amp; 0 &amp; 1
\end{bmatrix}\]
      </li>
      <li>The waiting time in state 1 is $f_1(t)=(M+1)e^{-(M+1)t}$, with $E[T_1]=\frac{1}{M+1}$.</li>
      <li>The waiting time in state 2 is $f_1(t)=(\frac{M}{D - 1})e^{-(\frac{M}{D - 1})t}$, with $E[T_2]=\frac{D-1}{M}$.</li>
      <li>
        <p>$T_w$: Coalescent time (within) started from state 1:</p>

\[\begin{align*}
  E[T_w]&amp;=\frac{1}{M+1}+\frac{M}{M+1}\cdot E[T_b]+ \frac{1}{M+1}\cdot 0 \\
  &amp;=D
  \end{align*}\]
      </li>
      <li>
        <p>$T_b$: Coalescent time (between) started from state 2:</p>

\[\begin{align*}
  E[T_b]&amp;=\frac{D-1}{M}+ E[T_w] \\
  &amp;=D(1+\frac{D-1}{MD})
  \end{align*}\]
      </li>
      <li>$T_w$ and $T_b$ can be solved if put together.</li>
    </ul>
  </li>
  <li>A more relaxed model:
    <ul>
      <li>Notations:
        <ul>
          <li>$N_i$: size for deme $i$.</li>
          <li>$q_{ij}$: migration rate from deme $i$ to deme $j$.</li>
        </ul>
      </li>
      <li>The $N_i$ can changed, something similar to the traveler matrix in the metapopulation model is happening.</li>
      <li>Conservative migration: forwards and backwards migration rates are equal.</li>
    </ul>
  </li>
</ul>

<h1 id="coalescent-theory-by-aneil-agrawal-on-a-workshop-fourth-bangalore-school-on-population-genetics-and-evolution">Coalescent theory by Aneil Agrawal on a workshop (Fourth Bangalore School on Population Genetics and Evolution)</h1>

<h2 id="drift-inbreeding-and-n_e"><a href="https://www.youtube.com/watch?v=oegeySlWHrE">Drift, Inbreeding, and $N_e$</a></h2>

<ul>
  <li>Under only genetic drift, The cumulative probability that a coalescence event has occurred by generation $t$: $F(t) = 1/(2N) + (1 - 1/(2N)) * F(t-1) = 1 - (1 - 1/(2N))^t$.</li>
  <li>Considering also the mutation process with $\mu$ rate, $F(t) = 1 - (1 - 1/(2N))^t \cdot (1-\mu)^2$. Assuming equilibrium and assuming $N$ is large, $\mu$ is small, we get $F^*=\frac{1}{4N\mu}=\frac{1}{\theta}.$</li>
  <li>Effective population size is the size of an <strong>idealized population</strong> that would show the same amount of genetic drift or inbreeding as the population under consideration. Many process <strong>cannot</strong> be modeled/captured by a single $N_e$.</li>
</ul>

<h2 id="coalescence-i-basic-theory-and-connection-to-mol-pop-gen-statistics"><a href="https://www.youtube.com/watch?v=8DlZ2tPZ0tU">Coalescence I: basic theory and connection to mol pop gen statistics</a></h2>

<ul>
  <li>
    <table>
      <tbody>
        <tr>
          <td>The probability of NOT coalescing (for constant N) in $t$ is $1-F(t) = (1 - 1/(2N))^t$, using first order Taylor expansion ($e^x \approx 1 + x \quad \text{if }</td>
          <td>x</td>
          <td>\ll 1$), we get $1-F(t) \approx e^{-t/(2N)}$.</td>
        </tr>
      </tbody>
    </table>
  </li>
  <li>The probability of NOT coalescing (for changing N), the probability of NOT coalescing is equivalent to the <strong>harmonic mean</strong> of the population size over time. Note that harmonic mean is the reciprocal of the average of the reciprocals, which is sensitive to small values.</li>
  <li><a href="https://youtu.be/8DlZ2tPZ0tU?t=1325">Gender bias</a> can lead to less effective population size than the actual population size.</li>
  <li><a href="https://youtu.be/8DlZ2tPZ0tU?t=1555">A model without self-fertilization</a>, which can also yield smaller effective population size than actual population size.</li>
  <li>Smaller effective population size $\approx$ more genetic drift $\approx$ more homozygosity.</li>
  <li>In later part of the lesson, he revisited the (total) time to coalescence for $k$ lineages.</li>
  <li>The expected number of mutations is $2\mu \bar{t}=4N\mu. $</li>
</ul>

<h2 id="coalescence-ii-structured-coalescent-including-pop-structure-selfing-and-backgroundbalancing-selection"><a href="https://www.youtube.com/watch?v=W5jwoH4cUkY">Coalescence II: structured coalescent including pop structure, selfing, and background/balancing selection</a></h2>

<ul>
  <li>The probability of a mutation events among all events: $\frac{P(mut)}{P(something)}=\frac{2\mu}{2\mu+\frac{1}{2N}}=\frac{4N\mu}{4N\mu+1}=\frac{\Theta_{\pi}}{\Theta_{\pi}+1}$</li>
  <li>Expected number of segregating sites: $E[S]=\Theta_w \sum_{i=1}^{k-1}\frac{1}{i}$.</li>
  <li>Tajima’s D comparing $\Theta_{\pi}$ and $\Theta_w$, by $D=\frac{\Theta_{\pi}-\Theta_w}{\sqrt{Var(\Theta_{\pi}-\Theta_w)}}$. The expectation is zero, if under an idealized Wright-Fisher model. Excessive rare variants (negative $D$) can be due to population expansion, or balancing selection. Excessive common variants (positive $D$) can be due to population contraction, or directional selection.</li>
  <li>Mcdonald-Kreitman test use polymorphism and divergence to infer selection. Considering <strong>two species</strong>, it takes $G$ generations to reach back to the ancestral specie, and $2N_A$ generation to coalesce (within the ancestral specie), so $T_D=2N_A+G$. The expected number of sequence divergence is $E[D]=2\mu T_D$. In this test, y ou can take the ratio of the number of segregating sites to the number of divergence sites. The ratio should be the same for synonymous and non-synonymous sites, if there is no selection. $\frac{E(S_{syn})}{E(D_{syn})}= \frac{E(S_{non})}{E(D_{non}) }$.</li>
  <li><strong>Kimura’s neutral theory</strong> argued that most evolutionary changes in DNA (or amino acid) sequences are the result of random fixation of neutral mutations rather than being driven by natural selection. In other words, while beneficial and deleterious mutations certainly occur, the bulk of the substitutions (i.e., the differences that become fixed between species) are those that are effectively neutral with respect to fitness.</li>
  <li>Strongly deleterious mutations are not likely to be observed in the data, thus not contributing to the number of segregating sites, however, they can contribute to the divergence.</li>
  <li>
    <p>If we set $a$ as the number of adaptive substitutions, assuming weakly deleterious mutations, thus not affecting $E(S_{non})$ but only affecting $E(D_{non})$, we can get:</p>

\[\begin{aligned}
D_{non} &amp;= 2\mu T_D + a, \\ \\
a &amp;= D_{non} - 2\mu T_D\\
  &amp;= D_{non} - E(S_{non})\frac{E(D_{syn})}{E(S_{syn})}.
\end{aligned}\]
  </li>
  <li>The estimation of $a$ is surprisingly high ($\approx 0.4$) for some cases, but for human data it is low.</li>
  <li>In structured populations, the alleles are not exchangeable - quite complicated!</li>
  <li>
    <p>Rederived the classic coalescent time for two alleles. He constructed the same instantaneous transition matrix as John Wakeley did in the earlier notes.</p>

\[\begin{aligned}
\mathbb{E}[T_1] &amp;= 2\,d\,n,\\
\mathbb{E}[T_2] &amp;= 2\,d\,n \;+\; \frac{d - 1}{2\,m},\\
\mathbb{E}[T_*]   &amp;= \frac{1}{d}\,\mathbb{E}[T_1] \;+\; \bigl(1 - d\bigr)\,\mathbb{E}[T_2].
\end{aligned}\]
  </li>
  <li>
    <p><a href="https://youtu.be/sM7JRU44oJk?t=240">FST</a> is a measure of population differentiation due to genetic structure, from a coalescent perspective:</p>

\[\begin{aligned}
F_{ST}&amp;=\frac{E(H_T)-E(H_S)}{E(H_T)}\\
&amp;=\frac{E(T_{*})-E(T_1)}{E(T_{*})} \\
&amp;= \frac{(d - 1)^2}{1 - 2d + d^2 \left(1 + 4mn\right)}\\\\
\lim_{d\to \infty} F_{ST} &amp;= \frac{1}{1 + 4mn}
\end{aligned}\]

    <p>Note that $mn$ is like the number of migrants per generation. Be careful that there are many assumptions in this model, which are usually not met in real data.</p>
  </li>
</ul>]]></content><author><name>Haogao Gu</name><email>work@guhaogao.com</email></author><category term="Course notes" /><category term="Coalescent theory" /><category term="Phylogenetics" /><summary type="html"><![CDATA[I wanted to get in more details about the structured coalescent model, here I record some notes when I watch introductory videos.]]></summary></entry></feed>