# BD shifts

#### Nick Youngblut

#### 2016-11-01

# Making BD shift plots

Note: if you haven’t checked out the beta diversity ordinations vignette yet, I recommend looking at that one first.

## Introduction

While the beta diversity ordinations of gradient fractions provides a nice overview of isotope incorporation at the whole-community level, it doesn’t provide a good idea of the magnitude of this BD shift (ie., was there a lot of isotope incorporation or a little for each labeled-treatment?).

Let’s assume that the gradient fraction communities of a labeled-treatment and its corresponding unlabled-control would be (approximately) the same at the same buoyant densities if no incorperation occured. If so, then the pairwise beta diversity between gradient fractions of the treatment vs control would (e.g., the beta diversity between the 13C & 12C communities at a BD of 1.75 g/ml^1) would be ~0 (no differentiation) across the BD range. However, if some taxa incorporated isotope in the labeled-treatment, then they would shift to heavier buoyant densities, which would change the labeled-communities at the buoyant densities where the taxa used to be if unlabeled and the buoyant densities where the taxa have shifted to due to isotope incorporation.

In other words, if we make pairwise treatment-vs-control beta diversity calculations between gradient fraction communities, then we should see evidence of community-level BD shifts in the form of ‘spikes’ in beta diversity.

The only major issue with this approach is that the BD range of each gradient fraction varies from gradient to gradient. So, gradient fractions between gradients usually only partially overlap. To deal with this issue, we have taken the approach of weighting the beta diversity based on gradient fraction overlap. For instance, if 2 labeled-treatment fractions overlapped 1 control fraction by 40% and 60%, then the final beta diversity value would be the weighted average of treatment fraction 1 (40% weight) and treatment fraction 2 (60% weight). Note that this makes all beta diversity values (and their associated buoyant densities) relative to the control.

The following analysis measures these community-wide BD shifts with the following:

1. Splitting the dataset into pairwise comparisons between each labeled-treatment and its corresponding unlabeled control.
2. The percent BD overlap of treatment gradient fractions relative to the control are calculated.
3. For overlapping gradient fractions in each treatment-control comparison, beta diversity is calculated between the gradient fraction communities.
4. The weighted mean beta diversity (weighted by % fraction overlap) is calculated.
5. The resulting data.frame can then easily plotted with ggplot.

## Dataset

First, let’s load some packages including `HTSSIP`.

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    library(HTSSIP)

Also let’s get an overview of the phyloseq object that we’re going to use.

    physeq_S2D2

    ## phyloseq-class experiment-level object
    ## otu_table()   OTU Table:         [ 10001 taxa and 139 samples ]
    ## sample_data() Sample Data:       [ 139 samples by 17 sample variables ]
    ## tax_table()   Taxonomy Table:    [ 10001 taxa by 8 taxonomic ranks ]
    ## phy_tree()    Phylogenetic Tree: [ 10001 tips and 10000 internal nodes ]

## Subsetting the phyloseq object

As with the beta diversity ordinations, we are going to split up the dataset into individual labeled-treamtent + corresponding unlabeled-control comparisons. Treatment-control correspondence is based on the day from substrate addition. So, we have to parse the dataset by Substrate & Day.

    params = get_treatment_params(physeq_S2D2, c('Substrate', 'Day'))
    params = dplyr::filter(params, Substrate!='12C-Con')
    ex = "(Substrate=='12C-Con' & Day=='${Day}') | (Substrate=='${Substrate}' & Day == '${Day}')"
    physeq_S2D2_l = phyloseq_subset(physeq_S2D2, params, ex)
    physeq_S2D2_l

    ## $`(Substrate=='12C-Con' & Day=='3') | (Substrate=='13C-Cel' & Day == '3')`
    ## phyloseq-class experiment-level object
    ## otu_table()   OTU Table:         [ 10001 taxa and 46 samples ]
    ## sample_data() Sample Data:       [ 46 samples by 17 sample variables ]
    ## tax_table()   Taxonomy Table:    [ 10001 taxa by 8 taxonomic ranks ]
    ## phy_tree()    Phylogenetic Tree: [ 10001 tips and 10000 internal nodes ]
    ##
    ## $`(Substrate=='12C-Con' & Day=='14') | (Substrate=='13C-Cel' & Day == '14')`
    ## phyloseq-class experiment-level object
    ## otu_table()   OTU Table:         [ 10001 taxa and 46 samples ]
    ## sample_data() Sample Data:       [ 46 samples by 17 sample variables ]
    ## tax_table()   Taxonomy Table:    [ 10001 taxa by 8 taxonomic ranks ]
    ## phy_tree()    Phylogenetic Tree: [ 10001 tips and 10000 internal nodes ]
    ##
    ## $`(Substrate=='12C-Con' & Day=='14') | (Substrate=='13C-Glu' & Day == '14')`
    ## phyloseq-class experiment-level object
    ## otu_table()   OTU Table:         [ 10001 taxa and 47 samples ]
    ## sample_data() Sample Data:       [ 47 samples by 17 sample variables ]
    ## tax_table()   Taxonomy Table:    [ 10001 taxa by 8 taxonomic ranks ]
    ## phy_tree()    Phylogenetic Tree: [ 10001 tips and 10000 internal nodes ]
    ##
    ## $`(Substrate=='12C-Con' & Day=='3') | (Substrate=='13C-Glu' & Day == '3')`
    ## phyloseq-class experiment-level object
    ## otu_table()   OTU Table:         [ 10001 taxa and 46 samples ]
    ## sample_data() Sample Data:       [ 46 samples by 17 sample variables ]
    ## tax_table()   Taxonomy Table:    [ 10001 taxa by 8 taxonomic ranks ]
    ## phy_tree()    Phylogenetic Tree: [ 10001 tips and 10000 internal nodes ]

## Calculating BD shift

Now, let’s just measure BD shift for just 1 subset (1 item in the list of phyloseq objects).

    wmean1 = BD_shift(physeq_S2D2_l[[2]])
    cat('Subset:', names(physeq_S2D2_l)[2], '\n')

    ## Subset: (Substrate=='12C-Con' & Day=='14') | (Substrate=='13C-Cel' & Day == '14')

    wmean1 %>% head(n=3)

    ## # A tibble: 3 x 14
    ##             sample.x           sample.y  distance IS__CONTROL.x BD_min.x
    ##                <chr>              <chr>     <dbl>         <lgl>    <dbl>
    ## 1 12C-Con.D14.R1_F12 13C-Cel.D14.R1_F12 0.2615498          TRUE 1.736237
    ## 2 12C-Con.D14.R1_F13 13C-Cel.D14.R1_F12 0.2570687          TRUE 1.730773
    ## 3 12C-Con.D14.R1_F23 13C-Cel.D14.R1_F22 0.1537309          TRUE 1.692527
    ## # ... with 9 more variables: BD_max.x <dbl>, BD_range.x <dbl>,
    ## #   IS__CONTROL.y <lgl>, BD_min.y <dbl>, BD_max.y <dbl>, BD_range.y <dbl>,
    ## #   perc_overlap <dbl>, n_over_fracs <int>, wmean_dist <dbl>

Note that the `sample.x` column is all 12C-Con control samples, while the comparison column (`sample.y`) is the treatment gradient fraction samples.

OK. Let’s plot the results!

    x_lab = 'Buoyant density (g/ml^-1)'
    y_lab = 'Weighted mean of\nweighted-Unifrac distances'
    ggplot(wmean1, aes(BD_min.x, wmean_dist)) +
      geom_point() +
      labs(x=x_lab, y=y_lab, title='Beta diversity of 13C-treatment relative to 12C-Con') +
      theme_bw()

Each point represents the weighted mean of beta diversity values between all 13C-treatment fractions that overlap a particular 12C-control fraction, so there should be 1 point per 12C-control gradient fraction.

Note the 2 spikes in beta diversity. The 2nd spike is larger than the first, which is likely due to more taxa at the ‘light’ gradient fractions (1st spike), so a loss of a few taxa (due to BD shifting) impacts beta diveristy less than at ‘heavy’ gradient fractions, where there’s less taxa.

## Calculating BD shift for all treatments

Now let’s run `BD_shift()` on all phyloseq objects in our list. We’ll use `plyr::ldply()` for this because it preserves the list names in the resulting data.frame (list names are assigned to `.id` by default).

    wmean = plyr::ldply(physeq_S2D2_l, BD_shift)
    wmean %>% head(n=3)

    ##                                                                       .id
    ## 1 (Substrate=='12C-Con' & Day=='3') | (Substrate=='13C-Cel' & Day == '3')
    ## 2 (Substrate=='12C-Con' & Day=='3') | (Substrate=='13C-Cel' & Day == '3')
    ## 3 (Substrate=='12C-Con' & Day=='3') | (Substrate=='13C-Cel' & Day == '3')
    ##            sample.x          sample.y   distance IS__CONTROL.x BD_min.x
    ## 1 12C-Con.D3.R3_F19 13C-Cel.D3.R1_F21 0.08867784          TRUE 1.705640
    ## 2 12C-Con.D3.R3_F13 13C-Cel.D3.R1_F15 0.12424811          TRUE 1.728588
    ## 3 12C-Con.D3.R3_F14 13C-Cel.D3.R1_F15 0.13054131          TRUE 1.724217
    ##   BD_max.x BD_range.x IS__CONTROL.y BD_min.y BD_max.y BD_range.y
    ## 1 1.710011   0.004371         FALSE  1.70564 1.706186   0.000546
    ## 2 1.732959   0.004371         FALSE  1.72531 1.734052   0.008742
    ## 3 1.728588   0.004371         FALSE  1.72531 1.734052   0.008742
    ##   perc_overlap n_over_fracs wmean_dist
    ## 1     12.49142            2  0.1179129
    ## 2    100.00000            1  0.1242481
    ## 3     74.99428            2  0.1240763

Alright, let’s plot the data!

    # formatting the treatment names to look a bit better as facet labels
    wmean = wmean %>%
      mutate(Substrate = gsub('.+(13C-[A-z]+).+', '\\1', .id),
             Day = gsub('.+Day ==[ \']*([0-9]+).+', '\\1', .id),
             Day = Day %>% reorder(Day %>% as.numeric))

    # plotting, with facetting by 13C-treatment
    ggplot(wmean, aes(BD_min.x, wmean_dist)) +
      geom_point() +
      geom_line() +
      labs(x=x_lab, y=y_lab,
           title='Beta diversity of 13C-treatments relative to 12C-Con') +
      facet_grid(Day ~ Substrate) +
      theme_bw() +
      theme(axis.text.x = element_text(angle=45, hjust=1))

As you can see, the ‘heavy’ beta diversity spike is stronger for 13C-Glucose at Day 3 versus 13C-Cellulose, but this pattern reverses at Day 14 of the substrate incubation. These results are to be expected, given that glucose is more labile than cellulose.

# Session info

    sessionInfo()

    ## R version 3.2.4 Revised (2016-03-16 r70336)
    ## Platform: x86_64-pc-linux-gnu (64-bit)
    ## Running under: Ubuntu precise (12.04.5 LTS)
    ##
    ## locale:
    ##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
    ##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=C
    ##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
    ##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
    ##  [9] LC_ADDRESS=C               LC_TELEPHONE=C
    ## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] phyloseq_1.14.0 HTSSIP_1.0.3    ggplot2_2.1.0   tidyr_0.5.1
    ## [5] dplyr_0.5.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] reshape2_1.4.1      splines_3.2.4       lattice_0.20-33
    ##  [4] colorspace_1.2-6    htmltools_0.3.5     stats4_3.2.4
    ##  [7] yaml_2.1.13         mgcv_1.8-12         chron_2.3-47
    ## [10] survival_2.39-5     DBI_0.4-1           BiocGenerics_0.16.1
    ## [13] foreach_1.4.3       plyr_1.8.4          stringr_1.0.0
    ## [16] zlibbioc_1.16.0     Biostrings_2.38.4   munsell_0.4.3
    ## [19] gtable_0.2.0        codetools_0.2-14    evaluate_0.9
    ## [22] labeling_0.3        Biobase_2.30.0      knitr_1.13
    ## [25] permute_0.9-0       IRanges_2.4.8       parallel_3.2.4
    ## [28] Rcpp_0.12.5         scales_0.4.0        formatR_1.4
    ## [31] vegan_2.4-0         S4Vectors_0.8.11    XVector_0.10.0
    ## [34] digest_0.6.10       stringi_1.1.1       RJSONIO_1.3-0
    ## [37] grid_3.2.4          ade4_1.7-4          tools_3.2.4
    ## [40] magrittr_1.5        lazyeval_0.2.0      tibble_1.1
    ## [43] cluster_2.0.4       ape_3.5             MASS_7.3-45
    ## [46] Matrix_1.2-6        biom_0.3.12         data.table_1.9.6
    ## [49] assertthat_0.1      rmarkdown_1.0       iterators_1.0.8
    ## [52] R6_2.1.2            multtest_2.26.0     igraph_1.0.1
    ## [55] nlme_3.1-128        compiler_3.2.4