// $Id: prior.cpp,v 1.14 2018/01/03 21:33:04 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: Peter Beerli, Mary Kuhner, Jon Yamato and Joseph Felsenstein */


#include <cassert>

#include "local_build.h"                // for definition of LAMARC_NEW_FEATURE_RELATIVE_SAMPLING

#include "defaults.h"
#include "mathx.h"
#include "paramstat.h"
#include "prior.h"
#include "random.h"
#include "registry.h"
#include "stringx.h"
#include "ui_vars_prior.h"

//------------------------------------------------------------------------------------

Prior::Prior(UIVarsPrior uiprior)
    : m_priortype(uiprior.GetPriorType()),
      m_lowerbound(uiprior.GetLowerBound()),
      m_upperbound(uiprior.GetUpperBound()),
      m_binwidth(uiprior.GetBinwidth())
#ifdef LAMARC_NEW_FEATURE_RELATIVE_SAMPLING
    , m_samplingRate(uiprior.GetRelativeSampling())
#endif
{
    //We don't worry about growth, since those are constrained to not have log priors.
    m_lnlower = SafeLog(m_upperbound);
    m_lnupper = SafeLog(m_lowerbound);
}

//------------------------------------------------------------------------------------

Prior::Prior(ParamStatus shouldBeInvalid)
    : m_priortype(LINEAR),
      m_lowerbound(0),
      m_upperbound(0),
      m_lnlower(0),
      m_lnupper(0),
      m_binwidth(1)
#ifdef LAMARC_NEW_FEATURE_RELATIVE_SAMPLING
    , m_samplingRate(defaults::samplingRate)
#endif

{
    assert(shouldBeInvalid.Status() == pstat_invalid);
}

//------------------------------------------------------------------------------------

Prior::~Prior()
{
    // intentionally blank
}

//------------------------------------------------------------------------------------

bool Prior::operator==(const Prior src) const
{
    if (m_priortype != src.m_priortype) return false;
    if (m_lowerbound != src.m_lowerbound) return false;
    if (m_upperbound != src.m_upperbound) return false;
#ifdef LAMARC_NEW_FEATURE_RELATIVE_SAMPLING
    if (m_samplingRate != src.m_samplingRate) return false;
#endif
    return true;
}

//------------------------------------------------------------------------------------

std::pair<double, double> Prior::RandomDraw() const
{
    Random& rnd = registry.GetRandom();
    double newparam = 0, newlnparam = 0;
    switch (m_priortype)
    {
        case LINEAR:
            newparam = rnd.Float() * (m_upperbound - m_lowerbound) + m_lowerbound;
            newlnparam = log(newparam);
            return std::make_pair(newparam, newlnparam);
            break;
        case LOGARITHMIC:
            newlnparam = rnd.Float() * (m_lnupper - m_lnlower) + m_lnlower;
            newparam = exp(newlnparam);
            return std::make_pair(newparam, newlnparam);
            break;
    }
    string e = "Unknown prior type " + ToString(m_priortype) +
        " in Parameter::DrawFromPrior";
    throw implementation_error(e);
} // RandomDraw

//____________________________________________________________________________________

std::pair<double,double> Prior::RandomDrawWithReflection(double current, double windowfraction) const
{
    Random& rnd = registry.GetRandom();
    double newparam = 0, newlnparam = 0;
    double delta = windowfraction * (m_upperbound - m_lowerbound);
    switch (m_priortype)
    {
         case LINEAR:
            newparam = current + (rnd.Float() - 0.5) * delta;
            if (newparam <= m_lowerbound) 
            {
                newparam = - newparam + 2.0 * m_lowerbound; 
            }
            else if (newparam >= m_upperbound) 
            {
                newparam = 2.0 * m_upperbound - newparam;
            }
            return std::make_pair(newparam, log(newparam));
            break;
         case LOGARITHMIC:
            string e = "Cannot use prior type " + ToString(m_priortype) +
                " in Parameter::RandomDrawWithReflection";
            throw implementation_error(e);
            break;
    }
    string e = "Unknown prior type " + ToString(m_priortype) +
        " in Parameter::RandomDrawWithReflection";
    throw implementation_error(e);
} // RandomDrawWithReflection

//______________________________________________________________________________________________

std::pair<double, double> Prior::RandomDrawWithinBounds(double lower, double upper) const
{
  Random& rnd = registry.GetRandom();
  double newparam = 0, newlnparam = 0;
  double lowbound = std::max(m_lowerbound, lower);
  double upbound = std::min(m_upperbound, upper);
  switch (m_priortype)
  {
         case LINEAR:
            newparam = rnd.Float() * (upbound - lowbound) + lowbound;
            newlnparam = log(newparam);
            return std::make_pair(newparam, newlnparam);
            break;
         case LOGARITHMIC:
            lowbound = log(lowbound);
            upbound = log(upbound);
            newlnparam = rnd.Float() * (upbound - lowbound) + lowbound;
            newparam = exp(newlnparam);
            return std::make_pair(newparam, newlnparam);
            break;
  }
  string e = "Unknown prior type " + ToString(m_priortype) +
      " in Parameter::RandomDrawWithinBounds";
  throw implementation_error(e);

} // RandomDrawWithinBounds
