Example usage for org.apache.commons.math3.exception NumberIsTooSmallException NumberIsTooSmallException

List of usage examples for org.apache.commons.math3.exception NumberIsTooSmallException NumberIsTooSmallException

Introduction

In this page you can find the example usage for org.apache.commons.math3.exception NumberIsTooSmallException NumberIsTooSmallException.

Prototype

public NumberIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) 

Source Link

Document

Construct the exception.

Usage

From source file:gedi.util.math.stat.distributions.NormalMixtureDistribution.java

public static NormalMixtureDistribution init(final double[] data, final int numComponents)
        throws NotStrictlyPositiveException, DimensionMismatchException {

    if (numComponents == 1)
        return new NormalMixtureDistribution(new NormalDistribution[] {
                new NormalDistribution(new Mean().evaluate(data), new StandardDeviation().evaluate(data)) },
                new double[] { 1 });

    if (data.length < 2) {
        throw new NotStrictlyPositiveException(data.length);
    }/* ww w.  j a v a2  s  .c  o  m*/
    if (numComponents < 1) {
        throw new NumberIsTooSmallException(numComponents, 2, true);
    }
    if (numComponents > data.length) {
        throw new NumberIsTooLargeException(numComponents, data.length, true);
    }

    final int numRows = data.length;
    double[] sortedData = data.clone();
    Arrays.sort(sortedData);

    // components of mixture model to be created
    double[] mixing = new double[numComponents];
    NormalDistribution[] comp = new NormalDistribution[numComponents];

    // create a component based on data in each bin
    for (int k = 0; k < numComponents; k++) {
        // minimum index (inclusive) from sorted data for this bin
        final int minIndex = (k * numRows) / numComponents;

        // maximum index (exclusive) from sorted data for this bin
        final int maxIndex = Math.min(numRows, ((k + 1) * numRows) / numComponents);

        double m = new Mean().evaluate(sortedData, minIndex, maxIndex - minIndex);
        double sd = new StandardDeviation().evaluate(sortedData, minIndex, maxIndex - minIndex);
        mixing[k] = 1d / numComponents;
        comp[k] = new NormalDistribution(m, sd);
    }

    return new NormalMixtureDistribution(comp, mixing);
}

From source file:Clustering.technique.KMeansPlusPlusClusterer.java

/**
 * Runs the K-means++ clustering algorithm.
 *
 * @param points the points to cluster//w w  w.jav a2s  .  com
 * @return a list of clusters containing the points
 * @throws MathIllegalArgumentException if the data points are null or the number
 *     of clusters is larger than the number of data points
 * @throws ConvergenceException if an empty cluster is encountered and the
 * {@link #emptyStrategy} is set to {@code ERROR}
 */
public List<CentroidCluster<T>> cluster(final Collection<T> points)
        throws MathIllegalArgumentException, ConvergenceException {

    // sanity checks
    MathUtils.checkNotNull(points);

    // number of clusters has to be smaller or equal the number of data points
    if (points.size() < k) {
        throw new NumberIsTooSmallException(points.size(), k, false);
    }

    // create the initial clusters
    List<CentroidCluster<T>> clusters = chooseInitialCenters(points);

    // create an array containing the latest assignment of a point to a cluster
    // no need to initialize the array, as it will be filled with the first assignment
    int[] assignments = new int[points.size()];
    assignPointsToClusters(clusters, points, assignments);

    // iterate through updating the centers until we're done
    final int max = (maxIterations < 0) ? Integer.MAX_VALUE : maxIterations;
    for (int count = 0; count < max; count++) {
        boolean emptyCluster = false;
        List<CentroidCluster<T>> newClusters = new ArrayList<CentroidCluster<T>>();
        for (final CentroidCluster<T> cluster : clusters) {
            final Clusterable newCenter;
            if (cluster.getPoints().isEmpty()) {
                switch (emptyStrategy) {
                case LARGEST_VARIANCE:
                    newCenter = getPointFromLargestVarianceCluster(clusters);
                    break;
                case LARGEST_POINTS_NUMBER:
                    newCenter = getPointFromLargestNumberCluster(clusters);
                    break;
                case FARTHEST_POINT:
                    newCenter = getFarthestPoint(clusters);
                    break;
                default:
                    throw new ConvergenceException(LocalizedFormats.EMPTY_CLUSTER_IN_K_MEANS);
                }
                emptyCluster = true;
            } else {
                newCenter = centroidOf(cluster.getCenter(), cluster.getPoints(),
                        cluster.getCenter().getPoint().length);
            }
            newClusters.add(new CentroidCluster<T>(newCenter));
        }
        int changes = assignPointsToClusters(newClusters, points, assignments);
        clusters = newClusters;

        // if there were no more changes in the point-to-cluster assignment
        // and there are no empty clusters left, return the current clusters
        if (changes == 0 && !emptyCluster) {
            return clusters;
        }
    }
    return clusters;
}

From source file:KMeansRecommender.MyKMeansPlusPlusClusterer.java

/**
 * Runs the K-means++ clustering algorithm.
 *
 * @param points the points to cluster//from   w ww  .  ja va  2s  . c o m
 * @return a list of clusters containing the points
 * @throws MathIllegalArgumentException if the data points are null or the number
 *     of clusters is larger than the number of data points
 * @throws ConvergenceException if an empty cluster is encountered and the
 * {@link #emptyStrategy} is set to {@code ERROR}
 */
public List<CentroidCluster<T>> cluster(final Collection<T> points)
        throws MathIllegalArgumentException, ConvergenceException {

    // sanity checks
    MathUtils.checkNotNull(points);

    // number of clusters has to be smaller or equal the number of data points
    if (points.size() < k) {
        throw new NumberIsTooSmallException(points.size(), k, false);
    }

    // create the initial clusters
    List<CentroidCluster<T>> clusters = chooseInitialCenters(points);

    // create an array containing the latest assignment of a point to a cluster
    // no need to initialize the array, as it will be filled with the first assignment
    int[] assignments = new int[points.size()];
    assignPointsToClusters(clusters, points, assignments);

    // iterate through updating the centers until we're done
    int finalchange = 0;
    final int max = (maxIterations < 0) ? Integer.MAX_VALUE : maxIterations;
    for (int count = 0; count < max; count++) {
        boolean emptyCluster = false;
        List<CentroidCluster<T>> newClusters = new ArrayList<CentroidCluster<T>>();
        for (final CentroidCluster<T> cluster : clusters) {
            final Clusterable newCenter;
            if (cluster.getPoints().isEmpty()) {
                switch (emptyStrategy) {
                case LARGEST_VARIANCE:
                    newCenter = getPointFromLargestVarianceCluster(clusters);
                    break;
                case LARGEST_POINTS_NUMBER:
                    newCenter = getPointFromLargestNumberCluster(clusters);
                    break;
                case FARTHEST_POINT:
                    newCenter = getFarthestPoint(clusters);
                    break;
                default:
                    throw new ConvergenceException(LocalizedFormats.EMPTY_CLUSTER_IN_K_MEANS);
                }
                emptyCluster = true;
            } else {
                newCenter = centroidOf(cluster.getPoints(), cluster.getCenter().getPoint().length);
            }
            newClusters.add(new CentroidCluster<T>(newCenter));
        }
        int changes = assignPointsToClusters(newClusters, points, assignments);
        clusters = newClusters;
        finalchange = changes; //for test
        // if there were no more changes in the point-to-cluster assignment
        // and there are no empty clusters left, return the current clusters
        if (changes == 0 && !emptyCluster) {
            //System.out.println("iteration time: " + count + ", changes : 0");  //for test
            return clusters;
        }

    }
    //System.out.println("iteration time: " + max + ", changes : " + finalchange);  //for test  
    return clusters;
}

From source file:nars.concept.util.BeliefClusterer.java

/**
 * Runs the K-means++ clustering algorithm.
 *
 * @param points the points to cluster/*from  ww w.  ja va2  s. co  m*/
 * @return a list of clusters containing the points
 * @throws MathIllegalArgumentException if the data points are null or the number
 *     of clusters is larger than the number of data points
 * @throws ConvergenceException if an empty cluster is encountered and the
 * {@link #emptyStrategy} is set to {@code ERROR}
 */
@NotNull
public List<Cluster> cluster(@NotNull final Collection<T> points)
        throws MathIllegalArgumentException, ConvergenceException {

    // sanity checks
    MathUtils.checkNotNull(points);

    // number of clusters has to be smaller or equal the number of data points
    if (points.size() < k) {
        throw new NumberIsTooSmallException(points.size(), k, false);
    }

    // create the initial clusters
    List<Cluster> clusters = chooseInitialCenters(points);

    // create an array containing the latest assignment of a point to a cluster
    // no need to initialize the array, as it will be filled with the first assignment
    int[] assignments = new int[points.size()];
    assignPointsToClusters(clusters, points, assignments);

    // iterate through updating the centers until we're done
    final int max = (maxIterations < 0) ? Integer.MAX_VALUE : maxIterations;
    for (int count = 0; count < max; count++) {
        boolean emptyCluster = false;
        List<Cluster> newClusters = new ArrayList<>();
        for (final Cluster cluster : clusters) {
            final ArrayRealVector newCenter;
            if (cluster.getPoints().isEmpty()) {
                switch (emptyStrategy) {
                case LARGEST_VARIANCE:
                    newCenter = getPointFromLargestVarianceCluster(clusters);
                    break;
                case LARGEST_POINTS_NUMBER:
                    newCenter = getPointFromLargestNumberCluster(clusters);
                    break;
                case FARTHEST_POINT:
                    newCenter = getFarthestPoint(clusters);
                    break;
                default:
                    throw new ConvergenceException(LocalizedFormats.EMPTY_CLUSTER_IN_K_MEANS);
                }
                emptyCluster = true;
            } else {
                newCenter = centroidOf(cluster.getPoints(), getDimensions());
            }
            newClusters.add(new Cluster(newCenter));
        }
        int changes = assignPointsToClusters(newClusters, points, assignments);
        clusters = newClusters;

        // if there were no more changes in the point-to-cluster assignment
        // and there are no empty clusters left, return the current clusters
        if (changes == 0 && !emptyCluster) {
            return clusters;
        }
    }
    return clusters;
}

From source file:com.wwidesigner.math.DIRECTOptimizer.java

/**
 * Performs validity checks, and creates initial rectangle.
 *//*from  w ww .j a  v a2 s .  co m*/
protected void setup() {
    double[] init = getStartPoint();
    final int dimension = init.length;

    // Check problem dimension.
    if (dimension < 1) {
        throw new NumberIsTooSmallException(dimension, 1, true);
    }

    // Initialize bound differences.
    boundDifference = new double[dimension];
    double[] centre = new double[dimension];
    double[] width = new double[dimension];

    for (int i = 0; i < dimension; i++) {
        boundDifference[i] = getUpperBound()[i] - getLowerBound()[i];
        centre[i] = 0.5 * (getUpperBound()[i] + getLowerBound()[i]);
        if (boundDifference[i] > 0) {
            width[i] = 1.0; // Full scale
        } else {
            width[i] = 0.0; // No variation
        }
    }

    nextSerial = 0;
    rtree = new TreeMap<RectangleKey, RectangleValue>();
    fv = new double[2 * dimension];
    isort = new Integer[dimension];
    int hullSize = (int) FastMath.sqrt(getMaxEvaluations());
    if (hullSize < 150) {
        hullSize = 150;
    }
    hull = new Rectangle[hullSize];

    fMax = 1.0;
    RectangleValue firstRect = new RectangleValue(centre, width);
    RectangleKey firstKey = new RectangleKey(rectangleDiameter(width), computeObjectiveValue(centre));
    // We assume that the first point is feasible, and does not throw
    // an exception, otherwise the function value will be fMax.
    fMax = firstKey.getfValue();

    rtree.put(firstKey, firstRect);
    divideRectangle(firstKey, firstRect);
}

From source file:com.itemanalysis.psychometrics.optimization.BOBYQAOptimizer.java

/**
 * Performs validity checks.//from w w  w. j  a v  a  2  s.  c  o  m
 *
 * @param lowerBound Lower bounds (constraints) of the objective variables.
 * @param upperBound Upperer bounds (constraints) of the objective variables.
 */
private void setup(double[] lowerBound, double[] upperBound) {
    printMethod(); // XXX

    double[] init = getStartPoint();
    final int dimension = init.length;

    // Check problem dimension.
    if (dimension < MINIMUM_PROBLEM_DIMENSION) {
        throw new NumberIsTooSmallException(dimension, MINIMUM_PROBLEM_DIMENSION, true);
    }
    // Check number of interpolation points.
    final int[] nPointsInterval = { dimension + 2, (dimension + 2) * (dimension + 1) / 2 };
    if (numberOfInterpolationPoints < nPointsInterval[0] || numberOfInterpolationPoints > nPointsInterval[1]) {
        throw new OutOfRangeException(LocalizedFormats.NUMBER_OF_INTERPOLATION_POINTS,
                numberOfInterpolationPoints, nPointsInterval[0], nPointsInterval[1]);
    }

    // Initialize bound differences.
    boundDifference = new double[dimension];

    double requiredMinDiff = 2 * initialTrustRegionRadius;
    double minDiff = Double.POSITIVE_INFINITY;
    for (int i = 0; i < dimension; i++) {
        boundDifference[i] = upperBound[i] - lowerBound[i];
        minDiff = Math.min(minDiff, boundDifference[i]);
    }
    if (minDiff < requiredMinDiff) {
        initialTrustRegionRadius = minDiff / 3.0;
    }

    // Initialize the data structures used by the "bobyqa" method.
    bMatrix = new Array2DRowRealMatrix(dimension + numberOfInterpolationPoints, dimension);
    zMatrix = new Array2DRowRealMatrix(numberOfInterpolationPoints,
            numberOfInterpolationPoints - dimension - 1);
    interpolationPoints = new Array2DRowRealMatrix(numberOfInterpolationPoints, dimension);
    originShift = new ArrayRealVector(dimension);
    fAtInterpolationPoints = new ArrayRealVector(numberOfInterpolationPoints);
    trustRegionCenterOffset = new ArrayRealVector(dimension);
    gradientAtTrustRegionCenter = new ArrayRealVector(dimension);
    lowerDifference = new ArrayRealVector(dimension);
    upperDifference = new ArrayRealVector(dimension);
    modelSecondDerivativesParameters = new ArrayRealVector(numberOfInterpolationPoints);
    newPoint = new ArrayRealVector(dimension);
    alternativeNewPoint = new ArrayRealVector(dimension);
    trialStepPoint = new ArrayRealVector(dimension);
    lagrangeValuesAtNewPoint = new ArrayRealVector(dimension + numberOfInterpolationPoints);
    modelSecondDerivativesValues = new ArrayRealVector(dimension * (dimension + 1) / 2);
}

From source file:org.apache.kylin.cube.cuboid.algorithm.generic.lib.FixedGenerationCount.java

/**
 * Create a new FixedGenerationCount instance.
 *
 * @param maxGenerations number of generations to evolve
 * @throws NumberIsTooSmallException if the number of generations is &lt; 1
 */// w  ww  .  ja v a  2  s.  c o  m
public FixedGenerationCount(final int maxGenerations) throws NumberIsTooSmallException {
    if (maxGenerations <= 0) {
        throw new NumberIsTooSmallException(maxGenerations, 1, true);
    }
    this.maxGenerations = maxGenerations;
}

From source file:org.apache.kylin.cube.cuboid.algorithm.generic.lib.ListPopulation.java

/**
 * Sets the maximal population size.//from   ww  w .j a v  a  2 s.  c o  m
 * @param populationLimit maximal population size.
 * @throws NotPositiveException if the population limit is not a positive number (&lt; 1)
 * @throws NumberIsTooSmallException if the new population size is smaller than the current number
 *   of chromosomes in the population
 */
public void setPopulationLimit(final int populationLimit)
        throws NotPositiveException, NumberIsTooSmallException {
    if (populationLimit <= 0) {
        throw new NotPositiveException(LocalizedFormats.POPULATION_LIMIT_NOT_POSITIVE, populationLimit);
    }
    if (populationLimit < chromosomes.size()) {
        throw new NumberIsTooSmallException(populationLimit, chromosomes.size(), true);
    }
    this.populationLimit = populationLimit;
}

From source file:org.esa.s2tbx.s2msi.idepix.operators.cloudshadow.MyClustering.java

/**
 * Runs the K-means++ clustering algorithm.
 *
 * @param points the points to cluster/*from  www  . j  ava  2  s  .  c o m*/
 * @return a list of clusters containing the points
 * @throws MathIllegalArgumentException if the data points are null or the number
 *                                      of clusters is larger than the number of data points
 * @throws ConvergenceException         if an empty cluster is encountered and the
 *                                      {@link #emptyStrategy} is set to {@code ERROR}
 */
@Override
public List<CentroidCluster<T>> cluster(final Collection<T> points)
        throws MathIllegalArgumentException, ConvergenceException {

    // sanity checks
    MathUtils.checkNotNull(points);

    // number of clusters has to be smaller or equal the number of data points
    if (points.size() < k) {
        throw new NumberIsTooSmallException(points.size(), k, false);
    }
    // todo adaption for more bands is required
    double darkestPoint = Double.MAX_VALUE;
    int darkestPointIndex = -1;
    for (int index = 0; index < points.size(); index++) {
        DoublePoint p = ((ArrayList<DoublePoint>) points).get(index);
        double value = p.getPoint()[0];
        if (value < darkestPoint) {
            darkestPoint = value;
            darkestPointIndex = index;
        }
    }
    /*
    int array [][] = {{11, 0},{34, 1},{8, 2}};
            
     java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
     public int compare(double[] a, double[] b) {
         return b[0] - a[0];
     }
    });
            
    array [][] = {{8, 2}, {11, 0}, {34, 1}};
    */

    // create the initial clusters
    List<CentroidCluster<T>> clusters = chooseInitialCenters(points, darkestPointIndex);

    // create an array containing the latest assignment of a point to a cluster
    // no need to initialize the array, as it will be filled with the first assignment
    int[] assignments = new int[points.size()];
    assignPointsToClusters(clusters, points, assignments);

    // iterate through updating the centers until we're done
    final int max = (maxIterations < 0) ? Integer.MAX_VALUE : maxIterations;
    for (int count = 0; count < max; count++) {
        boolean emptyCluster = false;
        List<CentroidCluster<T>> newClusters = new ArrayList<>();
        for (final CentroidCluster<T> cluster : clusters) {
            final Clusterable newCenter;
            if (cluster.getPoints().isEmpty()) {
                switch (emptyStrategy) {
                case LARGEST_VARIANCE:
                    newCenter = getPointFromLargestVarianceCluster(clusters);
                    break;
                case LARGEST_POINTS_NUMBER:
                    newCenter = getPointFromLargestNumberCluster(clusters);
                    break;
                case FARTHEST_POINT:
                    newCenter = getFarthestPoint(clusters);
                    break;
                default:
                    throw new ConvergenceException(LocalizedFormats.EMPTY_CLUSTER_IN_K_MEANS);
                }
                emptyCluster = true;
            } else {
                newCenter = centroidOf(cluster.getPoints(), cluster.getCenter().getPoint().length);
            }
            newClusters.add(new CentroidCluster<>(newCenter));
        }
        int changes = assignPointsToClusters(newClusters, points, assignments);
        clusters = newClusters;

        // if there were no more changes in the point-to-cluster assignment
        // and there are no empty clusters left, return the current clusters
        if (changes == 0 && !emptyCluster) {
            return clusters;
        }
    }
    return clusters;
}

From source file:org.gitools.analysis.clustering.kmeans.KMeansPlusPlusClusterer.java

public List<CentroidCluster<T>> cluster(final Collection<T> points, IProgressMonitor monitor)
        throws MathIllegalArgumentException, ConvergenceException {

    // number of clusters has to be smaller or equal the number of data points
    if (points.size() < k) {
        throw new NumberIsTooSmallException(points.size(), k, false);
    }/*from  www.  j a  va  2s. com*/

    // create the initial clusters
    List<CentroidCluster<T>> clusters = chooseInitialCenters(points);

    // create an array containing the latest assignment of a point to a cluster
    // no need to initialize the array, as it will be filled with the first assignment
    int[] assignments = new int[points.size()];
    assignPointsToClusters(clusters, points, assignments);

    final int max = (maxIterations < 0) ? Integer.MAX_VALUE : maxIterations;
    for (int count = 0; count < max; count++) {

        // iterate through updating the centers until we're done
        monitor.begin("Iteration " + (count + 1), clusters.size());

        boolean emptyCluster = false;
        List<CentroidCluster<T>> newClusters = new ArrayList<CentroidCluster<T>>();
        for (final CentroidCluster<T> cluster : clusters) {

            monitor.worked(1);
            if (monitor.isCancelled()) {
                throw new CancellationException();
            }

            final Clusterable newCenter;
            if (cluster.getPoints().isEmpty()) {
                switch (emptyStrategy) {
                case LARGEST_VARIANCE:
                    newCenter = getPointFromLargestVarianceCluster(clusters);
                    break;
                case LARGEST_POINTS_NUMBER:
                    newCenter = getPointFromLargestNumberCluster(clusters);
                    break;
                case FARTHEST_POINT:
                    newCenter = getFarthestPoint(clusters);
                    break;
                default:
                    throw new ConvergenceException(LocalizedFormats.EMPTY_CLUSTER_IN_K_MEANS);
                }
                emptyCluster = true;
            } else {
                newCenter = centroidOf(cluster.getPoints(), cluster.getCenter().size());
            }
            newClusters.add(new CentroidCluster<T>(newCenter));
        }
        int changes = assignPointsToClusters(newClusters, points, assignments);
        clusters = newClusters;

        // if there were no more changes in the point-to-cluster assignment
        // and there are no empty clusters left, return the current clusters
        if (changes == 0 && !emptyCluster) {
            return clusters;
        }
    }
    return clusters;
}