#!/usr/bin/python3

# orthologer - Pipeline for deducing orthology from fasta files.
# Copyright (C) 2005-2023 E. Zdobnov lab: F. Tegenfeldt
# <fredrik.tegenfeldt@unige.ch> based on code by E. Kriventseva
#
# This file is part of orthologer.
#
# orthologer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# orthologer 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 orthologer.  If not, see <http://www.gnu.org/licenses/>.

'''
This is generic tool for getting basic statistics of columnwise data.
Pipeline usage: STATS
'''
from __future__ import print_function

import sys
import argparse
import numpy as np

def read_data( options ):
    val = []
    usehdr = options.useheader
    with open(options.filename) as fh:
        for line in fh.readlines():
            line = line.strip().rstrip('\n')
            if len(line)==0 or line[0] in '#':
                continue
            if usehdr:
                usehdr = False
                continue
            
            elems = line.split()
            if options.column >= len(elems):
                continue
            v = float(elems[options.column])
            val.append(v)
               
    return np.array(val)


def build_header( options ):
    header=''
    if options.dondata:
        header=header+'ndata '

    if options.domin:
        header=header+'min '

    if options.domax:
        header=header+'max '

    if options.domean:
        header=header+'mean '

    if options.domedian:
        header=header+'median '

    if options.dosum:
        header=header+'sum '

    if options.dostdev:
        header=header+'stdev '

    if options.dovar:
        header=header+'variance '
    return header
    

parser = argparse.ArgumentParser(description='Simple statistics tool')

parser.add_argument("-f", "--file", dest="filename",
                    help="read data from FILE", metavar="FILE", default=None)
parser.add_argument("-c", "--column", dest="column", type=int,
                    help="use data in column (0,1,..)", metavar="COL", default=None)
parser.add_argument("-u", "--useheader", dest="useheader", action="store_true",
                  help="assume first non-commented line is a header")
parser.add_argument("-N", "--ndata", dest="dondata", action="store_true",
                  help="get nr of data points")
parser.add_argument("-p", "--min", dest="domin", action="store_true",
                  help="get min value")
parser.add_argument("-g", "--max", dest="domax", action="store_true",
                  help="get max value")
parser.add_argument("-m", "--mean", dest="domean", action="store_true",
                  help="get mean value")
parser.add_argument("-M", "--median", dest="domedian", action="store_true",
                  help="get median value")
parser.add_argument("-S", "--sum", dest="dosum", action="store_true",
                  help="get sum")
parser.add_argument("-s", "--stdev", dest="dostdev", action="store_true",
                  help="get standard deviation")
parser.add_argument("-V", "--variance", dest="dovar", action="store_true",
                  help="get variance")
parser.add_argument("-H", "--header", dest="doheader", action="store_true",
                  help="add a header line")
parser.add_argument("-P", "--pheader", dest="printheader", action="store_true",
                  help="just print the header line")
#parser.add_argument('-f', '--fmt', dest='fmt', default='%m %M %s',
#                  help='output format', metavar='STRING')

options = parser.parse_args()
doany=options.dondata or options.domin or options.domax or options.domean or options.domedian or options.dostdev or options.dovar or options.dosum
if not doany:
    options.dondata=True
    options.domin=True
    options.domax=True
    options.domean=True
    options.domedian=True
    options.dosum=True
    options.dovar=True

header = build_header( options )

if options.printheader:
    print(header)
    sys.exit(0)

if options.filename is None:
    print('error: --file must be set')
    sys.exit(0)
if options.column is None:
    print('error: --column must be set')
    sys.exit(0)
##########################################################################


val=read_data(options)

outpstr=''
header='# '

if len(val)==0:
    print('# NO DATA')
    sys.exit(0)
    
if options.dondata:
    outpstr=outpstr+('%d ') % len(val)

if options.domin:
    outpstr=outpstr+('%g ') % np.min(val)

if options.domax:
    outpstr=outpstr+('%g ') % np.max(val)

if options.domean:
    outpstr=outpstr+('%g ') % np.mean(val)

if options.domedian:
    outpstr=outpstr+('%g ') % np.median(val)

if options.dosum:
    outpstr=outpstr+('%g ') % np.sum(val)

if options.dostdev:
    outpstr=outpstr+('%g ') % np.std(val)

if options.dovar:
    outpstr=outpstr+('%g ') % np.var(val)

if options.doheader:
    print( header )
print( outpstr )
