# Path: picrust/util.py
# def write_biom_table(biom_table, biom_table_fp, compress=True,
#                      write_hdf5=HAVE_H5PY, format_fs=None):
#     """Writes a BIOM table to the specified filepath
# 
#     Parameters
#     ----------
#     biom_table : biom.Table
#         The table object to write out
#     biom_table_fp : str
#         The path to the output file
#     compress : bool, optional
#         Defaults to ``True``. If True, built-in compression on the output HDF5
#         file will be enabled. This option is only relevant if ``write_hdf5`` is
#         ``True``.
#     write_hdf5 : bool, optional
#         Defaults to ``True`` if H5PY is installed and to ``False`` if H5PY is
#         not installed. If ``True`` the output biom table will be written as an
#         HDF5 binary file, otherwise it will be a JSON string.
#     format_fs : dict, optional
#         Formatting functions to be passed to `Table.to_hdf5`
# 
#     Notes
#     -----
#     This code was adapted from QIIME 1.9
#     """
#     generated_by = "PICRUSt " + __version__
# 
#     if write_hdf5:
#         with biom_open(biom_table_fp, 'w') as biom_file:
#             biom_table.to_hdf5(biom_file, generated_by, compress,
#                                format_fs=format_fs)
#     else:
#         with open(biom_table_fp, 'w') as biom_file:
#             biom_table.to_json(generated_by, biom_file)


import json
import h5py
from cogent.util.option_parsing import parse_command_line_parameters, make_option
from biom import load_table
from biom.table import vlen_list_of_str_formatter
from picrust.util import write_biom_table
    option_parser, opts, args =\
       parse_command_line_parameters(**script_info)

    if opts.level <= 0:
        option_parser.error("level must be greater than zero!")

    collapse_f = make_collapse_f(opts.metadata_category, opts.level,
                                 opts.ignore)
    table = load_table(opts.input_fp)

    if h5py.is_hdf5(opts.input_fp):
        # metadata are not deserializing correctly. Duct tape it.
        update_d = {}
        for i, md in zip(table.ids(axis='observation'),
                         table.metadata(axis='observation')):
            update_d[i] = {k: json.loads(v[0]) for k, v in md.items()}
        table.add_metadata(update_d, axis='observation')

    result = table.collapse(collapse_f, axis='observation', one_to_many=True,
                            norm=False,
                            one_to_many_md_key=opts.metadata_category)

    if(opts.format_tab_delimited):
        f = open(opts.output_fp, 'w')
        f.write(result.to_tsv(header_key=opts.metadata_category,
                              header_value=opts.metadata_category,
                              metadata_formatter=lambda s: '; '.join(s)))
        f.close()
    else:
        format_fs = {opts.metadata_category: vlen_list_of_str_formatter}

# Path: picrust/util.py
# def write_biom_table(biom_table, biom_table_fp, compress=True,
#                      write_hdf5=HAVE_H5PY, format_fs=None):
#     """Writes a BIOM table to the specified filepath
# 
#     Parameters
#     ----------
#     biom_table : biom.Table
#         The table object to write out
#     biom_table_fp : str
#         The path to the output file
#     compress : bool, optional
#         Defaults to ``True``. If True, built-in compression on the output HDF5
#         file will be enabled. This option is only relevant if ``write_hdf5`` is
#         ``True``.
#     write_hdf5 : bool, optional
#         Defaults to ``True`` if H5PY is installed and to ``False`` if H5PY is
#         not installed. If ``True`` the output biom table will be written as an
#         HDF5 binary file, otherwise it will be a JSON string.
#     format_fs : dict, optional
#         Formatting functions to be passed to `Table.to_hdf5`
# 
#     Notes
#     -----
#     This code was adapted from QIIME 1.9
#     """
#     generated_by = "PICRUSt " + __version__
# 
#     if write_hdf5:
#         with biom_open(biom_table_fp, 'w') as biom_file:
#             biom_table.to_hdf5(biom_file, generated_by, compress,
#                                format_fs=format_fs)
#     else:
#         with open(biom_table_fp, 'w') as biom_file:
#             biom_table.to_json(generated_by, biom_file)


# Path: scripts/categorize_by_function.py
import json
import h5py
from cogent.util.option_parsing import parse_command_line_parameters, make_option
from biom import load_table
from biom.table import vlen_list_of_str_formatter
from picrust.util import write_biom_table

    option_parser, opts, args =\
       parse_command_line_parameters(**script_info)

    if opts.level <= 0:
        option_parser.error("level must be greater than zero!")

    collapse_f = make_collapse_f(opts.metadata_category, opts.level,
                                 opts.ignore)
    table = load_table(opts.input_fp)

    if h5py.is_hdf5(opts.input_fp):
        # metadata are not deserializing correctly. Duct tape it.
        update_d = {}
        for i, md in zip(table.ids(axis='observation'),
                         table.metadata(axis='observation')):
            update_d[i] = {k: json.loads(v[0]) for k, v in md.items()}
        table.add_metadata(update_d, axis='observation')

    result = table.collapse(collapse_f, axis='observation', one_to_many=True,
                            norm=False,
                            one_to_many_md_key=opts.metadata_category)

    if(opts.format_tab_delimited):
        f = open(opts.output_fp, 'w')
        f.write(result.to_tsv(header_key=opts.metadata_category,
                              header_value=opts.metadata_category,
                              metadata_formatter=lambda s: '; '.join(s)))
        f.close()
    else:
        format_fs = {opts.metadata_category: vlen_list_of_str_formatter}

        write_biom_table(result, opts.output_fp, format_fs=format_fs)