Added missing throws declarations. JIRA: MATH-854.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/trunk@1392342 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Phil Steitz 2012-10-01 14:08:52 +00:00
parent bb60e51654
commit e055dcd21a
14 changed files with 199 additions and 105 deletions

View File

@ -318,13 +318,13 @@ public final class StatUtils {
* <p>
* Returns 0 for a single-value (i.e. length = 1) sample.</p>
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null.</p>
* Throws <code>MathIllegalArgumentException</code> if the array is null.</p>
*
* @param values the input array
* @return the variance of the values or Double.NaN if the array is empty
* @throws IllegalArgumentException if the array is null
* @throws MathIllegalArgumentException if the array is null
*/
public static double variance(final double[] values) {
public static double variance(final double[] values) throws MathIllegalArgumentException {
return VARIANCE.evaluate(values);
}
@ -342,18 +342,18 @@ public final class StatUtils {
* <p>
* Returns 0 for a single-value (i.e. length = 1) sample.</p>
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null or the
* Throws <code>MathIllegalArgumentException</code> if the array is null or the
* array index parameters are not valid.</p>
*
* @param values the input array
* @param begin index of the first array element to include
* @param length the number of elements to include
* @return the variance of the values or Double.NaN if length = 0
* @throws IllegalArgumentException if the array is null or the array index
* @throws MathIllegalArgumentException if the array is null or the array index
* parameters are not valid
*/
public static double variance(final double[] values, final int begin,
final int length) {
final int length) throws MathIllegalArgumentException {
return VARIANCE.evaluate(values, begin, length);
}
@ -376,7 +376,7 @@ public final class StatUtils {
* <p>
* Returns 0 for a single-value (i.e. length = 1) sample.</p>
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null or the
* Throws <code>MathIllegalArgumentException</code> if the array is null or the
* array index parameters are not valid.</p>
*
* @param values the input array
@ -384,11 +384,11 @@ public final class StatUtils {
* @param begin index of the first array element to include
* @param length the number of elements to include
* @return the variance of the values or Double.NaN if length = 0
* @throws IllegalArgumentException if the array is null or the array index
* @throws MathIllegalArgumentException if the array is null or the array index
* parameters are not valid
*/
public static double variance(final double[] values, final double mean,
final int begin, final int length) {
final int begin, final int length) throws MathIllegalArgumentException {
return VARIANCE.evaluate(values, mean, begin, length);
}
@ -411,14 +411,15 @@ public final class StatUtils {
* <p>
* Returns 0 for a single-value (i.e. length = 1) sample.</p>
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null.</p>
* Throws <code>MathIllegalArgumentException</code> if the array is null.</p>
*
* @param values the input array
* @param mean the precomputed mean value
* @return the variance of the values or Double.NaN if the array is empty
* @throws IllegalArgumentException if the array is null
* @throws MathIllegalArgumentException if the array is null
*/
public static double variance(final double[] values, final double mean) {
public static double variance(final double[] values, final double mean)
throws MathIllegalArgumentException {
return VARIANCE.evaluate(values, mean);
}
@ -432,13 +433,14 @@ public final class StatUtils {
* <p>
* Returns 0 for a single-value (i.e. length = 1) sample.</p>
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null.</p>
* Throws <code>MathIllegalArgumentException</code> if the array is null.</p>
*
* @param values the input array
* @return the population variance of the values or Double.NaN if the array is empty
* @throws IllegalArgumentException if the array is null
* @throws MathIllegalArgumentException if the array is null
*/
public static double populationVariance(final double[] values) {
public static double populationVariance(final double[] values)
throws MathIllegalArgumentException {
return new Variance(false).evaluate(values);
}
@ -453,18 +455,18 @@ public final class StatUtils {
* <p>
* Returns 0 for a single-value (i.e. length = 1) sample.</p>
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null or the
* Throws <code>MathIllegalArgumentException</code> if the array is null or the
* array index parameters are not valid.</p>
*
* @param values the input array
* @param begin index of the first array element to include
* @param length the number of elements to include
* @return the population variance of the values or Double.NaN if length = 0
* @throws IllegalArgumentException if the array is null or the array index
* @throws MathIllegalArgumentException if the array is null or the array index
* parameters are not valid
*/
public static double populationVariance(final double[] values, final int begin,
final int length) {
final int length) throws MathIllegalArgumentException {
return new Variance(false).evaluate(values, begin, length);
}
@ -484,7 +486,7 @@ public final class StatUtils {
* <p>
* Returns 0 for a single-value (i.e. length = 1) sample.</p>
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null or the
* Throws <code>MathIllegalArgumentException</code> if the array is null or the
* array index parameters are not valid.</p>
*
* @param values the input array
@ -492,11 +494,11 @@ public final class StatUtils {
* @param begin index of the first array element to include
* @param length the number of elements to include
* @return the population variance of the values or Double.NaN if length = 0
* @throws IllegalArgumentException if the array is null or the array index
* @throws MathIllegalArgumentException if the array is null or the array index
* parameters are not valid
*/
public static double populationVariance(final double[] values, final double mean,
final int begin, final int length) {
final int begin, final int length) throws MathIllegalArgumentException {
return new Variance(false).evaluate(values, mean, begin, length);
}
@ -516,14 +518,15 @@ public final class StatUtils {
* <p>
* Returns 0 for a single-value (i.e. length = 1) sample.</p>
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null.</p>
* Throws <code>MathIllegalArgumentException</code> if the array is null.</p>
*
* @param values the input array
* @param mean the precomputed mean value
* @return the population variance of the values or Double.NaN if the array is empty
* @throws IllegalArgumentException if the array is null
* @throws MathIllegalArgumentException if the array is null
*/
public static double populationVariance(final double[] values, final double mean) {
public static double populationVariance(final double[] values, final double mean)
throws MathIllegalArgumentException {
return new Variance(false).evaluate(values, mean);
}
@ -531,7 +534,7 @@ public final class StatUtils {
* Returns the maximum of the entries in the input array, or
* <code>Double.NaN</code> if the array is empty.
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null.</p>
* Throws <code>MathIllegalArgumentException</code> if the array is null.</p>
* <p>
* <ul>
* <li>The result is <code>NaN</code> iff all values are <code>NaN</code>
@ -542,9 +545,9 @@ public final class StatUtils {
*
* @param values the input array
* @return the maximum of the values or Double.NaN if the array is empty
* @throws IllegalArgumentException if the array is null
* @throws MathIllegalArgumentException if the array is null
*/
public static double max(final double[] values) {
public static double max(final double[] values) throws MathIllegalArgumentException {
return MAX.evaluate(values);
}
@ -553,7 +556,7 @@ public final class StatUtils {
* the input array, or <code>Double.NaN</code> if the designated subarray
* is empty.
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null or
* Throws <code>MathIllegalArgumentException</code> if the array is null or
* the array index parameters are not valid.</p>
* <p>
* <ul>
@ -567,11 +570,11 @@ public final class StatUtils {
* @param begin index of the first array element to include
* @param length the number of elements to include
* @return the maximum of the values or Double.NaN if length = 0
* @throws IllegalArgumentException if the array is null or the array index
* @throws MathIllegalArgumentException if the array is null or the array index
* parameters are not valid
*/
public static double max(final double[] values, final int begin,
final int length) {
final int length) throws MathIllegalArgumentException {
return MAX.evaluate(values, begin, length);
}
@ -579,7 +582,7 @@ public final class StatUtils {
* Returns the minimum of the entries in the input array, or
* <code>Double.NaN</code> if the array is empty.
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null.</p>
* Throws <code>MathIllegalArgumentException</code> if the array is null.</p>
* <p>
* <ul>
* <li>The result is <code>NaN</code> iff all values are <code>NaN</code>
@ -590,9 +593,9 @@ public final class StatUtils {
*
* @param values the input array
* @return the minimum of the values or Double.NaN if the array is empty
* @throws IllegalArgumentException if the array is null
* @throws MathIllegalArgumentException if the array is null
*/
public static double min(final double[] values) {
public static double min(final double[] values) throws MathIllegalArgumentException {
return MIN.evaluate(values);
}
@ -601,7 +604,7 @@ public final class StatUtils {
* the input array, or <code>Double.NaN</code> if the designated subarray
* is empty.
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null or
* Throws <code>MathIllegalArgumentException</code> if the array is null or
* the array index parameters are not valid.</p>
* <p>
* <ul>
@ -615,11 +618,11 @@ public final class StatUtils {
* @param begin index of the first array element to include
* @param length the number of elements to include
* @return the minimum of the values or Double.NaN if length = 0
* @throws IllegalArgumentException if the array is null or the array index
* @throws MathIllegalArgumentException if the array is null or the array index
* parameters are not valid
*/
public static double min(final double[] values, final int begin,
final int length) {
final int length) throws MathIllegalArgumentException {
return MIN.evaluate(values, begin, length);
}
@ -643,10 +646,11 @@ public final class StatUtils {
* @param values input array of values
* @param p the percentile value to compute
* @return the percentile value or Double.NaN if the array is empty
* @throws IllegalArgumentException if <code>values</code> is null
* @throws MathIllegalArgumentException if <code>values</code> is null
* or p is invalid
*/
public static double percentile(final double[] values, final double p) {
public static double percentile(final double[] values, final double p)
throws MathIllegalArgumentException {
return PERCENTILE.evaluate(values,p);
}
@ -660,25 +664,25 @@ public final class StatUtils {
* <li>Returns <code>Double.NaN</code> if <code>length = 0</code></li>
* <li>Returns (for any value of <code>p</code>) <code>values[begin]</code>
* if <code>length = 1 </code></li>
* <li>Throws <code>IllegalArgumentException</code> if <code>values</code>
* <li>Throws <code>MathIllegalArgumentException</code> if <code>values</code>
* is null , <code>begin</code> or <code>length</code> is invalid, or
* <code>p</code> is not a valid quantile value (p must be greater than 0
* and less than or equal to 100)</li>
* </ul></p>
* <p>
* See {@link org.apache.commons.math3.stat.descriptive.rank.Percentile} for
* a description of the percentile estimation algorithm used.</p>
* See {@link org.apache.commons.math3.stat.descriptive.rank.Percentile} for
* a description of the percentile estimation algorithm used.</p>
*
* @param values array of input values
* @param p the percentile to compute
* @param begin the first (0-based) element to include in the computation
* @param length the number of array elements to include
* @return the percentile value
* @throws IllegalArgumentException if the parameters are not valid or the
* @throws MathIllegalArgumentException if the parameters are not valid or the
* input array is null
*/
public static double percentile(final double[] values, final int begin,
final int length, final double p) {
final int length, final double p) throws MathIllegalArgumentException {
return PERCENTILE.evaluate(values, begin, length, p);
}
@ -693,7 +697,8 @@ public final class StatUtils {
* (positive) length.
* @throws NoDataException if the sample arrays are empty.
*/
public static double sumDifference(final double[] sample1, final double[] sample2) {
public static double sumDifference(final double[] sample1, final double[] sample2)
throws DimensionMismatchException, NoDataException {
int n = sample1.length;
if (n != sample2.length) {
throw new DimensionMismatchException(n, sample2.length);
@ -719,7 +724,8 @@ public final class StatUtils {
* (positive) length.
* @throws NoDataException if the sample arrays are empty.
*/
public static double meanDifference(final double[] sample1, final double[] sample2) {
public static double meanDifference(final double[] sample1, final double[] sample2)
throws DimensionMismatchException, NoDataException{
return sumDifference(sample1, sample2) / sample1.length;
}
@ -737,8 +743,8 @@ public final class StatUtils {
* @throws NumberIsTooSmallException if the arrays length is less than 2.
*/
public static double varianceDifference(final double[] sample1,
final double[] sample2,
double meanDifference) {
final double[] sample2, double meanDifference) throws DimensionMismatchException,
NumberIsTooSmallException {
double sum1 = 0d;
double sum2 = 0d;
double diff = 0d;
@ -758,7 +764,7 @@ public final class StatUtils {
}
/**
* Normalize (standardize) the series, so in the end it is having a mean of 0 and a standard deviation of 1.
* Normalize (standardize) the sample, so it is has a mean of 0 and a standard deviation of 1.
*
* @param sample Sample to normalize.
* @return normalized (standardized) sample.

View File

@ -95,10 +95,12 @@ public class KMeansPlusPlusClusterer<T extends Clusterable<T>> {
* @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<Cluster<T>> cluster(final Collection<T> points, final int k,
int numTrials, int maxIterationsPerTrial)
throws MathIllegalArgumentException {
throws MathIllegalArgumentException, ConvergenceException {
// at first, we have not found any clusters list yet
List<Cluster<T>> best = null;
@ -149,10 +151,12 @@ public class KMeansPlusPlusClusterer<T extends Clusterable<T>> {
* @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<Cluster<T>> cluster(final Collection<T> points, final int k,
final int maxIterations)
throws MathIllegalArgumentException {
throws MathIllegalArgumentException, ConvergenceException {
// sanity checks
MathUtils.checkNotNull(points);
@ -371,8 +375,10 @@ public class KMeansPlusPlusClusterer<T extends Clusterable<T>> {
*
* @param clusters the {@link Cluster}s to search
* @return a random point from the selected cluster
* @throws ConvergenceException if clusters are all empty
*/
private T getPointFromLargestVarianceCluster(final Collection<Cluster<T>> clusters) {
private T getPointFromLargestVarianceCluster(final Collection<Cluster<T>> clusters)
throws ConvergenceException {
double maxVariance = Double.NEGATIVE_INFINITY;
Cluster<T> selected = null;
@ -412,8 +418,9 @@ public class KMeansPlusPlusClusterer<T extends Clusterable<T>> {
*
* @param clusters the {@link Cluster}s to search
* @return a random point from the selected cluster
* @throws ConvergenceException if clusters are all empty
*/
private T getPointFromLargestNumberCluster(final Collection<Cluster<T>> clusters) {
private T getPointFromLargestNumberCluster(final Collection<Cluster<T>> clusters) throws ConvergenceException {
int maxNumber = 0;
Cluster<T> selected = null;
@ -446,8 +453,9 @@ public class KMeansPlusPlusClusterer<T extends Clusterable<T>> {
*
* @param clusters the {@link Cluster}s to search
* @return point farthest to its cluster center
* @throws ConvergenceException if clusters are all empty
*/
private T getFarthestPoint(final Collection<Cluster<T>> clusters) {
private T getFarthestPoint(final Collection<Cluster<T>> clusters) throws ConvergenceException {
double maxDistance = Double.NEGATIVE_INFINITY;
Cluster<T> selectedCluster = null;

View File

@ -75,10 +75,11 @@ public class Covariance {
*
* @param data rectangular array with columns representing covariates
* @param biasCorrected true means covariances are bias-corrected
* @throws IllegalArgumentException if the input data array is not
* @throws MathIllegalArgumentException if the input data array is not
* rectangular with at least two rows and two columns.
*/
public Covariance(double[][] data, boolean biasCorrected) {
public Covariance(double[][] data, boolean biasCorrected)
throws MathIllegalArgumentException {
this(new BlockRealMatrix(data), biasCorrected);
}
@ -90,10 +91,10 @@ public class Covariance {
* and two rows</p>
*
* @param data rectangular array with columns representing covariates
* @throws IllegalArgumentException if the input data array is not
* @throws MathIllegalArgumentException if the input data array is not
* rectangular with at least two rows and two columns.
*/
public Covariance(double[][] data) {
public Covariance(double[][] data) throws MathIllegalArgumentException {
this(data, true);
}
@ -108,10 +109,11 @@ public class Covariance {
*
* @param matrix matrix with columns representing covariates
* @param biasCorrected true means covariances are bias-corrected
* @throws IllegalArgumentException if the input matrix does not have
* @throws MathIllegalArgumentException if the input matrix does not have
* at least two rows and two columns
*/
public Covariance(RealMatrix matrix, boolean biasCorrected) {
public Covariance(RealMatrix matrix, boolean biasCorrected)
throws MathIllegalArgumentException {
checkSufficientData(matrix);
n = matrix.getRowDimension();
covarianceMatrix = computeCovarianceMatrix(matrix, biasCorrected);
@ -124,10 +126,10 @@ public class Covariance {
* <p>The matrix must have at least two columns and two rows</p>
*
* @param matrix matrix with columns representing covariates
* @throws IllegalArgumentException if the input matrix does not have
* @throws MathIllegalArgumentException if the input matrix does not have
* at least two rows and two columns
*/
public Covariance(RealMatrix matrix) {
public Covariance(RealMatrix matrix) throws MathIllegalArgumentException {
this(matrix, true);
}
@ -155,8 +157,10 @@ public class Covariance {
* @param matrix input matrix (must have at least two columns and two rows)
* @param biasCorrected determines whether or not covariance estimates are bias-corrected
* @return covariance matrix
* @throws MathIllegalArgumentException if the matrix does not contain sufficient data
*/
protected RealMatrix computeCovarianceMatrix(RealMatrix matrix, boolean biasCorrected) {
protected RealMatrix computeCovarianceMatrix(RealMatrix matrix, boolean biasCorrected)
throws MathIllegalArgumentException {
int dimension = matrix.getColumnDimension();
Variance variance = new Variance(biasCorrected);
RealMatrix outMatrix = new BlockRealMatrix(dimension, dimension);
@ -176,9 +180,11 @@ public class Covariance {
* covariates. Covariances are computed using the bias-corrected formula.
* @param matrix input matrix (must have at least two columns and two rows)
* @return covariance matrix
* @throws MathIllegalArgumentException if matrix does not contain sufficient data
* @see #Covariance
*/
protected RealMatrix computeCovarianceMatrix(RealMatrix matrix) {
protected RealMatrix computeCovarianceMatrix(RealMatrix matrix)
throws MathIllegalArgumentException {
return computeCovarianceMatrix(matrix, true);
}
@ -188,8 +194,11 @@ public class Covariance {
* @param data input array (must have at least two columns and two rows)
* @param biasCorrected determines whether or not covariance estimates are bias-corrected
* @return covariance matrix
* @throws MathIllegalArgumentException if the data array does not contain sufficient
* data
*/
protected RealMatrix computeCovarianceMatrix(double[][] data, boolean biasCorrected) {
protected RealMatrix computeCovarianceMatrix(double[][] data, boolean biasCorrected)
throws MathIllegalArgumentException {
return computeCovarianceMatrix(new BlockRealMatrix(data), biasCorrected);
}
@ -198,9 +207,10 @@ public class Covariance {
* covariates. Covariances are computed using the bias-corrected formula.
* @param data input array (must have at least two columns and two rows)
* @return covariance matrix
* @throws MathIllegalArgumentException if the data array does not contain sufficient data
* @see #Covariance
*/
protected RealMatrix computeCovarianceMatrix(double[][] data) {
protected RealMatrix computeCovarianceMatrix(double[][] data) throws MathIllegalArgumentException {
return computeCovarianceMatrix(data, true);
}
@ -213,11 +223,11 @@ public class Covariance {
* @param yArray second data array
* @param biasCorrected if true, returned value will be bias-corrected
* @return returns the covariance for the two arrays
* @throws IllegalArgumentException if the arrays lengths do not match or
* @throws MathIllegalArgumentException if the arrays lengths do not match or
* there is insufficient data
*/
public double covariance(final double[] xArray, final double[] yArray, boolean biasCorrected)
throws IllegalArgumentException {
throws MathIllegalArgumentException {
Mean mean = new Mean();
double result = 0d;
int length = xArray.length;
@ -248,20 +258,22 @@ public class Covariance {
* @param xArray first data array
* @param yArray second data array
* @return returns the covariance for the two arrays
* @throws IllegalArgumentException if the arrays lengths do not match or
* @throws MathIllegalArgumentException if the arrays lengths do not match or
* there is insufficient data
*/
public double covariance(final double[] xArray, final double[] yArray)
throws IllegalArgumentException {
throws MathIllegalArgumentException {
return covariance(xArray, yArray, true);
}
/**
* Throws IllegalArgumentException of the matrix does not have at least
* two columns and two rows
* Throws MathIllegalArgumentException if the matrix does not have at least
* two columns and two rows.
* @param matrix matrix to check
* @throws MathIllegalArgumentException if the matrix does not contain sufficient data
* to compute covariance
*/
private void checkSufficientData(final RealMatrix matrix) {
private void checkSufficientData(final RealMatrix matrix) throws MathIllegalArgumentException {
int nRows = matrix.getRowDimension();
int nCols = matrix.getColumnDimension();
if (nRows < 2 || nCols < 2) {

View File

@ -181,6 +181,7 @@ public class MannWhitneyUTest {
final double z = (Umin - EU) / FastMath.sqrt(VarU);
// No try-catch or advertised exception because args are valid
final NormalDistribution standardNormal = new NormalDistribution(0, 1);
return 2 * standardNormal.cumulativeProbability(z);

View File

@ -125,6 +125,7 @@ public class OneWayAnova {
ConvergenceException, MaxCountExceededException {
AnovaStats a = anovaStats(categoryData);
// No try-catch or advertised exception because args are valid
FDistribution fdist = new FDistribution(a.dfbg, a.dfwg);
return 1.0 - fdist.cumulativeProbability(a.F);
@ -253,7 +254,7 @@ public class OneWayAnova {
}
/**
Convenience class to pass dfbg,dfwg,F values around within AnovaImpl.
Convenience class to pass dfbg,dfwg,F values around within OneWayAnova.
No get/set methods provided.
*/
private static class AnovaStats {

View File

@ -18,8 +18,10 @@ package org.apache.commons.math3.stat.inference;
import org.apache.commons.math3.distribution.TDistribution;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.exception.MaxCountExceededException;
import org.apache.commons.math3.exception.NoDataException;
import org.apache.commons.math3.exception.NotStrictlyPositiveException;
import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.commons.math3.exception.NumberIsTooSmallException;
import org.apache.commons.math3.exception.OutOfRangeException;
@ -202,6 +204,7 @@ public class TTest {
throws NullArgumentException, NumberIsTooSmallException {
checkSampleData(observed);
// No try-catch or advertised exception because args have just been checked
return t(StatUtils.mean(observed), mu, StatUtils.variance(observed),
observed.length);
@ -272,6 +275,7 @@ public class TTest {
checkSampleData(sample1);
checkSampleData(sample2);
// No try-catch or advertised exception because args have just been checked
return homoscedasticT(StatUtils.mean(sample1), StatUtils.mean(sample2),
StatUtils.variance(sample1), StatUtils.variance(sample2),
sample1.length, sample2.length);
@ -312,6 +316,7 @@ public class TTest {
checkSampleData(sample1);
checkSampleData(sample2);
// No try-catch or advertised exception because args have just been checked
return t(StatUtils.mean(sample1), StatUtils.mean(sample2),
StatUtils.variance(sample1), StatUtils.variance(sample2),
sample1.length, sample2.length);
@ -442,6 +447,7 @@ public class TTest {
MaxCountExceededException {
checkSampleData(sample);
// No try-catch or advertised exception because args have just been checked
return tTest(StatUtils.mean(sample), mu, StatUtils.variance(sample),
sample.length);
@ -623,6 +629,7 @@ public class TTest {
checkSampleData(sample1);
checkSampleData(sample2);
// No try-catch or advertised exception because args have just been checked
return tTest(StatUtils.mean(sample1), StatUtils.mean(sample2),
StatUtils.variance(sample1), StatUtils.variance(sample2),
sample1.length, sample2.length);
@ -669,6 +676,7 @@ public class TTest {
checkSampleData(sample1);
checkSampleData(sample2);
// No try-catch or advertised exception because args have just been checked
return homoscedasticTTest(StatUtils.mean(sample1),
StatUtils.mean(sample2),
StatUtils.variance(sample1),
@ -1043,10 +1051,11 @@ public class TTest {
* @param n sample n
* @return p-value
* @throws MaxCountExceededException if an error occurs computing the p-value
* @throws MathIllegalArgumentException if n is not greater than 1
*/
protected double tTest(final double m, final double mu,
final double v, final double n)
throws MaxCountExceededException {
throws MaxCountExceededException, MathIllegalArgumentException {
double t = FastMath.abs(t(m, mu, v, n));
TDistribution distribution = new TDistribution(n - 1);
@ -1068,11 +1077,13 @@ public class TTest {
* @param n2 second sample n
* @return p-value
* @throws MaxCountExceededException if an error occurs computing the p-value
* @throws NotStrictlyPositiveException if the estimated degrees of freedom is not
* strictly positive
*/
protected double tTest(final double m1, final double m2,
final double v1, final double v2,
final double n1, final double n2)
throws MaxCountExceededException {
throws MaxCountExceededException, NotStrictlyPositiveException {
final double t = FastMath.abs(t(m1, m2, v1, v2, n1, n2));
final double degreesOfFreedom = df(v1, v2, n1, n2);
@ -1095,11 +1106,13 @@ public class TTest {
* @param n2 second sample n
* @return p-value
* @throws MaxCountExceededException if an error occurs computing the p-value
* @throws NotStrictlyPositiveException if the estimated degrees of freedom is not
* strictly positive
*/
protected double homoscedasticTTest(double m1, double m2,
double v1, double v2,
double n1, double n2)
throws MaxCountExceededException {
throws MaxCountExceededException, NotStrictlyPositiveException {
final double t = FastMath.abs(homoscedasticT(m1, m2, v1, v2, n1, n2));
final double degreesOfFreedom = n1 + n2 - 2;

View File

@ -253,6 +253,7 @@ public class WilcoxonSignedRankTest {
// - 0.5 is a continuity correction
final double z = (Wmin - ES - 0.5) / FastMath.sqrt(VarS);
// No try-catch or advertised exception because args are valid
final NormalDistribution standardNormal = new NormalDistribution(0, 1);
return 2*standardNormal.cumulativeProbability(z);

View File

@ -345,6 +345,7 @@ public class NaturalRanking implements RankingAlgorithm {
Iterator<Integer> iterator = tiesTrace.iterator();
long f = FastMath.round(c);
while (iterator.hasNext()) {
// No advertised exception because args are guaranteed valid
ranks[iterator.next()] =
randomData.nextLong(f, f + length - 1);
}

View File

@ -222,7 +222,7 @@ public abstract class AbstractMultipleLinearRegression implements
* @throws MathIllegalArgumentException if the number of rows of {@code x}
* is not larger than the number of columns + 1
*/
protected void validateSampleData(double[][] x, double[] y) {
protected void validateSampleData(double[][] x, double[] y) throws MathIllegalArgumentException {
if ((x == null) || (y == null)) {
throw new NullArgumentException();
}

View File

@ -95,8 +95,10 @@ public class MillerUpdatingRegression implements UpdatingMultipleLinearRegressio
* @param numberOfVariables number of regressors to expect, not including constant
* @param includeConstant include a constant automatically
* @param errorTolerance zero tolerance, how machine zero is determined
* @throws ModelSpecificationException if {@code numberOfVariables is less than 1}
*/
public MillerUpdatingRegression(int numberOfVariables, boolean includeConstant, double errorTolerance) {
public MillerUpdatingRegression(int numberOfVariables, boolean includeConstant, double errorTolerance)
throws ModelSpecificationException {
if (numberOfVariables < 1) {
throw new ModelSpecificationException(LocalizedFormats.NO_REGRESSORS);
}
@ -132,8 +134,10 @@ public class MillerUpdatingRegression implements UpdatingMultipleLinearRegressio
*
* @param numberOfVariables maximum number of potential regressors
* @param includeConstant include a constant automatically
* @throws ModelSpecificationException if {@code numberOfVariables is less than 1}
*/
public MillerUpdatingRegression(int numberOfVariables, boolean includeConstant) {
public MillerUpdatingRegression(int numberOfVariables, boolean includeConstant)
throws ModelSpecificationException {
this(numberOfVariables, includeConstant, Precision.EPSILON);
}
@ -160,7 +164,8 @@ public class MillerUpdatingRegression implements UpdatingMultipleLinearRegressio
* @exception ModelSpecificationException if the length of {@code x} does not equal
* the number of independent variables in the model
*/
public void addObservation(final double[] x, final double y) {
public void addObservation(final double[] x, final double y)
throws ModelSpecificationException {
if ((!this.hasIntercept && x.length != nvars) ||
(this.hasIntercept && x.length + 1 != nvars)) {
@ -186,7 +191,7 @@ public class MillerUpdatingRegression implements UpdatingMultipleLinearRegressio
* @throws ModelSpecificationException if {@code x} is not rectangular, does not match
* the length of {@code y} or does not contain sufficient data to estimate the model
*/
public void addObservations(double[][] x, double[] y) {
public void addObservations(double[][] x, double[] y) throws ModelSpecificationException {
if ((x == null) || (y == null) || (x.length != y.length)) {
throw new ModelSpecificationException(
LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE,
@ -360,8 +365,10 @@ public class MillerUpdatingRegression implements UpdatingMultipleLinearRegressio
* @param nreq how many of the regressors to include (either in canonical
* order, or in the current reordered state)
* @return an array with the estimated slope coefficients
* @throws ModelSpecificationException if {@code nreq} is less than 1
* or greater than the number of independent variables
*/
private double[] regcf(int nreq) {
private double[] regcf(int nreq) throws ModelSpecificationException {
int nextr;
if (nreq < 1) {
throw new ModelSpecificationException(LocalizedFormats.NO_REGRESSORS);

View File

@ -16,6 +16,7 @@
*/
package org.apache.commons.math3.stat.regression;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.LUDecomposition;
import org.apache.commons.math3.linear.QRDecomposition;
@ -62,10 +63,10 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio
* Computes and caches QR decomposition of the X matrix.
* @param y the [n,1] array representing the y sample
* @param x the [n,k] array representing the x sample
* @throws IllegalArgumentException if the x and y array data are not
* @throws MathIllegalArgumentException if the x and y array data are not
* compatible for the regression
*/
public void newSampleData(double[] y, double[][] x) {
public void newSampleData(double[] y, double[][] x) throws MathIllegalArgumentException {
validateSampleData(x, y);
newYSampleData(y);
newXSampleData(x);
@ -93,6 +94,10 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio
* formula is from "The Hat Matrix in Regression and ANOVA",
* David C. Hoaglin and Roy E. Welsch,
* <i>The American Statistician</i>, Vol. 32, No. 1 (Feb., 1978), pp. 17-22.
* </p>
* <p>Data for the model must have been successfully loaded using one of
* the {@code newSampleData} methods before invoking this method; otherwise
* a {@code NullPointerException} will be thrown.</p>
*
* @return the hat matrix
*/
@ -101,6 +106,7 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio
RealMatrix Q = qr.getQ();
final int p = qr.getR().getColumnDimension();
final int n = Q.getColumnDimension();
// No try-catch or advertised NotStrictlyPositiveException - NPE above if n < 3
Array2DRowRealMatrix augI = new Array2DRowRealMatrix(n, n);
double[][] augIData = augI.getDataRef();
for (int i = 0; i < n; i++) {
@ -114,6 +120,7 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio
}
// Compute and return Hat matrix
// No DME advertised - args valid if we get here
return Q.multiply(augI).multiply(Q.transpose());
}
@ -127,10 +134,12 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio
* the {@link #calculateRSquared() R-squared} computation.</p>
*
* @return SSTO - the total sum of squares
* @throws MathIllegalArgumentException if the sample has not been set or does
* not contain at least 3 observations
* @see #isNoIntercept()
* @since 2.2
*/
public double calculateTotalSumOfSquares() {
public double calculateTotalSumOfSquares() throws MathIllegalArgumentException {
if (isNoIntercept()) {
return StatUtils.sumSq(getY().toArray());
} else {
@ -146,6 +155,7 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio
*/
public double calculateResidualSumOfSquares() {
final RealVector residuals = calculateResiduals();
// No advertised DME, args are valid
return residuals.dotProduct(residuals);
}
@ -157,9 +167,11 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio
* and SSTO is the {@link #calculateTotalSumOfSquares() total sum of squares}
*
* @return R-square statistic
* @throws MathIllegalArgumentException if the sample has not been set or does
* not contain at least 3 observations
* @since 2.2
*/
public double calculateRSquared() {
public double calculateRSquared() throws MathIllegalArgumentException {
return 1 - calculateResidualSumOfSquares() / calculateTotalSumOfSquares();
}
@ -176,10 +188,12 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio
* </pre></p>
*
* @return adjusted R-Squared statistic
* @throws MathIllegalArgumentException if the sample has not been set or does
* not contain at least 3 observations
* @see #isNoIntercept()
* @since 2.2
*/
public double calculateAdjustedRSquared() {
public double calculateAdjustedRSquared() throws MathIllegalArgumentException {
final double n = getX().getRowDimension();
if (isNoIntercept()) {
return 1 - (1 - calculateRSquared()) * (n / (n - getX().getColumnDimension()));
@ -203,6 +217,10 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio
/**
* Calculates the regression coefficients using OLS.
*
* <p>Data for the model must have been successfully loaded using one of
* the {@code newSampleData} methods before invoking this method; otherwise
* a {@code NullPointerException} will be thrown.</p>
*
* @return beta
*/
@Override
@ -219,6 +237,10 @@ public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegressio
* to (R<sup>T</sup>R)<sup>-1</sup>, with only the top p rows of
* R included, where p = the length of the beta vector.</p>
*
* <p>Data for the model must have been successfully loaded using one of
* the {@code newSampleData} methods before invoking this method; otherwise
* a {@code NullPointerException} will be thrown.</p>
*
* @return The beta variance-covariance matrix
*/
@Override

View File

@ -147,7 +147,7 @@ public class RegressionResults implements Serializable {
* @throws OutOfRangeException if {@code index} is not in the interval
* {@code [0, number of parameters)}.
*/
public double getParameterEstimate(int index) {
public double getParameterEstimate(int index) throws OutOfRangeException {
if (parameters == null) {
return Double.NaN;
}
@ -184,7 +184,7 @@ public class RegressionResults implements Serializable {
* @throws OutOfRangeException if {@code index} is not in the interval
* {@code [0, number of parameters)}.
*/
public double getStdErrorOfEstimate(int index) {
public double getStdErrorOfEstimate(int index) throws OutOfRangeException {
if (parameters == null) {
return Double.NaN;
}
@ -237,7 +237,7 @@ public class RegressionResults implements Serializable {
* @throws OutOfRangeException if {@code i} or {@code j} is not in the
* interval {@code [0, number of parameters)}.
*/
public double getCovarianceOfParameters(int i, int j) {
public double getCovarianceOfParameters(int i, int j) throws OutOfRangeException {
if (parameters == null) {
return Double.NaN;
}

View File

@ -214,7 +214,7 @@ public class SimpleRegression implements Serializable, UpdatingMultipleLinearReg
* @throws ModelSpecificationException if the length of {@code data[i]} is not
* greater than or equal to 2
*/
public void addData(final double[][] data) {
public void addData(final double[][] data) throws ModelSpecificationException {
for (int i = 0; i < data.length; i++) {
if( data[i].length < 2 ){
throw new ModelSpecificationException(LocalizedFormats.INVALID_REGRESSION_OBSERVATION,
@ -232,7 +232,8 @@ public class SimpleRegression implements Serializable, UpdatingMultipleLinearReg
* @throws ModelSpecificationException if the length of {@code x} does not equal
* the number of independent variables in the model
*/
public void addObservation(final double[] x,final double y) throws ModelSpecificationException{
public void addObservation(final double[] x,final double y)
throws ModelSpecificationException {
if( x == null || x.length == 0 ){
throw new ModelSpecificationException(LocalizedFormats.INVALID_REGRESSION_OBSERVATION,x!=null?x.length:0, 1);
}
@ -249,7 +250,7 @@ public class SimpleRegression implements Serializable, UpdatingMultipleLinearReg
* @throws ModelSpecificationException if {@code x} is not rectangular, does not match
* the length of {@code y} or does not contain sufficient data to estimate the model
*/
public void addObservations(final double[][] x,final double[] y) {
public void addObservations(final double[][] x,final double[] y) throws ModelSpecificationException {
if ((x == null) || (y == null) || (x.length != y.length)) {
throw new ModelSpecificationException(
LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE,
@ -605,7 +606,7 @@ public class SimpleRegression implements Serializable, UpdatingMultipleLinearReg
* @return half-width of 95% confidence interval for the slope estimate
* @throws OutOfRangeException if the confidence interval can not be computed.
*/
public double getSlopeConfidenceInterval() {
public double getSlopeConfidenceInterval() throws OutOfRangeException {
return getSlopeConfidenceInterval(0.05d);
}
@ -640,11 +641,16 @@ public class SimpleRegression implements Serializable, UpdatingMultipleLinearReg
* @return half-width of 95% confidence interval for the slope estimate
* @throws OutOfRangeException if the confidence interval can not be computed.
*/
public double getSlopeConfidenceInterval(final double alpha) {
public double getSlopeConfidenceInterval(final double alpha)
throws OutOfRangeException {
if (n < 3) {
return Double.NaN;
}
if (alpha >= 1 || alpha <= 0) {
throw new OutOfRangeException(LocalizedFormats.SIGNIFICANCE_LEVEL,
alpha, 0, 1);
}
// No advertised NotStrictlyPositiveException here - will return NaN above
TDistribution distribution = new TDistribution(n - 2);
return getSlopeStdErr() *
distribution.inverseCumulativeProbability(1d - alpha / 2d);
@ -673,6 +679,10 @@ public class SimpleRegression implements Serializable, UpdatingMultipleLinearReg
* if the significance level can not be computed.
*/
public double getSignificance() {
if (n < 3) {
return Double.NaN;
}
// No advertised NotStrictlyPositiveException here - will return NaN above
TDistribution distribution = new TDistribution(n - 2);
return 2d * (1.0 - distribution.cumulativeProbability(
FastMath.abs(getSlope()) / getSlopeStdErr()));
@ -706,14 +716,21 @@ public class SimpleRegression implements Serializable, UpdatingMultipleLinearReg
}
/**
* Performs a regression on data present in buffers and outputs a RegressionResults object
* Performs a regression on data present in buffers and outputs a RegressionResults object.
*
* <p>If there are fewer than 3 observations in the model and {@code hasIntercept} is true
* a {@code NoDataException} is thrown. If there is no intercept term, the model must
* contain at least 2 observations.</p>
*
* @return RegressionResults acts as a container of regression output
* @throws ModelSpecificationException if the model is not correctly specified
* @throws NoDataException if there is not sufficient data in the model to
* estimate the regression parameters
*/
public RegressionResults regress() throws ModelSpecificationException{
if( hasIntercept ){
public RegressionResults regress() throws ModelSpecificationException, NoDataException {
if (hasIntercept) {
if( n < 3 ){
throw new NoDataException( LocalizedFormats.NOT_ENOUGH_DATA_REGRESSION );
throw new NoDataException(LocalizedFormats.NOT_ENOUGH_DATA_REGRESSION);
}
if( FastMath.abs( sumXX ) > Precision.SAFE_MIN ){
final double[] params = new double[]{ getIntercept(), getSlope() };
@ -738,8 +755,8 @@ public class SimpleRegression implements Serializable, UpdatingMultipleLinearReg
sumY, sumYY, getSumSquaredErrors(),true,false);
}
}else{
if( n < 2 ){
throw new NoDataException( LocalizedFormats.NOT_ENOUGH_DATA_REGRESSION );
if (n < 2) {
throw new NoDataException(LocalizedFormats.NOT_ENOUGH_DATA_REGRESSION);
}
if( !Double.isNaN(sumXX) ){
final double[] vcv = new double[]{ getMeanSquareError() / sumXX };
@ -762,11 +779,10 @@ public class SimpleRegression implements Serializable, UpdatingMultipleLinearReg
* indexed in variablesToInclude and outputs a RegressionResults object
* @param variablesToInclude an array of indices of regressors to include
* @return RegressionResults acts as a container of regression output
* @throws ModelSpecificationException if the model is not correctly specified
* @throws MathIllegalArgumentException if the variablesToInclude array is null or zero length
* @throws OutOfRangeException if a requested variable is not present in model
*/
public RegressionResults regress(int[] variablesToInclude) throws ModelSpecificationException{
public RegressionResults regress(int[] variablesToInclude) throws MathIllegalArgumentException{
if( variablesToInclude == null || variablesToInclude.length == 0){
throw new MathIllegalArgumentException(LocalizedFormats.ARRAY_ZERO_LENGTH_OR_NULL_NOT_ALLOWED);
}

View File

@ -16,6 +16,9 @@
*/
package org.apache.commons.math3.stat.regression;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.exception.NoDataException;
/**
* An interface for regression models allowing for dynamic updating of the data.
* That is, the entire data set need not be loaded into memory. As observations
@ -74,8 +77,10 @@ public interface UpdatingMultipleLinearRegression {
* Performs a regression on data present in buffers and outputs a RegressionResults object
* @return RegressionResults acts as a container of regression output
* @throws ModelSpecificationException if the model is not correctly specified
* @throws NoDataException if there is not sufficient data in the model to
* estimate the regression parameters
*/
RegressionResults regress() throws ModelSpecificationException;
RegressionResults regress() throws ModelSpecificationException, NoDataException;
/**
* Performs a regression on data present in buffers including only regressors
@ -83,6 +88,7 @@ public interface UpdatingMultipleLinearRegression {
* @param variablesToInclude an array of indices of regressors to include
* @return RegressionResults acts as a container of regression output
* @throws ModelSpecificationException if the model is not correctly specified
* @throws MathIllegalArgumentException if the variablesToInclude array is null or zero length
*/
RegressionResults regress(int[] variablesToInclude) throws ModelSpecificationException;
RegressionResults regress(int[] variablesToInclude) throws ModelSpecificationException, MathIllegalArgumentException;
}