# ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------
'''
neon visualization script.

Visualize data generated by running neon with --output_file.

For example these commands run an experiment in neon and collect metrics, then
use nvis to visualize them.

    neon <yaml path> -o mnist.h5
    nvis -i mnist.h5 -o mnist.html

HDF5 currently does not support reading while open for writing. An upcoming HDF5
release should support this officially, but in the meantime neon flushes the output
file once per epoch which generally leaves the file in a good state for periodic
inspection with nvis.

For details of all the command line arguments run this script with
the --help option.
'''
import os
import logging
import argparse
from bokeh import plotting
from neon.visualizations.figure import cost_fig, hist_fig, deconv_summary_page
from neon.visualizations.data import h5_cost_data, h5_hist_data, h5_deconv_data

logging.basicConfig(level=20)
logger = logging.getLogger()


def parse_args():
    """
    Parse command line args.
    """
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('--axis', choices=['epoch', 'minibatch'], default='epoch',
                        help='display time plots on either an epoch or minibatch axis.'
                             ' default=epoch')

    static_grp = parser.add_argument_group('Static HTML Generator')

    static_grp.add_argument('--in_file', '-i', required=True,
                            help='input hdf5 file containing data generated by running'
                                 ' an experiment in neon')

    static_grp.add_argument('--out_dir', '-o', default=os.getcwd() + "/nvis/",
                            help='output folder to write visualizations (./nvis/ by default)')

    return parser.parse_args()


def static_plot(args, plot_height=400, plot_width=600):
    """
    Generate a static html plot with train and validation cost if present in file.
    Deconvolution plots for each layer will also be generated if deconvolution data is present.
    """
    if not os.path.exists(args.out_dir):
        os.makedirs(args.out_dir)

    epoch_axis = args.axis == 'epoch'
    cost_data = h5_cost_data(args.in_file, epoch_axis)
    hist_data = h5_hist_data(args.in_file, epoch_axis)

    figs = []
    figs.append(cost_fig(cost_data, plot_height, plot_width, epoch_axis=epoch_axis))
    shared_x_range = figs[0].x_range
    if hist_data:
        for hist in hist_data:
            figs.append(hist_fig(hist, plot_height // 2, plot_width,
                                 x_range=shared_x_range, epoch_axis=epoch_axis))

    plotting.output_file(os.path.join(args.out_dir, "cost-hist.html"))
    plotting.save(plotting.vplot(*figs))

    # deconv plots
    deconv_data = h5_deconv_data(args.in_file)
    if deconv_data is not None:
        deconv_summary_page(os.path.join(args.out_dir, "deconv.html"), cost_data, deconv_data)


if __name__ == "__main__":
    args = parse_args()
    if args.in_file and args.out_dir:
        static_plot(args)
