//                                               -*- C++ -*-
/**
 *  @file  InverseNormalFactory.cxx
 *  @brief Factory for InverseNormal 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   2011-04-11 12:32:27 +0200 (lun. 11 avril 2011)
 */
#include <cmath>
#include "InverseNormalFactory.hxx"

BEGIN_NAMESPACE_OPENTURNS



CLASSNAMEINIT(InverseNormalFactory);

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

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

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

InverseNormalFactory::Implementation InverseNormalFactory::build(const NumericalSample & sample) const
{
  const UnsignedLong size(sample.getSize());
  if (size == 0) throw InvalidArgumentException(HERE) << "Error: cannot build an InverseNormal distribution from an empty sample";
  if (sample.getDimension() != 1) throw InvalidArgumentException(HERE) << "Error: cannot build an InverseNormal distribution from a sample of dimension different from 1";
  const NumericalScalar mu(sample.computeMean()[0]);
  NumericalScalar sum(0.0);
  for (UnsignedLong i = 0; i < size; ++i)
  {
    const NumericalScalar xI(sample[i][0]);
    if (xI <= 0.0) throw InvalidArgumentException(HERE) << "Error: cannot build an InverseNormal distribution from a sample with non positive values";
    sum += 1.0 / sample[i][0];
  }
  const NumericalScalar lambda(1.0 / (sum / size - 1.0 / mu));
  return InverseNormal(lambda, mu).clone();
}

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

InverseNormalFactory::Implementation InverseNormalFactory::build() const
{
  return InverseNormal().clone();
}


END_NAMESPACE_OPENTURNS
