---
title: "Building phylogenetic trees with aptg"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Building phylogenetic trees with aptg}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  # Every chunk below queries a remote service (Open Tree of Life, NCBI,
  # Fish Tree of Life). To keep the vignette buildable offline and on CRAN,
  # code is shown but not evaluated. Run it yourself in an interactive
  # session with network access.
  eval = FALSE
)
```

`aptg` builds phylogenetic trees for a list of taxa, or for a higher taxon
expanded down to a lower rank. It has two backends:

* **`source = "otl"`** (default) --- induced subtrees of the
  [Open Tree of Life](https://tree.opentreeoflife.org/) synthetic tree, via
  the `rotl` package. Covers all of life, but the trees are *topology only*
  (no branch lengths).
* **`source = "fish"`** --- a dated chronogram from the
  [Fish Tree of Life](https://fishtreeoflife.org/) (Rabosky *et al.* 2018),
  via the suggested `fishtree` package. Ray-finned fishes only, but with real
  (time-calibrated) branch lengths.

```{r setup}
library(aptg)
```

## Trees are split by phylum

A key safeguard: `aptg` never builds a single tree that spans more than one
phylum. There is no meaningfully calibrated deep phylogeny linking, say, land
plants and vertebrates, so combining them into one tree would be misleading.
Instead, `taxa.tree()` groups the input by phylum and returns **one tree per
phylum**.

Here is a deliberately mixed list --- three mammals and three trees:

```{r mixed}
res <- taxa.tree(c(
  "Canis lupus", "Alces alces", "Rangifer tarandus",   # phylum Chordata
  "Acer saccharum", "Acer rubrum", "Betula alleghaniensis"  # phylum Streptophyta
))

names(res$trees)
#> [1] "Chordata"     "Streptophyta"
```

`res` is a list with two components: `trees` (named by phylum) and
`unmatched` (anything that could not be placed). Each element of `trees` is
itself a list holding the `phylo` object and a distance matrix:

```{r inspect}
chordata <- res$trees[["Chordata"]]

chordata$tree            # an ape "phylo" object
chordata$dist            # pairwise distances among the three mammals

# Plot just the plant tree:
plot(res$trees[["Streptophyta"]]$tree)
```

Because Open Tree subtrees have no branch lengths, `aptg` assigns unit edges,
so the distance matrix for the `"otl"` backend counts the **number of edges**
between tips --- a topological distance, not time or substitutions.

Names that Open Tree cannot resolve, that are absent from the synthetic tree,
or whose lineage carries no phylum rank, are reported rather than silently
dropped:

```{r unmatched}
res$unmatched
```

## Starting from a higher taxon

`downto.tree()` expands a taxon to all of its descendants at a chosen rank
(using `taxize`), then feeds them to `taxa.tree()`. The phylum safeguard still
applies, so if the descendants happen to span more than one phylum you get
more than one tree back.

```{r downto}
# Every species in the deer family:
deer <- downto.tree("Cervidae", downto = "species")
names(deer$trees)
#> [1] "Chordata"
```

If you hit NCBI rate limits, either supply an Entrez API key
(`taxize::use_entrez()`) via the `key` argument, or switch the expansion
database, e.g. `downto.tree("Cervidae", "species", db = "gbif")`.

## A dated fish tree

For ray-finned fishes, the `"fish"` backend gives a **dated** tree, which is
usually what you want for comparative analyses. It requires the `fishtree`
package:

```{r fish-install}
install.packages("fishtree")  # once
```

```{r fish}
fish <- taxa.tree(
  c("Thunnus thynnus", "Gadus morhua", "Danio rerio", "Salmo salar"),
  source = "fish"
)

tr <- fish$trees[["Actinopterygii"]]$tree
plot(tr)

# These branch lengths are real, so cophenetic() gives patristic (time)
# distances rather than edge counts:
fish$trees[["Actinopterygii"]]$dist
```

Species not in the Fish Tree of Life are dropped and listed in
`fish$unmatched`.

## Trees for a geographic area

`region.tree()` pulls the species of a clade recorded in an area from GBIF and
builds the tree(s). Give it a **required** clade (`taxon`) plus either a radius
around a coordinate or an administrative area.

```{r region}
# Birds within 50 km of Montreal:
region.tree("Aves", lat = 45.50, lon = -73.57, radius_km = 50)

# Mammals of a Canadian territory (all 13 provinces/territories work,
# by name or postal code):
region.tree("Mammalia", province = "Nunavut")

# Freshwater fishes of Quebec as a dated tree:
region.tree("Actinopterygii", province = "QC", source = "fish")

# Anywhere in the world via a GADM GID:
region.tree("Reptilia", gadm = "USA.5_1")
```

Radius mode needs `geosphere`; both modes need `rgbif`. The returned object is
the usual `list(trees, unmatched)` plus a `species` element (the GBIF-derived
list).

**Important:** GBIF gives *occurrence records*, not a checklist. The list is
presence-only and sampling-biased — better-recorded groups and places are
over-represented — so treat it as a starting point, not a definitive
inventory. `region.tree()` counts only georeferenced records without flagged
geospatial issues, but coordinate precision still varies.

## Which backend should I use?

| You want... | Use |
|---|---|
| A tree for an arbitrary mix of taxa (any group) | `source = "otl"` (topology) |
| Dated branch lengths for ray-finned fishes | `source = "fish"` |
| Dated trees for other groups (birds, mammals, plants) | see `vignette`/README notes on `fishtree`-style megatree packages |

The `"otl"` backend is the general workhorse; reach for `"fish"` (or, in
future, other clade-specific dated backends) when you need calibrated branch
lengths.

## References

* Michonneau, F., Brown, J. W. & Winter, D. J. (2016). rotl: an R package to
  interact with the Open Tree of Life data. *Methods in Ecology and
  Evolution*, 7(12), 1476--1481.
  <https://doi.org/10.1111/2041-210X.12593>
* Rabosky, D. L. *et al.* (2018). An inverse latitudinal gradient in
  speciation rate for marine fishes. *Nature*, 559, 392--395.
  <https://doi.org/10.1038/s41586-018-0273-1>
* Chang, J., Rabosky, D. L., Smith, S. A. & Alfaro, M. E. (2019). An R package
  and online resource for macroevolutionary studies using the ray-finned fish
  tree of life. *Methods in Ecology and Evolution*, 10(7), 1118--1124.
  <https://doi.org/10.1111/2041-210X.13182>
