# Path: alis/almsgs.py
# class Colors:
# class msgs:
#     def disable(self):
#     def __init__(self):
#     def alisheader(self, prognm, verbose=2):
#     def signal_handler(self, signalnum, handler):
#     def error(self, msg, verbose=None):
#     def info(self, msg, verbose=None):
#     def warn(self, msg, verbose=None):
#     def test(self, msg, verbose=None):
#     def bug(self, msg, verbose=None):
#     def work(self, msg, verbose=None):
#     def input(self):
#     def newline(self,verbose=None):
#     def indent(self,verbose=None):
# 
# Path: alis/alfunc_base.py
# class Base :
#     def __init__(self, prgname="", getinst=False, atomic=None, verbose=2):
#     def call_CPU(self, x, p, ae='em', mkey=None, ncpus=1):
#         def model():
#     def call_GPU(self, x, p, ae='em'):
#     def adjust_fix(self, mp, cntr, jval, parj):
#     def adjust_lim(self, mp, cntr, jval, jind, parj):
#     def getminmax(self, par, fitrng, Nsig=5.0):
#     def load(self, instr, cntr, mp, specid):
#         def check_tied_param(ival, cntr, mps, iind):
#     def parin(self, i, par, parb):
#     def parout(self, params, mp, istart, level, errs=None, reletter=False, conv=None):
#     def set_pinfo(self, pinfo, level, mp, lnk, mnum):
#     def set_vars(self, p, level, mp, ival, wvrng=[0.0,0.0], spid='None', levid=None, nexbin=None, ddpid=None, getinfl=False):
#     def gtoef(self, num, fmt):
#     def tick_info(self, p, level, mp, ival, wvrng=[0.0,0.0], spid='None', levid=None):
# def call(prgname="",getfuncs=False,getinst=False,atomic=None,verbose=2):
# 
# Path: alis/alutils.py
# def getreason(idnum,verbose=2):
#     if   idnum == 1: return "Both actual and predicted relative reductions in the sum of squares are at most ftol"
#     elif idnum == 2: return "Relative error between two consecutive iterates is at most xtol"
#     elif idnum == 3: return "Both actual and predicted relative reductions in the sum of squares are at most ftol and the relative error between two consecutive iterates is at most xtol"
#     elif idnum == 4: return "The cosine of the angle between fvec and any column of the jacobian is at most gtol in absolute value"
#     elif idnum == 5: return "The maximum number of iterations has been reached"
#     elif idnum == 6: return "ftol is too small. No further reduction in the sum of squares is possible"
#     elif idnum == 7: return "xtol is too small. No further improvement in the approximate solution x is possible"
#     elif idnum == 8: return "gtol is too small. fvec is orthogonal to the columns of the jacobian to machine precision"
#     elif idnum == 9: return "The relative reduction in the sum of squares is less than atol"
#     else:
#         msgs.bug("Convergence reason is unknown (probably failed) --- please contact the author",verbose=verbose)
#         return "Convergence reason is unknown (probably failed) --- please contact the author"


import os
import copy
import numpy as np
import datetime
import astropy.io.fits as pyfits
from alis import almsgs
from alis import alfunc_base
from matplotlib import pyplot as plt
from matplotlib import cm as pltcm
from alis.alutils import getreason
                shestring += errstr
            else:
                outstring += outstr
                errstring += errstr
    if blind: return outstring
    if getlines:
        if errs is None:
            return outstring.split("\n"), [cvstring.split("\n"),cvastring.split("\n"),shstring.split("\n"),shastring.split("\n")]
        else:
            return outstring.split("\n"), errstring.split("\n"), [cvstring.split("\n"),cvestring.split("\n"),cvastring.split("\n"),shstring.split("\n"),shestring.split("\n"),shastring.split("\n")]
    if errs is None:
        return outstring, [cvstring,cvastring,shstring,shastring]
    else:
        return outstring, errstring, [cvstring,cvestring,cvastring,shstring,shestring,shastring]


def save_model(slf,params,errors,info,printout=True,extratxt=["",""],filename=None,getlines=False,save=True):
    """
    Save the input model into an output script
    that can be run as input.
    """
    msgs.info("Saving the best-fitting model parameters", verbose=slf._argflag['out']['verbose'])
    if filename is None:
        filename = extratxt[0]+slf._argflag['out']['modelname']+extratxt[1]
    prestringA = "#\n#  Generated by ALIS on {0:s}\n#\n".format(datetime.datetime.now().strftime("%d/%m/%y at %H:%M:%S"))
    prestringA += "#   Running Time (hrs)  = {0:f}\n".format(info[0])
    prestringA += "#   Initial Chi-Squared = {0:f}\n".format(slf._chisq_init)
    prestringA += "#   Bestfit Chi-Squared = {0:f}\n".format(info[1])
    prestringA += "#   Degrees-of-Freedom  = {0:d}\n".format(info[2])
    prestringA += "#   Num. of Iterations  = {0:d}\n".format(info[3])

# Path: alis/almsgs.py
# class Colors:
# class msgs:
#     def disable(self):
#     def __init__(self):
#     def alisheader(self, prognm, verbose=2):
#     def signal_handler(self, signalnum, handler):
#     def error(self, msg, verbose=None):
#     def info(self, msg, verbose=None):
#     def warn(self, msg, verbose=None):
#     def test(self, msg, verbose=None):
#     def bug(self, msg, verbose=None):
#     def work(self, msg, verbose=None):
#     def input(self):
#     def newline(self,verbose=None):
#     def indent(self,verbose=None):
# 
# Path: alis/alfunc_base.py
# class Base :
#     def __init__(self, prgname="", getinst=False, atomic=None, verbose=2):
#     def call_CPU(self, x, p, ae='em', mkey=None, ncpus=1):
#         def model():
#     def call_GPU(self, x, p, ae='em'):
#     def adjust_fix(self, mp, cntr, jval, parj):
#     def adjust_lim(self, mp, cntr, jval, jind, parj):
#     def getminmax(self, par, fitrng, Nsig=5.0):
#     def load(self, instr, cntr, mp, specid):
#         def check_tied_param(ival, cntr, mps, iind):
#     def parin(self, i, par, parb):
#     def parout(self, params, mp, istart, level, errs=None, reletter=False, conv=None):
#     def set_pinfo(self, pinfo, level, mp, lnk, mnum):
#     def set_vars(self, p, level, mp, ival, wvrng=[0.0,0.0], spid='None', levid=None, nexbin=None, ddpid=None, getinfl=False):
#     def gtoef(self, num, fmt):
#     def tick_info(self, p, level, mp, ival, wvrng=[0.0,0.0], spid='None', levid=None):
# def call(prgname="",getfuncs=False,getinst=False,atomic=None,verbose=2):
# 
# Path: alis/alutils.py
# def getreason(idnum,verbose=2):
#     if   idnum == 1: return "Both actual and predicted relative reductions in the sum of squares are at most ftol"
#     elif idnum == 2: return "Relative error between two consecutive iterates is at most xtol"
#     elif idnum == 3: return "Both actual and predicted relative reductions in the sum of squares are at most ftol and the relative error between two consecutive iterates is at most xtol"
#     elif idnum == 4: return "The cosine of the angle between fvec and any column of the jacobian is at most gtol in absolute value"
#     elif idnum == 5: return "The maximum number of iterations has been reached"
#     elif idnum == 6: return "ftol is too small. No further reduction in the sum of squares is possible"
#     elif idnum == 7: return "xtol is too small. No further improvement in the approximate solution x is possible"
#     elif idnum == 8: return "gtol is too small. fvec is orthogonal to the columns of the jacobian to machine precision"
#     elif idnum == 9: return "The relative reduction in the sum of squares is less than atol"
#     else:
#         msgs.bug("Convergence reason is unknown (probably failed) --- please contact the author",verbose=verbose)
#         return "Convergence reason is unknown (probably failed) --- please contact the author"


# Path: alis/alsave.py
import os
import copy
import numpy as np
import datetime
import astropy.io.fits as pyfits
from alis import almsgs
from alis import alfunc_base
from matplotlib import pyplot as plt
from matplotlib import cm as pltcm
from alis.alutils import getreason

                shestring += errstr
            else:
                outstring += outstr
                errstring += errstr
    if blind: return outstring
    if getlines:
        if errs is None:
            return outstring.split("\n"), [cvstring.split("\n"),cvastring.split("\n"),shstring.split("\n"),shastring.split("\n")]
        else:
            return outstring.split("\n"), errstring.split("\n"), [cvstring.split("\n"),cvestring.split("\n"),cvastring.split("\n"),shstring.split("\n"),shestring.split("\n"),shastring.split("\n")]
    if errs is None:
        return outstring, [cvstring,cvastring,shstring,shastring]
    else:
        return outstring, errstring, [cvstring,cvestring,cvastring,shstring,shestring,shastring]


def save_model(slf,params,errors,info,printout=True,extratxt=["",""],filename=None,getlines=False,save=True):
    """
    Save the input model into an output script
    that can be run as input.
    """
    msgs.info("Saving the best-fitting model parameters", verbose=slf._argflag['out']['verbose'])
    if filename is None:
        filename = extratxt[0]+slf._argflag['out']['modelname']+extratxt[1]
    prestringA = "#\n#  Generated by ALIS on {0:s}\n#\n".format(datetime.datetime.now().strftime("%d/%m/%y at %H:%M:%S"))
    prestringA += "#   Running Time (hrs)  = {0:f}\n".format(info[0])
    prestringA += "#   Initial Chi-Squared = {0:f}\n".format(slf._chisq_init)
    prestringA += "#   Bestfit Chi-Squared = {0:f}\n".format(info[1])
    prestringA += "#   Degrees-of-Freedom  = {0:d}\n".format(info[2])
    prestringA += "#   Num. of Iterations  = {0:d}\n".format(info[3])

    prestringA += "#   Convergence Reason  = {0:s}\n".format(getreason(info[4],verbose=slf._argflag['out']['verbose']))