List of usage examples for org.apache.commons.math3.util MathUtils checkNotNull
public static void checkNotNull(Object o) throws NullArgumentException
From source file:DBScan.java
public List<List<Character>> cluster(final Collection<Character> points) throws NullArgumentException { // sanity checks MathUtils.checkNotNull(points); final List<List<Character>> clusters = new ArrayList<>(); // final Map<Character, PointStatus> visited = new HashMap<>(); for (final Character point : points) { if (point.visited) continue; final List<Character> neighbors = getNeighbors(point, points); if (neighbors.size() >= minPts) { final List<Character> cluster = new ArrayList<>(); clusters.add(expandCluster(cluster, point, neighbors, points)); } else {// w w w.j a v a 2 s . c o m point.status = PointStatus.NOISE; point.visited = true; noiseSet.add(point); } } return clusters; }
From source file:lirmm.inria.fr.math.BigSparseRealMatrix.java
/** * Create a new {@code BigSparseRealMatrix} using the input array as the * underlying data array./*from w w w .j a v a 2 s .c o m*/ * * @param data Data for the new matrix. * @throws DimensionMismatchException if {@code d} is not rectangular. * @throws NoDataException if {@code d} i or column dimension is zero. */ public BigSparseRealMatrix(final double[][] data) throws DimensionMismatchException, NoDataException { MathUtils.checkNotNull(data); this.entries = new OpenLongToDoubleHashMap(0.0); rows = data.length; if (rows == 0) { throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW); } columns = data[0].length; if (columns == 0) { throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); } for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { setEntry(i, j, data[i][j]); } } }
From source file:com.yahoo.egads.utilities.DBSCANClusterer.java
/** * Performs DBSCAN cluster analysis./*from w w w .ja va2 s.c o m*/ * * @param points the points to cluster * @return the list of clusters * @throws NullArgumentException if the data points are null */ public List<Cluster<T>> cluster(final Collection<T> points) throws NullArgumentException { // sanity checks MathUtils.checkNotNull(points); final List<Cluster<T>> clusters = new ArrayList<Cluster<T>>(); final List<Cluster<T>> anomalousClusters = new ArrayList<Cluster<T>>(); final Cluster<T> anomalyCluster = new Cluster<T>(); final Map<Clusterable, PointStatus> visited = new HashMap<Clusterable, PointStatus>(); for (final T point : points) { if (visited.get(point) != null) { continue; } final List<T> neighbors = getNeighbors(point, points); if (neighbors.size() >= minPts) { // DBSCAN does not care about center points final Cluster<T> cluster = new Cluster<T>(); clusters.add(expandCluster(cluster, point, neighbors, points, visited)); } else { visited.put(point, PointStatus.NOISE); anomalyCluster.addPoint(point); } } anomalousClusters.add(anomalyCluster); return anomalousClusters; }
From source file:com.bolatu.gezkoncsvlogger.GyroOrientation.RotationKalmanFilter.java
/** * Creates a new Kalman filter with the given process and measurement * models.// w w w. j a va 2 s . c o m * * @param process * the model defining the underlying process dynamics * @param measurement * the model defining the given measurement characteristics * @throws NullArgumentException * if any of the given inputs is null (except for the control * matrix) * @throws NonSquareMatrixException * if the transition matrix is non square * @throws DimensionMismatchException * if the column dimension of the transition matrix does not * match the dimension of the initial state estimation vector * @throws MatrixDimensionMismatchException * if the matrix dimensions do not fit together */ public RotationKalmanFilter(final ProcessModel process, final MeasurementModel measurement) throws NullArgumentException, NonSquareMatrixException, DimensionMismatchException, MatrixDimensionMismatchException { MathUtils.checkNotNull(process); MathUtils.checkNotNull(measurement); this.processModel = process; this.measurementModel = measurement; transitionMatrix = processModel.getStateTransitionMatrix(); MathUtils.checkNotNull(transitionMatrix); transitionMatrixT = transitionMatrix.transpose(); // create an empty matrix if no control matrix was given if (processModel.getControlMatrix() == null) { controlMatrix = new Array2DRowRealMatrix(); } else { controlMatrix = processModel.getControlMatrix(); } measurementMatrix = measurementModel.getMeasurementMatrix(); MathUtils.checkNotNull(measurementMatrix); measurementMatrixT = measurementMatrix.transpose(); // check that the process and measurement noise matrices are not null // they will be directly accessed from the model as they may change // over time RealMatrix processNoise = processModel.getProcessNoise(); MathUtils.checkNotNull(processNoise); RealMatrix measNoise = measurementModel.getMeasurementNoise(); MathUtils.checkNotNull(measNoise); // set the initial state estimate to a zero vector if it is not // available from the process model if (processModel.getInitialStateEstimate() == null) { stateEstimation = new ArrayRealVector(transitionMatrix.getColumnDimension()); } else { stateEstimation = processModel.getInitialStateEstimate(); } if (transitionMatrix.getColumnDimension() != stateEstimation.getDimension()) { throw new DimensionMismatchException(transitionMatrix.getColumnDimension(), stateEstimation.getDimension()); } // initialize the error covariance to the process noise if it is not // available from the process model if (processModel.getInitialErrorCovariance() == null) { errorCovariance = processNoise.copy(); } else { errorCovariance = processModel.getInitialErrorCovariance(); } // sanity checks, the control matrix B may be null // A must be a square matrix if (!transitionMatrix.isSquare()) { throw new NonSquareMatrixException(transitionMatrix.getRowDimension(), transitionMatrix.getColumnDimension()); } // row dimension of B must be equal to A // if no control matrix is available, the row and column dimension will // be 0 if (controlMatrix != null && controlMatrix.getRowDimension() > 0 && controlMatrix.getColumnDimension() > 0 && controlMatrix.getRowDimension() != transitionMatrix.getRowDimension()) { throw new MatrixDimensionMismatchException(controlMatrix.getRowDimension(), controlMatrix.getColumnDimension(), transitionMatrix.getRowDimension(), controlMatrix.getColumnDimension()); } // Q must be equal to A MatrixUtils.checkAdditionCompatible(transitionMatrix, processNoise); // column dimension of H must be equal to row dimension of A if (measurementMatrix.getColumnDimension() != transitionMatrix.getRowDimension()) { throw new MatrixDimensionMismatchException(measurementMatrix.getRowDimension(), measurementMatrix.getColumnDimension(), measurementMatrix.getRowDimension(), transitionMatrix.getRowDimension()); } // row dimension of R must be equal to row dimension of H if (measNoise.getRowDimension() != measurementMatrix.getRowDimension()) { throw new MatrixDimensionMismatchException(measNoise.getRowDimension(), measNoise.getColumnDimension(), measurementMatrix.getRowDimension(), measNoise.getColumnDimension()); } }
From source file:logic.ApachePolyNewtonForm.java
/** * Verifies that the input arrays are valid. * <p>// ww w. jav a 2s . co m * The centers must be distinct for interpolation purposes, but not * for general use. Thus it is not verified here.</p> * * @param a the coefficients in Newton form formula * @param c the centers * @throws NullArgumentException if any argument is {@code null}. * @throws NoDataException if any array has zero length. * @throws DimensionMismatchException if the size difference between * {@code a} and {@code c} is not equal to 1. * @see org.apache.commons.math3.analysis.interpolation.DividedDifferenceInterpolator#computeDividedDifference(double[], * double[]) */ protected static void verifyInputArray(double a[], double c[]) throws NullArgumentException, NoDataException, DimensionMismatchException { MathUtils.checkNotNull(a); MathUtils.checkNotNull(c); if (a.length == 0 || c.length == 0) { throw new NoDataException(LocalizedFormats.EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY); } if (a.length != c.length + 1) { throw new DimensionMismatchException(LocalizedFormats.ARRAY_SIZES_SHOULD_HAVE_DIFFERENCE_1, a.length, c.length); } }
From source file:Clustering.technique.KMeansPlusPlusClusterer.java
/** * Runs the K-means++ clustering algorithm. * * @param points the points to cluster//from w w w . j a v a 2 s .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 w w . 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//ww w . j a va 2s . c om * @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.bolatu.gezkoncsvlogger.GyroOrientation.RotationKalmanFilter.java
/** * Correct the current state estimate with an actual measurement. * * @param z/*from w ww .j a va 2s . co m*/ * the measurement vector * @throws NullArgumentException * if the measurement vector is {@code null} * @throws DimensionMismatchException * if the dimension of the measurement vector does not fit * @throws SingularMatrixException * if the covariance matrix could not be inverted */ public void correct(final RealVector z) throws NullArgumentException, DimensionMismatchException, SingularMatrixException { // sanity checks MathUtils.checkNotNull(z); if (z.getDimension() != measurementMatrix.getRowDimension()) { throw new DimensionMismatchException(z.getDimension(), measurementMatrix.getRowDimension()); } // S = H * P(k) * H' + R RealMatrix s = measurementMatrix.multiply(errorCovariance).multiply(measurementMatrixT) .add(measurementModel.getMeasurementNoise()); // Inn = z(k) - H * xHat(k)- RealVector innovation = z.subtract(measurementMatrix.operate(stateEstimation)); // calculate gain matrix // K(k) = P(k)- * H' * (H * P(k)- * H' + R)^-1 // K(k) = P(k)- * H' * S^-1 // instead of calculating the inverse of S we can rearrange the formula, // and then solve the linear equation A x X = B with A = S', X = K' and // B = (H * P)' // K(k) * S = P(k)- * H' // S' * K(k)' = H * P(k)-' RealMatrix kalmanGain = new CholeskyDecomposition(s).getSolver() .solve(measurementMatrix.multiply(errorCovariance.transpose())).transpose(); // update estimate with measurement z(k) // xHat(k) = xHat(k)- + K * Inn stateEstimation = stateEstimation.add(kalmanGain.operate(innovation)); // update covariance of prediction error // P(k) = (I - K * H) * P(k)- RealMatrix identity = MatrixUtils.createRealIdentityMatrix(kalmanGain.getRowDimension()); errorCovariance = identity.subtract(kalmanGain.multiply(measurementMatrix)).multiply(errorCovariance); }
From source file:org.esa.s2tbx.s2msi.idepix.operators.cloudshadow.MyClustering.java
/** * Runs the K-means++ clustering algorithm. * * @param points the points to cluster/* w w w. j av a2 s. c om*/ * @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; }