#! python
""" Code to compute the chisquare increment

Context : SRP
Module  : SRPFTest.py
Author  : Stefano Covino
Date    : 08/04/2020
E-mail  : stefano.covino@brera.inaf.it
URL:    : http://www.merate.mi.astro.it/utenti/covino

Usage   : SRPFTest [-a arg1] [-c arg2] -d arg3 [-p arg4] [-v]
            -a is the accuracy of the chisquare increment computation
            -c is the resulting chisquare for a fit
            -d is the number of degrees of freedom
            -p is the probability.
           
         The routine allows one to compute the increment for the chi square having a probability
         100-prob% to occur randonmly. Typical usage is for deriving uncertainties for multiparametric
         fits. Alternatively, one can compute the probability to have randomly a higher chisquare than
         the one obtained in a fit.

Remarks : 

History : (07/06/2013) First version.
        : (24/07/2015) scipy porting.
        : (08/04/2020) Stand-alone package.
"""

import argparse, math
from SRPSTATS.FTest import FTest
import scipy.special


__version__ = '1.2.0'


parser = argparse.ArgumentParser()
parser.add_argument("-n", "--newmod", action="store", nargs=2, type=float, help="Chi2 and degrees of freedom", metavar=('chi2', 'dof'), required=True)
parser.add_argument("-o", "--oldmod", action="store", nargs=2, type=float, help="Chi2 and degrees of freedom", metavar=('chi2', 'dof'), required=True)
parser.add_argument("-v", "--verbose", action="store_true", help="Fully describe operations")
parser.add_argument("--version", action="version", version=__version__)
options = parser.parse_args()


if options.newmod[0] <= 0.0 or options.newmod[1] <= 0.0 or options.oldmod[0] <= 0.0 or options.oldmod[0] <= 0.0:
    parser.error("Chi2 and number of degrees of freedom must be positive.")
elif options.newmod[1] > options.oldmod[1]:
    parser.error("Number of degrees of freedom should be lower for the extended model.")
elif options.newmod[0] > options.oldmod[0]:
    parser.error("Chi2 should decrease for the extended model.")
else:
    F = FTest(options.oldmod[0], options.oldmod[1], options.newmod[0], options.newmod[1])
    fp = options.oldmod[1]-options.newmod[1]
    sp = options.oldmod[1]
    res = scipy.special.betainc(0.5*sp,0.5*fp,sp/(sp+fp*F))
    if options.verbose:
        print("F value: {}, 1-tail probability: {}".format(F, res))
    else:
        print(F, res)
#