//                                               -*- C++ -*-
/**
 *  @brief The FiniteDiscreteDistribution distribution
 *
 *  Copyright 2005-2026 Airbus-EDF-IMACS-ONERA-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 License
 *  along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <cmath>
#include "openturns/FiniteDiscreteDistribution.hxx"
#include "openturns/RandomGenerator.hxx"
#include "openturns/SpecFunc.hxx"
#include "openturns/DistFunc.hxx"
#include "openturns/PersistentObjectFactory.hxx"

BEGIN_NAMESPACE_OPENTURNS

CLASSNAMEINIT(FiniteDiscreteDistribution)
static const Factory<FiniteDiscreteDistribution> Factory_FiniteDiscreteDistribution;
static const Factory<FiniteDiscreteDistribution> Factory_UserDefined("UserDefined");


/* Default constructor */
FiniteDiscreteDistribution::FiniteDiscreteDistribution()
  : DistributionImplementation()
  , points_(1, 1)
  , probabilities_(1, 1.0)
  , cumulativeProbabilities_(1, 1.0)
  , hasUniformWeights_(true)
  , base_(0)
  , alias_(0)
{
  setName("FiniteDiscreteDistribution");
  setData(Sample(1, 1), Point(1, 1.0));
}

/* Constructor from a sample */
FiniteDiscreteDistribution::FiniteDiscreteDistribution(const Sample & sample)
  : DistributionImplementation()
  , points_(0, 0)
  , probabilities_(0)
  , cumulativeProbabilities_(0)
  , hasUniformWeights_(true)
  , base_(0)
  , alias_(0)
{
  setName("FiniteDiscreteDistribution");
  const UnsignedInteger size = sample.getSize();
  // We set the dimension of the FiniteDiscreteDistribution distribution
  // This call set also the range
  setData(sample, Point(size, 1.0 / size));
  if ((getDimension() == 1) || (sample.getSize() <= ResourceMap::GetAsUnsignedInteger("FiniteDiscreteDistribution-SmallSize"))) compactSupport();
  if(!sample.getDescription().isBlank()) setDescription(sample.getDescription());
}

/* Constructor from a sample and the associated weights */
FiniteDiscreteDistribution::FiniteDiscreteDistribution(const Sample & sample,
    const Point & weights)
  : DistributionImplementation()
  , points_(0, 0)
  , probabilities_(0)
  , cumulativeProbabilities_(0)
  , hasUniformWeights_(false)
  , base_(0)
  , alias_(0)
{
  setName("FiniteDiscreteDistribution");
  // We set the dimension of the FiniteDiscreteDistribution distribution
  // This call set also the range
  setData(sample, weights);
  if ((getDimension() == 1) || (sample.getSize() <= ResourceMap::GetAsUnsignedInteger("FiniteDiscreteDistribution-SmallSize"))) compactSupport();
  if(!sample.getDescription().isBlank()) setDescription(sample.getDescription());
}

/* Tell if the distribution is continuous */
Bool FiniteDiscreteDistribution::isContinuous() const
{
  return false;
}

/* Tell if the distribution is discrete */
Bool FiniteDiscreteDistribution::isDiscrete() const
{
  return true;
}

/* Tell if the distribution is integer valued */
Bool FiniteDiscreteDistribution::isIntegral() const
{
  if (getDimension() != 1) return false;
  const UnsignedInteger size = points_.getSize();
  for (UnsignedInteger i = 0; i < size; ++i)
  {
    const Scalar x = points_(i, 0);
    if (std::abs(x - round(x)) >= supportEpsilon_) return false;
  }
  return true;
}

/* Comparison operator */
Bool FiniteDiscreteDistribution::operator ==(const FiniteDiscreteDistribution & other) const
{
  if (this == &other) return true;
  return (points_ == other.points_) && (probabilities_ == other.probabilities_);
}

Bool FiniteDiscreteDistribution::equals(const DistributionImplementation & other) const
{
  const FiniteDiscreteDistribution* p_other = dynamic_cast<const FiniteDiscreteDistribution*>(&other);
  return p_other && (*this == *p_other);
}

/* String converter */
String FiniteDiscreteDistribution::__repr__() const
{
  OSS oss;
  oss << "class=" << FiniteDiscreteDistribution::GetClassName()
      << " name=" << getName()
      << " dimension=" << getDimension()
      << " points=" << points_
      << " probabilities=" << probabilities_;
  return oss;
}

String FiniteDiscreteDistribution::__str__(const String & ) const
{
  OSS oss;
  oss << getClassName() << "(";
  String separator("");
  for (UnsignedInteger i = 0; i < points_.getSize(); ++i)
  {
    oss << separator << "{x = " << Point(points_[i]).__str__() << ", p = " << probabilities_[i] << "}";
    separator = ", ";
  }
  oss << ")";
  return oss;
}

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

/* Get one realization of the distribution */
Point FiniteDiscreteDistribution::getRealization() const
{
  const UnsignedInteger size = points_.getSize();
  UnsignedInteger index = 0;
  // Efficient algorithm for uniform weights
  if (hasUniformWeights_) index = RandomGenerator::IntegerGenerate(size);
  // Alias method for nonuniform weights
  else index = DistFunc::rDiscrete(base_, alias_);
  return points_[index];
}

/* Get a sample of the distribution */
Sample FiniteDiscreteDistribution::getSample(const UnsignedInteger size) const
{
  const UnsignedInteger supportSize = points_.getSize();
  Indices indices;
  // Efficient algorithm for uniform weights
  if (hasUniformWeights_)
  {
    Collection<UnsignedInteger> values(RandomGenerator::IntegerGenerate(size, supportSize));
    indices = Indices(values.begin(), values.end());
  }
  // Alias method for nonuniform weights
  else
    indices = DistFunc::rDiscrete(base_, alias_, size);
  return points_.select(indices);
}

/* Get the PDF of the distribution */
Scalar FiniteDiscreteDistribution::computePDF(const Point & point) const
{
  const UnsignedInteger dimension = getDimension();
  if (point.getDimension() != dimension) throw InvalidArgumentException(HERE) << "Error: the given point must have dimension=" << dimension << ", here dimension=" << point.getDimension();

  const UnsignedInteger size = points_.getSize();
  Scalar pdf = 0.0;
  // Quick search for 1D case
  const Scalar x = point[0];
  UnsignedInteger upper = size - 1;
  Scalar xUpper = points_(upper, 0);
  if (x > xUpper + supportEpsilon_) return 0.0;
  UnsignedInteger lower = 0;
  Scalar xLower = points_(lower, 0);
  if (x < xLower - supportEpsilon_) return 0.0;
  // Use bisection search of the correct index
  while (upper - lower > 1)
  {
    // The integer arithmetic ensure that middle will be strictly between lower and upper as far as upper - lower > 1
    const UnsignedInteger middle = (upper + lower) / 2;
    const Scalar xMiddle = points_(middle, 0);
    if (xMiddle > x + supportEpsilon_)
    {
      upper = middle;
      xUpper = xMiddle;
    }
    else
    {
      lower = middle;
      xLower = xMiddle;
    }
  } // while
  // At this point we have upper == lower or upper == lower + 1, with lower - epsilon <= x < upper + epsilon
  SignedInteger index = upper;
  while ((index < static_cast<SignedInteger>(size)) && (std::abs(x - points_(index, 0)) <= supportEpsilon_))
  {
    if ((point - points_[index]).norm() <= supportEpsilon_) pdf += probabilities_[index];
    ++ index;
  }
  index = upper;
  --index;
  while ((index >= 0) && (std::abs(x - points_(index, 0)) <= supportEpsilon_))
  {
    if ((point - points_[index]).norm() <= supportEpsilon_) pdf += probabilities_[index];
    --index;
  }
  return pdf;
}

/* Get the CDF of the distribution */
Scalar FiniteDiscreteDistribution::computeCDF(const Point & point) const
{
  if (point.getDimension() != getDimension()) throw InvalidArgumentException(HERE) << "Error: the given point must have dimension=" << getDimension() << ", here dimension=" << point.getDimension();

  Scalar cdf = 0.0;
  const UnsignedInteger size = points_.getSize();
  const UnsignedInteger dimension = getDimension();
  // Quick search for 1D case
  if (dimension == 1)
  {
    const Scalar x = point[0];
    UnsignedInteger upper = size - 1;
    Scalar xUpper = points_(upper, 0);
    if (x >= xUpper - supportEpsilon_) return 1.0;
    UnsignedInteger lower = 0;
    Scalar xLower = points_(lower, 0);
    if (x < xLower - supportEpsilon_) return 0.0;
    // Use dichotomic search of the correct index
    while (upper - lower > 1)
    {
      // The integer arithmetic insure that middle will be strictly between lower and upper as far as upper - lower > 1
      const UnsignedInteger middle = (upper + lower) / 2;
      const Scalar xMiddle = points_(middle, 0);
      if (xMiddle > x + supportEpsilon_)
      {
        upper = middle;
        xUpper = xMiddle;
      }
      else
      {
        lower = middle;
        xLower = xMiddle;
      }
    } // while
    // At this point we have upper == lower or upper == lower + 1, with lower - epsilon <= x < upper + epsilon
    // If xLower < x < xUpper, the contribution of lower must be taken into account, else it
    // must be discarded
    if (x <= xUpper - supportEpsilon_) return cumulativeProbabilities_[lower];
    return cumulativeProbabilities_[upper];
  }
  // Dimension > 1
  for (UnsignedInteger i = 0; i < size; ++i)
  {
    if (points_(i, 0) > point[0] + supportEpsilon_) break;
    UnsignedInteger j = 1;
    while ((j < dimension) && (points_(i, j) <= point[j] + supportEpsilon_)) ++j;
    if (j == dimension) cdf += probabilities_[i];
  }
  return cdf;
}

/* Get the PDF gradient of the distribution */
Point FiniteDiscreteDistribution::computePDFGradient(const Point & point) const
{
  if (point.getDimension() != getDimension()) throw InvalidArgumentException(HERE) << "Error: the given point must have dimension=" << getDimension() << ", here dimension=" << point.getDimension();

  const UnsignedInteger size = points_.getSize();
  const UnsignedInteger dimension = getDimension();
  Point pdfGradient((dimension + 1) * size, 0.0);
  for (UnsignedInteger i = 0; i < size; ++i)
  {
    if ((point - points_[i]).norm() < supportEpsilon_)
    {
      pdfGradient[i] = 1.0;
      break;
    }
  }
  return pdfGradient;
}


/* Get the CDF gradient of the distribution */
Point FiniteDiscreteDistribution::computeCDFGradient(const Point & point) const
{
  if (point.getDimension() != getDimension()) throw InvalidArgumentException(HERE) << "Error: the given point must have dimension=" << getDimension() << ", here dimension=" << point.getDimension();

  const UnsignedInteger size = points_.getSize();
  const UnsignedInteger dimension = getDimension();
  Point cdfGradient((dimension + 1) * size, 0.0);
  for (UnsignedInteger i = 0; i < size; ++i)
  {
    UnsignedInteger j = 0;
    while ((j < dimension) && (point[j] <= points_(i, j))) ++j;
    if (j == dimension) cdfGradient[i] = 1.0;
  }
  return cdfGradient;
}

/* Compute the numerical range of the distribution given the parameters values */
void FiniteDiscreteDistribution::computeRange()
{
  const UnsignedInteger size = points_.getSize();
  const UnsignedInteger dimension = getDimension();
  // Return an empty interval for the empty collection case
  if (size == 0)
  {
    setRange(Interval(Point(dimension, 1.0), Point(dimension, 0.0)));
    return;
  }
  // The number of points is finite, so are the bounds
  const Interval::BoolCollection finiteLowerBound(dimension, true);
  const Interval::BoolCollection finiteUpperBound(dimension, true);
  Point lowerBound(points_[0]);
  Point upperBound(lowerBound);
  for (UnsignedInteger i = 1; i < size; ++i)
  {
    const Point pt(points_[i]);
    for (UnsignedInteger j = 0; j < dimension; ++j)
    {
      const Scalar x = pt[j];
      if (x < lowerBound[j]) lowerBound[j] = x;
      if (x > upperBound[j]) upperBound[j] = x;
    }
  }
  setRange(Interval(lowerBound, upperBound, finiteLowerBound, finiteUpperBound));
}

/* Get the support of a discrete distribution that intersect a given interval */
Sample FiniteDiscreteDistribution::getSupport(const Interval & interval) const
{
  if (interval.getDimension() != getDimension()) throw InvalidArgumentException(HERE) << "Error: the given interval has a dimension that does not match the distribution dimension.";
  Sample result(0, getDimension());
  const UnsignedInteger size = points_.getSize();
  for (UnsignedInteger i = 0; i < size; ++i)
  {
    const Point x(points_[i]);
    if (interval.contains(x)) result.add(x);
  }
  return result;
}

/* Get the support on the whole range */
Sample FiniteDiscreteDistribution::getSupport() const
{
  return points_;
}

/* Get the discrete probability levels */
Point FiniteDiscreteDistribution::getProbabilities() const
{
  return probabilities_;
}

/* Compute the mean of the distribution */
void FiniteDiscreteDistribution::computeMean() const
{
  const UnsignedInteger size = points_.getSize();
  Point mean(getDimension());
  for (UnsignedInteger i = 0; i < size; ++i) mean += probabilities_[i] * points_[i];
  mean_ = mean;
  isAlreadyComputedMean_ = true;
}

/* Compute the covariance of the distribution */
void FiniteDiscreteDistribution::computeCovariance() const
{
  const UnsignedInteger size = points_.getSize();
  const UnsignedInteger dimension = getDimension();
  covariance_ = CovarianceMatrix(dimension);
  for (UnsignedInteger i = 0; i < dimension; ++i) covariance_(i, i) = 0.0;
  const Point mean(getMean());
  for (UnsignedInteger k = 0; k < size; ++k)
  {
    const Point xK(points_[k] - mean);
    const Scalar pK = probabilities_[k];
    for (UnsignedInteger i = 0; i < dimension; ++i)
      for (UnsignedInteger j = 0; j <= i; ++j)
        covariance_(i, j) += pK * xK[i] * xK[j];
  }
  isAlreadyComputedCovariance_ = true;
}

/* Compute the Spearman correlation of the distribution */
CorrelationMatrix FiniteDiscreteDistribution::getSpearmanCorrelation() const
{
  const UnsignedInteger size = points_.getSize();
  const UnsignedInteger dimension = getDimension();
  Sample rank(size, dimension);
  // Build the correct weighted ranks and compute its mean along the way
  Point meanRank(dimension);
  for (UnsignedInteger i = 0; i < dimension; ++i)
  {
    const Distribution marginalI(getMarginal(i));
    for (UnsignedInteger k = 0; k < size; ++k)
    {
      rank(k, i) = marginalI.computeCDF(points_(k, i));
      meanRank[i] += probabilities_[k] * rank(k, i);
    } // k
  } // i
  // Then, the covariance of the rank
  CorrelationMatrix spearman(dimension);
  for (UnsignedInteger k = 0; k < size; ++k)
  {
    const Point xK(rank[k] - meanRank);
    const Scalar pK = probabilities_[k];
    for (UnsignedInteger i = 0; i < dimension; ++i)
      for (UnsignedInteger j = 0; j <= i; ++j)
        spearman(i, j) += pK * xK[i] * xK[j];
  }  // k
  // Then, the correlation
  Point std(dimension);
  for (UnsignedInteger i = 0; i < dimension; ++i)
  {
    std[i] = std::sqrt(spearman(i, i));
    for (UnsignedInteger j = 0; j < i; ++j)
      spearman(i, j) /= std[i] * std[j];
    spearman(i, i) = 1.0;
  }
  return spearman;
}

/* Compute the Kendall concordance of the distribution */
CorrelationMatrix FiniteDiscreteDistribution::getKendallTau() const
{
  return DistributionImplementation::getKendallTau();
}

/* Parameters value and description accessor */
FiniteDiscreteDistribution::PointWithDescriptionCollection FiniteDiscreteDistribution::getParametersCollection() const
{
  const UnsignedInteger dimension = getDimension();
  PointWithDescriptionCollection parameters(dimension + 1);
  const UnsignedInteger size = points_.getSize();
  // Loop over the dimension to extract the marginal coordinates of the support
  for (UnsignedInteger i = 0; i < dimension; ++i)
  {
    PointWithDescription point(size);
    Description description(size);
    for (UnsignedInteger j = 0; j < size; ++j)
    {
      point[j] = points_(j, i);
      OSS oss;
      oss << "X^" << i << "_" << j;
      description[j] = oss;
    }
    point.setDescription(description);
    parameters[i] = point;
  }
  // Loop over the size to extract the probabilities, seen as the dependence parameters
  PointWithDescription point(size);
  Description description(size);
  for (UnsignedInteger i = 0; i < size; ++i)
  {
    point[i] = probabilities_[i];
    OSS oss;
    oss << "probabilities_" << i;
    description[i] = oss;
  }
  point.setDescription(description);
  point.setName(getDescription()[0]);
  parameters[dimension] = point;
  return parameters;
}

/* Parameters value accessor */
Point FiniteDiscreteDistribution::getParameter() const
{
  const UnsignedInteger dimension = getDimension();
  const UnsignedInteger size = points_.getSize();
  Point point((dimension + 1) * size);
  for (UnsignedInteger i = 0; i < dimension; ++ i)
  {
    for (UnsignedInteger j = 0; j < size; ++ j)
    {
      point[i * size + j] = points_(j, i);
    }
  }
  for (UnsignedInteger i = 0; i < size; ++ i)
  {
    point[dimension * size + i] = probabilities_[i];
  }
  return point;
}

/* Parameters description accessor */
Description FiniteDiscreteDistribution::getParameterDescription() const
{
  const UnsignedInteger dimension = getDimension();
  const UnsignedInteger size = points_.getSize();
  Description description((dimension + 1) * size);
  for (UnsignedInteger i = 0; i < dimension; ++ i)
  {
    for (UnsignedInteger j = 0; j < size; ++ j)
    {
      description[i * size + j] = (OSS() << "X^" << i << "_" << j);
    }
  }
  for (UnsignedInteger i = 0; i < size; ++ i)
  {
    description[dimension * size + i] = (OSS() << "probabilities_" << i);
  }
  return description;
}

void FiniteDiscreteDistribution::setParameter(const Point & parameter)
{
  const UnsignedInteger dimension = getDimension();
  const UnsignedInteger size = points_.getSize();
  if (parameter.getSize() != (dimension + 1) * size)
    throw InvalidArgumentException(HERE) << "Expected " << (dimension + 1) * size << " parameters";
  for (UnsignedInteger i = 0; i < dimension; ++ i)
  {
    for (UnsignedInteger j = 0; j < size; ++ j)
    {
      points_(j, i) = parameter[i * size + j];
    }
  }
  for (UnsignedInteger i = 0; i < size; ++ i)
  {
    probabilities_[i] = parameter[dimension * size + i];
  }
  setData(points_, probabilities_);
}

/* Get the i-th marginal distribution */
Distribution FiniteDiscreteDistribution::getMarginal(const UnsignedInteger i) const
{
  const UnsignedInteger dimension = getDimension();
  if (i >= dimension) throw InvalidArgumentException(HERE) << "The index of a marginal distribution must be in the range [0, dim-1]";
  // Special case for dimension 1
  if (dimension == 1) return clone();
  // General case
  FiniteDiscreteDistribution::Implementation marginal(new FiniteDiscreteDistribution(points_.getMarginal(i), probabilities_));
  marginal->setDescription(Description(1, getDescription()[i]));
  return marginal;
}

/* Get the distribution of the marginal distribution corresponding to indices dimensions */
Distribution FiniteDiscreteDistribution::getMarginal(const Indices & indices) const
{
  const UnsignedInteger dimension = getDimension();
  if (!indices.check(dimension)) throw InvalidArgumentException(HERE) << "The indices of a marginal distribution must be in the range [0, dim-1] and must be different";
  // Special case for dimension 1
  if (dimension == 1) return clone();
  // General case
  FiniteDiscreteDistribution::Implementation marginal(new FiniteDiscreteDistribution(points_.getMarginal(indices), probabilities_));
  marginal->setDescription(getDescription().select(indices));
  return marginal;
} // getMarginal(Indices)

/* Interface specific to FiniteDiscreteDistribution */

void FiniteDiscreteDistribution::setData(const Sample & sample,
    const Point & weights)
{
  const UnsignedInteger size = sample.getSize();
  if (size == 0) throw InvalidArgumentException(HERE) << "Error: the collection is empty";
  if (weights.getDimension() != size) throw InvalidArgumentException(HERE) << "Error: cannot build a FiniteDiscreteDistribution distribution if the weights don't have the same dimension as the sample size.";
  hasUniformWeights_ = true;
  const UnsignedInteger dimension = sample.getDimension();
  if (dimension == 0) throw InvalidArgumentException(HERE) << "Error: the points in the collection must have a dimension > 0";
  setDimension(dimension);
  // Check if all the given probabilities are >= 0
  // Check if all the points have the same dimension
  // First, sort the collection such that the sample made with the first component is in ascending order
  Sample weightedData(size, dimension + 1);
  for (UnsignedInteger i = 0; i < size; ++i)
  {
    for (UnsignedInteger j = 0; j < dimension; ++j) weightedData(i, j) = sample(i, j);
    weightedData(i, dimension) = weights[i];
  }
  // Sort the pairs
  weightedData = weightedData.sortAccordingToAComponent(0);
  // Check the probabilities and normalize them
  const Scalar firstProbability = weightedData(0, dimension);
  Scalar sum = 0.0;
  cumulativeProbabilities_ = Point(size);
  for (UnsignedInteger i = 0; i < size; ++i)
  {
    const Scalar p = weightedData(i, dimension);
    if (!(p >= 0.0)) throw InvalidArgumentException(HERE) << "FiniteDiscreteDistribution distribution must have positive probabilities";
    sum += p;
    cumulativeProbabilities_[i] = sum;
    hasUniformWeights_ = hasUniformWeights_ && (std::abs(p - firstProbability) < pdfEpsilon_);
  }
  if (sum <= 0.0) throw InvalidArgumentException(HERE) << "Error: the sum of probabilities is zero.";
  // Normalize the probabilities
  for (UnsignedInteger i = 0; i < size; ++i)
  {
    weightedData(i, dimension) /= sum;
    cumulativeProbabilities_[i] /= sum;
  }
  points_ = Sample(size, dimension);
  probabilities_ = Point(size);
  for (UnsignedInteger i = 0; i < size; ++i)
  {
    for (UnsignedInteger j = 0; j < dimension; ++j) points_(i, j) = weightedData(i, j);
    probabilities_[i] = SpecFunc::Clip01(weightedData(i, dimension));
  }
  base_ = Point(0);
  alias_ = Indices(0);
  if (!hasUniformWeights_)
    DistFunc::rDiscreteSetup(probabilities_, base_, alias_);
  // We augment slightly the last cumulative probability, which should be equal to 1.0 but we enforce a value > 1.0.
  cumulativeProbabilities_[size - 1] = 1.0 + 2.0 * supportEpsilon_;
  isAlreadyComputedMean_ = false;
  isAlreadyComputedCovariance_ = false;
  isAlreadyCreatedGeneratingFunction_ = false;
  computeRange();
}


Sample FiniteDiscreteDistribution::getX() const
{
  return points_;
}


Point FiniteDiscreteDistribution::getP() const
{
  return probabilities_;
}


/* Quantile computation for dimension=1 */
Scalar FiniteDiscreteDistribution::computeScalarQuantile(const Scalar prob,
    const Bool tail) const
{
  if (dimension_ != 1) throw InvalidDimensionException(HERE) << "Error: the method computeScalarQuantile is only defined for 1D distributions";
  if (!((prob >= 0.0) && (prob <= 1.0)))
    throw InvalidArgumentException(HERE) << "computeScalarQuantile expected prob to belong to [0,1], but is " << prob;
  UnsignedInteger index = tail ? cumulativeProbabilities_.getSize() - 1 : 0;
  const Scalar p = tail ? 0.5 - (prob - 0.5) : prob;
  if (tail)
    while (p < 1.0 && index > 0 && cumulativeProbabilities_[index] > p) --index;
  else
    while (cumulativeProbabilities_[index] < p) ++index;
  return points_(index, 0);
}

/* Merge the identical points of the support */
void FiniteDiscreteDistribution::compactSupport(const Scalar epsilon)
{
  // No compaction if epsilon is negative
  if (epsilon < 0.0) return;
  const UnsignedInteger size = points_.getSize();
  if (size == 0) return;
  const UnsignedInteger dimension = getDimension();
  Sample compactX(0, dimension);
  Point compactP(0);
  if (dimension > 1)
  {
    // Build a hash table with rounded components
    const UnsignedInteger hashSize = 511;
    Collection<Indices> indices(hashSize);
    Collection<Indices> residuals(hashSize);
    union
    {
      Scalar *s;
      Unsigned64BitsInteger *u64;
    } typepun;
    for (UnsignedInteger i = 0; i < size; ++i)
    {
      const Point x(points_[i]);
      Scalar roundedComponent = x[0];
      if (epsilon > 0.0) roundedComponent = epsilon * round(roundedComponent / epsilon);
      typepun.s = &roundedComponent;
      UnsignedInteger index = *typepun.u64;
      for (UnsignedInteger j = 1; j < dimension; ++j)
      {
        roundedComponent = x[j];
        if (epsilon > 0.0) roundedComponent = epsilon * round(roundedComponent / epsilon);
        // XOR based hash function on the binary representation of the floating point coordinates
        typepun.s = &roundedComponent;
        index ^= *typepun.u64;
      }
      const UnsignedInteger hash = index % hashSize;
      const UnsignedInteger quotient = index / hashSize;
      indices[hash].add(i);
      residuals[hash].add(quotient);
    }
    // Now, we just have to inspect the points with the same hash
    for (UnsignedInteger i = 0; i < hashSize; ++i)
    {
      const Indices bucket(indices[i]);
      const Indices keys(residuals[i]);
      const UnsignedInteger bucketSize = bucket.getSize();
      if (bucketSize == 0) continue;
      if (bucketSize == 1)
      {
        compactX.add(points_[bucket[0]]);
        compactP.add(probabilities_[bucket[0]]);
      }
      else
      {
        // New weights for the points in the bucket
        Point weights(bucketSize);
        // Here we have to detect and merge all the duplicates
        // The ith atom is removed if flagToRemove[i] > 0
        Indices flagToRemove(bucketSize, 0);
        for (UnsignedInteger j = 0; j < bucketSize; ++j)
        {
          const UnsignedInteger currentIndex = bucket[j];
          const UnsignedInteger currentKey = keys[j];
          weights[j] = probabilities_[currentIndex];
          const Point current(points_[currentIndex]);
          if (flagToRemove[j] == 0)
          {
            for (UnsignedInteger k = j + 1; k < bucketSize; ++k)
            {
              const UnsignedInteger candidateIndex = bucket[k];
              const UnsignedInteger candidateKey = keys[k];
              const Point candidate(points_[candidateIndex]);
              if ((currentKey == candidateKey) && (current - candidate).norm() <= epsilon)
              {
                flagToRemove[k] = 1;
                weights[j] += probabilities_[candidateIndex];
              }
            } // k
          } // flagToRemove
        } // j
        // We keep all the points that must not be removed
        for (UnsignedInteger j = 0; j < bucketSize; ++j)
        {
          if (flagToRemove[j] == 0)
          {
            compactX.add(points_[bucket[j]]);
            compactP.add(weights[j]);
          }
        }
      } // bucketSize > 1
    } // Loop over the hash table
    setData(compactX, compactP);
    return;
  }
  Scalar lastLocation = points_(0, 0);
  Scalar lastWeight = probabilities_[0];
  for (UnsignedInteger i = 1; i < size; ++i)
  {
    const Scalar currentLocation = points_(i, 0);
    const Scalar currentWeight = probabilities_[i];
    // The current point must be merged
    if (std::abs(currentLocation - lastLocation) <= epsilon) lastWeight += probabilities_[i];
    else
    {
      compactX.add(Point(1, lastLocation));
      compactP.add(SpecFunc::Clip01(lastWeight));
      lastLocation = currentLocation;
      lastWeight = currentWeight;
    }
  }
  compactX.add(Point(1, lastLocation));
  compactP.add(SpecFunc::Clip01(lastWeight));
  setData(compactX, compactP);
}

/* Tell if the distribution has an elliptical copula */
Bool FiniteDiscreteDistribution::hasEllipticalCopula() const
{
  return points_.getSize() == 1;
}


/* Tell if the distribution has independent copula */
Bool FiniteDiscreteDistribution::hasIndependentCopula() const
{
  return (dimension_ == 1) || (points_.getSize() == 1);
}


/* Method save() stores the object through the StorageManager */
void FiniteDiscreteDistribution::save(Advocate & adv) const
{
  DistributionImplementation::save(adv);
  adv.saveAttribute( "points_", points_ );
  adv.saveAttribute( "probabilities_", probabilities_ );
  adv.saveAttribute( "cumulativeProbabilities_", cumulativeProbabilities_ );
  adv.saveAttribute( "hasUniformWeights_", hasUniformWeights_ );
}

/* Method load() reloads the object from the StorageManager */
void FiniteDiscreteDistribution::load(Advocate & adv)
{
  DistributionImplementation::load(adv);
  adv.loadAttribute( "points_", points_ );
  adv.loadAttribute( "probabilities_", probabilities_ );
  adv.loadAttribute( "cumulativeProbabilities_", cumulativeProbabilities_ );
  adv.loadAttribute( "hasUniformWeights_", hasUniformWeights_ );
  computeRange();
}

END_NAMESPACE_OPENTURNS
