| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
# ---------------------------------------------------------------------------- |
| 4 |
# Copyright (c) 2011-2017, The BIOM Format Development Team. |
| 5 |
# |
| 6 |
# Distributed under the terms of the Modified BSD License. |
| 7 |
# |
| 8 |
# The full license is in the file COPYING.txt, distributed with this software. |
| 9 |
# ---------------------------------------------------------------------------- |
| 10 |
|
| 11 |
|
| 12 |
import click |
| 13 |
|
| 14 |
from biom import load_table |
| 15 |
from biom.cli import cli |
| 16 |
from biom.cli.util import write_biom_table |
| 17 |
|
| 18 |
|
| 19 |
@cli.command(name='normalize-table') |
| 20 |
@click.option('-i', '--input-fp', required=True, |
| 21 |
type=click.Path(exists=True, dir_okay=False), |
| 22 |
help='The input BIOM table') |
| 23 |
@click.option('-o', '--output-fp', default=None, |
| 24 |
type=click.Path(writable=True), |
| 25 |
help='An output file-path') |
| 26 |
@click.option('-r', '--relative-abund', default=False, is_flag=True, |
| 27 |
help='convert table to relative abundance', |
| 28 |
required=False) |
| 29 |
@click.option('-p', '--presence-absence', default=False, is_flag=True, |
| 30 |
help='convert table to presence/absence', |
| 31 |
required=False) |
| 32 |
@click.option('-a', '--axis', default='sample', |
| 33 |
type=click.Choice(['sample', 'observation']), |
| 34 |
help='The axis to normalize over') |
| 35 |
def normalize_table(input_fp, output_fp, relative_abund, presence_absence, |
| 36 |
axis): |
| 37 |
"""Normalize a BIOM table. |
| 38 |
|
| 39 |
Normalize the values of a BIOM table through various methods. Relative |
| 40 |
abundance will take the relative abundance of each observation in terms of |
| 41 |
samples or observations. Presence absensece will convert observations to |
| 42 |
1's and 0's based on presence of the observation. |
| 43 |
|
| 44 |
Example usage: |
| 45 |
|
| 46 |
Normalizing a BIOM table to relative abundnace: |
| 47 |
|
| 48 |
$ biom normalize-table -i table.biom -r -o normalized_table.biom |
| 49 |
|
| 50 |
Converting a BIOM table to a presence/absence table: |
| 51 |
|
| 52 |
$ biom normalize-table -i table.biom -p -o converted_table.biom |
| 53 |
""" |
| 54 |
table = load_table(input_fp) |
| 55 |
result = _normalize_table(table, relative_abund, presence_absence, axis) |
| 56 |
|
| 57 |
write_biom_table(result, 'hdf5', output_fp) |
| 58 |
|
| 59 |
|
| 60 |
def _normalize_table(table, relative_abund=False, presence_absence=False, |
| 61 |
axis='sample'): |
| 62 |
if relative_abund is False and presence_absence is False: |
| 63 |
raise ValueError("Must specifiy a normalization type") |
| 64 |
elif relative_abund is True and presence_absence is True: |
| 65 |
raise ValueError("Must specify only one normalization type") |
| 66 |
|
| 67 |
if relative_abund: |
| 68 |
table.norm(axis=axis) |
| 69 |
else: |
| 70 |
table.pa() |
| 71 |
|
| 72 |
return table |