In [1]:
%matplotlib inline
from os.path import join, exists, expandvars
import pandas as pd
from IPython.display import display, Markdown
import seaborn.xkcd_rgb as colors
from tax_credit.plotting_functions import (pointplot_from_data_frame,
boxplot_from_data_frame,
heatmap_from_data_frame,
per_level_kruskal_wallis,
beta_diversity_pcoa,
average_distance_boxplots,
rank_optimized_method_performance_by_dataset)
from tax_credit.eval_framework import (evaluate_results,
method_by_dataset_a1,
parameter_comparisons,
merge_expected_and_observed_tables,
filter_df)
This is the only cell that you will need to edit to generate basic reports locally. After editing this cell, you can run all cells in this notebook to generate your analysis report. This will take a few minutes to run, as results are computed at multiple taxonomic levels.
Values in this cell will not need to be changed, with the exception of project_dir
, to generate the default results contained within tax-credit. To analyze results separately from the tax-credit precomputed results, other variables in this cell will need to be set.
In [2]:
## project_dir should be the directory where you've downloaded (or cloned) the
## tax-credit repository.
project_dir = expandvars("../../")
## expected_results_dir contains expected composition data in the structure
## expected_results_dir/<dataset name>/<reference name>/expected/
expected_results_dir = join(project_dir, "data/precomputed-results/", "mock-community")
## mock_results_fp designates the files to which summary results are written.
## If this file exists, it can be read in to generate results plots, instead
## of computing new scores.
mock_results_fp = join(expected_results_dir, 'mock_results.tsv')
## results_dirs should contain the directory or directories where
## results can be found. By default, this is the same location as expected
## results included with the project. If other results should be included,
## absolute paths to those directories should be added to this list.
results_dirs = [expected_results_dir]
## directory containing mock community data, e.g., feature table without taxonomy
mock_dir = join(project_dir, "data", "mock-community")
## Minimum number of times an OTU must be observed for it to be included in analyses. Edit this
## to analyze the effect of the minimum count on taxonomic results.
min_count = 1
## Define the range of taxonomic levels over which to compute accuracy scores.
## The default given below will compute order (level 2) through species (level 6)
taxonomy_level_range = range(2,7)
# we can save plots in this directory
outdir = join(expandvars("../../../"), 'plots')
In [3]:
dataset_ids = ['mock-1', 'mock-2', 'mock-3', 'mock-4', 'mock-5', 'mock-7', 'mock-8', 'mock-9',
'mock-10', 'mock-12', 'mock-16', 'mock-18', 'mock-19', 'mock-20', 'mock-21',
'mock-22', 'mock-23', 'mock-24', 'mock-26-ITS1', 'mock-26-ITS9']
method_ids = ['rdp', 'sortmerna', 'uclust', 'blast', 'blast+', 'naive-bayes', 'naive-bayes-bespoke', 'vsearch']
ref_ids = ['gg_13_8_otus', 'unite_20.11.2016_clean_fullITS']
Next we'll use the paths defined above to find all of the tables that will be compared. These include the pre-computed result tables (i.e., the ones that the new methods will be compared to), the expected result tables (i.e., the tables containing the known composition of the mock microbial communities), and the query result tables (i.e., the tables generated with the new method(s) that we want to compare to the pre-computed result tables).
Note: if you have added additional methods to add, set append=True
. If you are attempting to recompute pre-computed results, set force=True
.
This cell will take a few minutes to run if new results are being added, so hold onto your hat. If you are attempting to re-compute everything, it may take an hour or so, so go take a nap.
In [4]:
mock_results = evaluate_results(results_dirs,
expected_results_dir,
mock_results_fp,
mock_dir,
taxonomy_level_range=range(2,7),
min_count=min_count,
taxa_to_keep=None,
md_key='taxonomy',
subsample=False,
per_seq_precision=True,
exclude=['other'],
dataset_ids=dataset_ids,
reference_ids=ref_ids,
method_ids=method_ids,
append=False,
force=False,
backup=False)
Restrict analyses to a set of datasets or references: e.g., exclude taxonomy assignments made for purpose of reference database comparisons. This can be performed as shown below — alternatively, specific reference databases, datasets, methods, or parameters can be chosen by setting dataset_ids, reference_ids, method_ids, and parameter_ids in the evaluate_results command above.
In [5]:
# mock_results = filter_df(mock_results, column_name='Method', values=['naive-bayes'], exclude=False)
mock_results = mock_results.reset_index(drop=True)
In this evaluation, we compute and summarize precision, recall, and F-measure of each result (pre-computed and query) based on the known composition of the mock communities. We then summarize the results in two ways: first with boxplots, and second with a table of the top methods based on their F-measures. Higher scores = better accuracy
As a first step, we will evaluate average method performance at each taxonomic level for each method within each reference dataset type.
Note that, as parameter configurations can cause results to vary widely, average results are not a good representation of the "best" results. See here for results using optimized parameters for each method.
First we will define our color palette and the variables we want to plot. Via seaborn, we can apply the xkcd crowdsourced color names. If that still doesn't match your hue, use hex codes.
In [6]:
color_palette={
'expected': 'black', 'rdp': colors['baby shit green'], 'sortmerna': colors['macaroni and cheese'],
'uclust': 'coral', 'blast': 'indigo', 'blast+': colors['electric purple'], 'naive-bayes': 'dodgerblue',
'naive-bayes-bespoke': 'blue', 'vsearch': 'firebrick'
}
y_vars = ["Precision", "Recall", "F-measure", "Taxon Accuracy Rate", "Taxon Detection Rate"]
In [8]:
point = pointplot_from_data_frame(mock_results, "Level", y_vars,
group_by="Reference", color_by="Method",
color_palette=color_palette)
In [10]:
for k, v in point.items():
v.savefig(join(outdir, 'mock-{0}-lineplots.pdf'.format(k)))
In [11]:
result = per_level_kruskal_wallis(mock_results, y_vars, group_by='Method',
dataset_col='Reference', level_name='Level',
levelrange=range(2,7), alpha=0.05,
pval_correction='fdr_bh')
result
Out[11]:
In [12]:
heatmap_from_data_frame(mock_results, metric="Precision", rows=["Method", "Parameters"], cols=["Reference", "Level"])
Out[12]:
In [13]:
heatmap_from_data_frame(mock_results, metric="Recall", rows=["Method", "Parameters"], cols=["Reference", "Level"])
Out[13]:
In [14]:
heatmap_from_data_frame(mock_results, metric="F-measure", rows=["Method", "Parameters"], cols=["Reference", "Level"])
Out[14]:
In [15]:
heatmap_from_data_frame(mock_results, metric="Taxon Accuracy Rate", rows=["Method", "Parameters"], cols=["Reference", "Level"])
Out[15]:
In [16]:
heatmap_from_data_frame(mock_results, metric="Taxon Detection Rate", rows=["Method", "Parameters"], cols=["Reference", "Level"])
Out[16]:
Now we will focus on results at species level (for genus level, change to level 5)
In [7]:
mock_results_6 = mock_results[mock_results['Level'] == 6]
In [8]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Precision", color_palette=color_palette)
Out[8]:
In [9]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Recall", color_palette=color_palette)
Out[9]:
In [10]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="F-measure", color_palette=color_palette)
Out[10]:
In [11]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Taxon Accuracy Rate", color_palette=color_palette)
Out[11]:
In [12]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Taxon Detection Rate", color_palette=color_palette)
Out[12]:
Look at F-measure at genus level
In [13]:
mock_results_5 = mock_results[mock_results['Level'] == 5]
In [14]:
boxplot_from_data_frame(mock_results_5, group_by="Method", metric="F-measure", color_palette=color_palette)
Out[14]:
In [20]:
mock_results_5.groupby("Method").median()
Out[20]:
In [23]:
mock_results_5.groupby("Method").std()
Out[23]:
In [21]:
mock_results_6.groupby("Method").median()
Out[21]:
In [22]:
mock_results_6.groupby("Method").std()
Out[22]:
In the following heatmaps, we assess accuracy rates in each dataset X method configuration combination. This allows us to assess how evenly configurations affect performance, whether specific mock communities outperform of underperform relative to others, and generally assess how increasing/decreasing specific parameters affects accuracy.
In [25]:
heatmap_from_data_frame(mock_results_6, "Precision")
Out[25]:
In [26]:
heatmap_from_data_frame(mock_results_6, "Recall")
Out[26]:
In [27]:
heatmap_from_data_frame(mock_results_6, "F-measure")
Out[27]:
In [28]:
heatmap_from_data_frame(mock_results_6, "Taxon Accuracy Rate")
Out[28]:
In [29]:
heatmap_from_data_frame(mock_results_6, "Taxon Detection Rate")
Out[29]:
In [30]:
for dataset in mock_results_6['Dataset'].unique():
display(Markdown('## {0}'.format(dataset)))
best = method_by_dataset_a1(mock_results_6, dataset)
display(best)
Now we can determine which parameter configuration performed best for each method. Count best values in each column indicate how many samples a given method achieved within one mean absolute deviation of the best result (which is why they may sum to more than the total number of samples).
In [31]:
for method in mock_results_6['Method'].unique():
top_params = parameter_comparisons(
mock_results_6, method,
metrics=['Taxon Accuracy Rate', 'Taxon Detection Rate', 'Precision', 'Recall', 'F-measure'])
display(Markdown('## {0}'.format(method)))
display(top_params[:5])
And, finally, which method performed best at each individual taxonomic level for each reference dataset (i.e., for across all fungal and bacterial mock communities combined)?
For this analysis, we rank the top-performing method/parameter combination for each method at family through species levels. Methods are ranked by top F-measure, and the average value for each metric is shown (rather than count best as above). F-measure distributions are plotted for each method, and compared using paired t-tests with FDR-corrected P-values. This cell does not need to be altered, unless if you wish to change the metric used for sorting best methods and for plotting.
In [15]:
boxes = rank_optimized_method_performance_by_dataset(mock_results,
dataset="Reference",
metric="F-measure",
level_range=range(4,7),
display_fields=["Method",
"Parameters",
"Taxon Accuracy Rate",
"Taxon Detection Rate",
"Precision",
"Recall",
"F-measure"],
paired=True,
parametric=True,
color=None,
color_palette=color_palette)
In [16]:
for k, v in boxes.items():
v.get_figure().savefig(join(outdir, 'mock-fmeasure-{0}-boxplots.pdf'.format(k)))
In [17]:
for metric in ["Taxon Accuracy Rate", "Taxon Detection Rate", "Precision", "Recall", "F-measure"]:
display(Markdown('## {0}'.format(metric)))
boxes = rank_optimized_method_performance_by_dataset(mock_results,
dataset="Reference",
metric=metric,
level_range=range(6,7),
display_fields=["Method",
"Parameters",
"Taxon Accuracy Rate",
"Taxon Detection Rate",
"Precision",
"Recall",
"F-measure"],
paired=True,
parametric=True,
color=None,
color_palette=color_palette)
for k, v in boxes.items():
v.get_figure().savefig(join(outdir, 'mock-{0}-{1}-boxplots.pdf'.format(metric, k)))
Principal coordinate analysis offers a neat way to assess the relative performance of multiple methods to reconstruct expected compositions. Methods that cluster with the "expected" composition probably outperform those that appear more distant on a PCoA plot. First, we need to merge biom tables from each method/parameter configuration for each dataset/reference/level combination, so that we can compare each method/parameter as a separate "sample".
Note: if you have added additional methods and are attempting to recompute results, set force=True.
In [33]:
merge_expected_and_observed_tables(expected_results_dir, results_dirs, taxonomy_level=6, force=True,
dataset_ids=list(mock_results.Dataset.unique()),
reference_ids=list(mock_results.Reference.unique()),
method_ids=list(mock_results.Method.unique()))
Now we can manually select which table we want to view. This will output a Bray-Curtis PCoA plot, in addition to ANOSIM test results, which indicate whether at least two methods are significantly different from each other.
These plots are useful for visualizing the relative performance of different methods and their configurations relative to each other and to expected compositions, but are primarily a qualitative technique and do not really give us an idea of whether method X actually performs better than method Y.
Note that 2D plots will only appear if you are running notebooks locally. If viewing static notebooks online, make sure you are viewing this notebook in nbviewer. (if viewing on GitHub, just copy the URL and paste into the search bar in nbviewer.)
In [34]:
table = join(expected_results_dir, 'mock-18', 'gg_13_8_otus', 'merged_table.biom')
sample_md, results, pc, dm = beta_diversity_pcoa(table, method="braycurtis", dim=2,
permutations=99, col='method',
colormap=color_palette)
You can also view all beta diversity plots with a single command, batch_beta_diversity()
, but we will only show single dataset examples in these example notebooks.
As we already discussed, PCoA plots are good for a qualitative overview, but don't offer much in the way of quantitative comparison. Instead, we can directly compare the Bray-Curtis dissimilarity between methods, and utilize pairwise Mann-Whitney U tests to determine precisely which methods perform better (lower dissimilarity = more accurate classification). In the cell below, we will use distance comparisons to determine:
1) Whether the dissimilarity between taxonomic assignment with different parameters of the same method is greater or less than the dissimilarity between taxonomic assignments with different methods, including the expected composition.
2) which method (averaged across all configurations) most closely reproduces the expected composition.
You can generate boxplots for individual datasets one-by-one with per_method_boxplots()
, or for all datasets individually with fastlane_boxplots()
. However, here we are most interested in the average performance of methods across each dataset.
The command below violin plots of distribution of distances between expected composition and predicted compositions for each method (all parameter configurations) across all samples/datasets, and pairwise Mann Whitney U tests between these distributions.
In [12]:
boxes, best = average_distance_boxplots(expected_results_dir, paired=False,
use_best=False, color_palette=color_palette)
In [35]:
for k, v in boxes.items():
v.get_figure().savefig(join(outdir, 'mock-nonopt-distance-{0}-boxplots.pdf'.format(k)))
Reports the top-performing parameter configuration for each method, violin plots of distribution of distances between expected composition and predicted compositions for the top parameter for each method across all samples/datasets, and pairwise paired Wilcoxon signed rank tests between these distributions.
In [7]:
boxes, best = average_distance_boxplots(expected_results_dir, paired=False,
color_palette=color_palette)
In [38]:
for k, v in boxes.items():
v.get_figure().savefig(join(outdir, 'mock-opt-distance-{0}-boxplots.pdf'.format(k)))
In [24]:
a = best['gg_13_8_otus'].groupby(['method', 'params']).mean()
a = a.sort_values('distance')
a[a['distance'] < 0.51]
Out[24]:
In [ ]: