#!/usr/bin/env python3

# Copyright (c) 2017, 2019 Danny van Dyk
#
# This file is part of the EOS project. EOS is free software;
# you can redistribute it and/or modify it under the terms of the GNU General
# Public License version 2, as published by the Free Software Foundation.
#
# EOS is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307  USA

import argparse
import eos
from eos.data import *
from logging import error, info, warn
import os
import scipy, scipy.stats
import sys

def main():
    parser = argparse.ArgumentParser(description='Print mean and standard deviation from an uncertainty propagation')
    parser.add_argument('input', metavar='HDF5FILE', type=str, help='Name of the HDF5 input file')

    args = parser.parse_args()

    # ensure that the input file exists
    if not os.path.isfile(args.input):
        error('\'%s\' is not a file' % args.input)

    # open HDF5 data file
    basename = os.path.basename(args.input)
    if basename.startswith('mcmc_'):
        datafile = MCMCDataFile(args.input)
    elif basename.startswith('pmc_monolithic'):
        datafile = PMCDataFile(args.input)
    elif basename.startswith('unc'):
        datafile = UncertaintyDataFile(args.input)

    data = datafile.data()
    parameters = datafile.parameters

    for i in range(0, len(parameters)):
        print('# {} ({})'.format(parameters[i][0],parameters[i][1]))

        x = numpy.sort(data[:, i])
        print('        median: %f' % numpy.percentile(x, 50))
        print('  68% interval: [{:f}, {:f}]'.format(numpy.percentile(x, 16), numpy.percentile(x, 84)))
        print('  95% interval: [{:f}, {:f}]'.format(numpy.percentile(x, 2.5), numpy.percentile(x, 97.5)))
        print('  99% interval: [{:f}, {:f}]'.format(numpy.percentile(x, 0.5), numpy.percentile(x, 99.5)))

        print('  mean = %e' % numpy.mean(data[:, i]))
        print('   std = %e' % numpy.std(data[:, i]))
        print('  skew = %e' % scipy.stats.skew(data[:, i]))
        print('  kurt = %e' % scipy.stats.kurtosis(data[:, i], fisher=False))

    print('# covariance matrix')
    print(numpy.cov(data.T))

    print('# correlation matrix')
    corr = numpy.corrcoef(data.T)
    print(corr)
    print('# det(corr) = %g' % numpy.linalg.det(corr))

    exit(0);

if __name__ == '__main__':
    main()
