//                                               -*- C++ -*-
/**
 *  @file  NormalCopulaFactory.cxx
 *  @brief Factory for NormalCopula distribution
 *
 *  (C) Copyright 2005-2012 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 2.1 of the License.
 *
 *  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
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 *
 *  @author schueller
 *  @date   2012-07-16 10:12:54 +0200 (Mon, 16 Jul 2012)
 */
#include <cmath>
#include "NormalCopulaFactory.hxx"

BEGIN_NAMESPACE_OPENTURNS


CLASSNAMEINIT(NormalCopulaFactory);

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

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

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

NormalCopulaFactory::Implementation NormalCopulaFactory::build(const NumericalSample & sample) const
{
  if (sample.getSize() == 0) throw InvalidArgumentException(HERE) << "Error: cannot build a NormalCopula distribution from an empty sample";
  try
  {
    return NormalCopula(NormalCopula::GetCorrelationFromKendallCorrelation(sample.computeKendallTau())).clone();
  }
  catch (...)
  {
    LOGWARN(OSS() << "Warning! Unable to build a NormalCopula using Kendall's tau, trying Spearman's rho instead.");
    return NormalCopula(NormalCopula::GetCorrelationFromSpearmanCorrelation(sample.computeSpearmanCorrelation())).clone();
  }
}

NormalCopulaFactory::Implementation NormalCopulaFactory::build(const NumericalPointCollection & parameters) const
{
  try
  {
    NormalCopula copula;
    copula.setParametersCollection(parameters);
    return copula.clone();
  }
  catch (InvalidArgumentException & ex)
  {
    throw InvalidArgumentException(HERE) << "Error: cannot build a NormalCopula from the given parameters";
  }
}

NormalCopulaFactory::Implementation NormalCopulaFactory::build() const
{
  return NormalCopula().clone();
}


END_NAMESPACE_OPENTURNS
