//                                               -*- C++ -*-
/**
 *  @file  GeneralizedParetoFactory.cxx
 *  @brief Factory for GeneralizedPareto distribution
 *
 *  Copyright (C) 2005-2013 EDF-EADS-Phimeca
 *
 *  This library is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This library 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 Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  @author dutka
 *  @date   2007-05-10 16:43:31 +0200 (jeu. 10 mai 2007)
 */
#include "GeneralizedParetoFactory.hxx"

BEGIN_NAMESPACE_OPENTURNS

CLASSNAMEINIT(GeneralizedParetoFactory);

struct GeneralizedParetoFactoryParameterConstraint
{
  /** Constructor from a sample and a derivative factor estimate */
  GeneralizedParetoFactoryParameterConstraint(const NumericalSample & sample):
    sample_(sample),
    // Here we know that the min is positive, so is the max.
    thetaMax_(1.0 / sample.getMax()[0]),
    sumLog_(0.0)
  {
    // Nothing to do
  };

  NumericalPoint computeConstraint(const NumericalPoint & parameter) const
  {
    const NumericalScalar theta(parameter[0]);
    if (theta >= thetaMax_) throw InvalidArgumentException(HERE) << "Error: the theta parameter must be less than " << thetaMax_;
    const UnsignedLong size(sample_.getSize());
    /* \sum_{i=1}^N \log(1 - theta x_i) */
    sumLog_ = 0.0;
    for (UnsignedLong i = 0; i < size; ++i)
    {
      const NumericalScalar x(sample_[i][0]);
      sumLog_ += log1p(-theta * x);
    }
    return NumericalPoint(1, -size - sumLog_ - size * log(-sumLog_ / (size * theta)));
  }

  NumericalScalar getSumLog() const
  {
    return sumLog_;
  }
  const NumericalSample & sample_;
  NumericalScalar thetaMax_;
  NumericalScalar sumLog_;
};

/* Default constructor */
GeneralizedParetoFactory::GeneralizedParetoFactory()
  : DistributionImplementationFactory()
{
  // Nothing to do
}

/* Virtual constructor */
GeneralizedParetoFactory * GeneralizedParetoFactory::clone() const
{
  return new GeneralizedParetoFactory(*this);
}

/* Here is the interface that all derived class must implement */

GeneralizedParetoFactory::Implementation GeneralizedParetoFactory::build(const NumericalSample & sample) const
{
  return buildAsGeneralizedPareto(sample).clone();
}

GeneralizedParetoFactory::Implementation GeneralizedParetoFactory::build(const NumericalPointCollection & parameters) const
{
  return buildAsGeneralizedPareto(parameters).clone();
}

GeneralizedParetoFactory::Implementation GeneralizedParetoFactory::build() const
{
  return buildAsGeneralizedPareto().clone();
}

GeneralizedPareto GeneralizedParetoFactory::buildAsGeneralizedPareto(const NumericalSample & sample) const
{
  if (sample.getSize() == 0) throw InvalidArgumentException(HERE) << "Error: cannot build a GeneralizedPareto distribution from an empty sample";
  if (sample.getDimension() != 1) throw InvalidArgumentException(HERE) << "Error: can build a GeneralizedPareto distribution only from a sample of dimension 1, here dimension=" << sample.getDimension();

  if (sample.getMin()[0] <= 0.0) throw InvalidArgumentException(HERE) << "Error: cannot build a GeneralizedPareto distribution based on a sample with nonpositive values.";
  GeneralizedParetoFactoryParameterConstraint constraint(sample);
  const NumericalMathFunction f(bindMethod<GeneralizedParetoFactoryParameterConstraint, NumericalPoint, NumericalPoint>(constraint, &GeneralizedParetoFactoryParameterConstraint::computeConstraint, 1, 1));
  // Find a bracketing interval
  NumericalScalar a(1.0);
  NumericalScalar b(2.0);
  NumericalScalar fA(f(NumericalPoint(1, a))[0]);
  NumericalScalar fB(f(NumericalPoint(1, b))[0]);
  // While f has the same sign at the two bounds, update the interval
  while ((fA * fB > 0.0))
  {
    a = 0.5 * a;
    fA = f(NumericalPoint(1, a))[0];
    if (fA * fB <= 0.0) break;
    b = 2.0 * b;
    fB = f(NumericalPoint(1, b))[0];
  }
  // Solve the constraint equation
  Brent solver(ResourceMap::GetAsNumericalScalar( "GeneralizedParetoFactory-AbsolutePrecision" ), ResourceMap::GetAsNumericalScalar( "GeneralizedParetoFactory-RelativePrecision" ), ResourceMap::GetAsNumericalScalar( "GeneralizedParetoFactory-ResidualPrecision" ), ResourceMap::GetAsUnsignedLong( "GeneralizedParetoFactory-MaximumIteration" ));
  // C estimate
  const NumericalScalar c(solver.solve(f, 0.0, a, b, fA, fB));
  // Corresponding k estimate
  NumericalScalar sumLogXC(0.0);
  for (UnsignedLong i = 0; i < size; ++i) sumLogXC += log1p(pow(sample[i][0], c));
  const NumericalScalar k(size / sumLogXC);
  return GeneralizedPareto(c, k);
}


GeneralizedPareto GeneralizedParetoFactory::buildAsGeneralizedPareto(const NumericalPointWithDescriptionCollection & parameters) const
{
  return buildAsGeneralizedPareto(RemoveDescriptionFromCollection(parameters));
}

GeneralizedPareto GeneralizedParetoFactory::buildAsGeneralizedPareto(const NumericalPointCollection & parameters) const
{
  try
  {
    GeneralizedPareto distribution;
    distribution.setParametersCollection(parameters);
    return distribution;
  }
  catch (InvalidArgumentException & ex)
  {
    throw InvalidArgumentException(HERE) << "Error: cannot build a GeneralizedPareto distribution from the given parameters";
  }
}

GeneralizedPareto GeneralizedParetoFactory::buildAsGeneralizedPareto() const
{
  return GeneralizedPareto();
}

END_NAMESPACE_OPENTURNS
