// $Id: funcMax.cpp,v 1.11 2018/01/03 21:32:57 mkkuhner Exp $

/*
Copyright 2002-2005 Mary K. Kuhner, Peter Beerli, and Joseph Felsenstein

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.

*/

/* Authors: Mary Kuhner, Jon Yamato, and Joseph Felsenstein */


#include <iostream>
#include <fstream>

#include "errhandling.h"
#include "funcMax.h"

using namespace std;

FMState::FMState(int _max_iters,
                 double _increment,
                 double _threshold,
                 double _leftLimit,
                 double _rightLimit,
                 double _initX
    )
{
    max_iters = _max_iters;
    increment = _increment;
    threshold = _threshold;
    leftLimit = _leftLimit;
    rightLimit = _rightLimit;
    initX = _initX;
    //pf = _pf;
}

FuncMax::FuncMax(MixedKSModel& _mksModel,
                 Tree* _tree,
                 const Locus& _locus)
    :mksModel(_mksModel),
     dlcalc(_locus.GetDLCalc()),
     tree(_tree),
     locus(_locus),
     m_moving(_locus.IsMoving())
{
}

void FuncMax::setState(FMState fms)
{
    max_iters = fms.max_iters;
    increment = fms.increment;
    threshold = fms.threshold;
    leftLimit = fms.leftLimit;
    rightLimit = fms.rightLimit;
    initX = fms.initX;
    pf = fms.pf;
}

FMState FuncMax::getCurState()
{
    FMState fms(max_iters,
                increment,
                threshold,
                leftLimit,
                rightLimit,
                curX      //instead of initX
        );
    return fms;
}

double FuncMax::getCurX()
{
    return curX;
}

void FuncMax::run()
{
    char leftMark, rightMark;

    for(int i=0; i<max_iters; i++)
    {
#ifdef DEBUG_FILE
        *fs << "[org] ";
#endif
        curX = (leftLimit+rightLimit)/2;
        if(isInc(curX, rightLimit))
        {
            leftLimit = curX;
            leftMark = '*';
            rightMark = ' ';
        }
        else
        {
            rightLimit = curX;
            leftMark = ' ';
            rightMark = '*';
        }

#ifdef DEBUG_FILE
        *fs << "[" << leftMark
            << setw(10) << leftLimit << "  " << rightMark
            << setw(10) << rightLimit << "]" << endl;
#endif
        if(fabs(rightLimit-leftLimit) < threshold)
        {
#ifdef DEBUG_FILE
            *fs << "Stop since reached threshold." << endl;
#endif
            return;
        }
    }
#ifdef DEBUG_FILE
    *fs << "Stop after " << max_iters << " iterations." << endl;
#endif
}

double FuncMax::eval(double x)
{
    //set alpha
    mksModel.SetAlpha(x);
    tree->GetTimeList().SetAllUpdateDLs();
    double y=EXPMIN;
    try
    {
        y=dlcalc->Calculate(*tree, locus, m_moving);
    }
    catch (datalikenorm_error e)
    {
        //We turned on normalization.  This should only happen once.
        tree->GetTimeList().SetAllUpdateDLs();
        try
        {
            y=dlcalc->Calculate(*tree, locus, m_moving);
        }
        catch (zero_dl_error e)
        {
            //We'll say that this is due to a very bad alpha.
            return EXPMIN;
        }
    }
    catch (zero_dl_error e)
    {
        //We'll say that this is due to a very bad alpha.
        return EXPMIN;
    }
#ifdef DEBUG_FILE
    static int i = 0;
    *fs << setw(5) << i++;
    *fs << "x " << setw(10) << x;
    *fs << "y " << setw(10) << y;
#endif
    return y;
}

bool FuncMax::isInc(double x, double max)
{
    double y = eval(x);
#ifdef DEBUG_FILE
    *fs << "[inc] ";
#endif
    double _y = eval(min(x+increment, max));
    return _y > y;
}

//____________________________________________________________________________________
