diff --git a/src/java/org/apache/commons/math/MathRuntimeException.java b/src/java/org/apache/commons/math/MathRuntimeException.java index 58877eac8..9c32573f1 100644 --- a/src/java/org/apache/commons/math/MathRuntimeException.java +++ b/src/java/org/apache/commons/math/MathRuntimeException.java @@ -293,6 +293,19 @@ public class MathRuntimeException extends RuntimeException { }; } + /** + * Constructs a new IllegalArgumentException with specified nested + * Throwable root cause. + * @param rootCause the exception or error that caused this exception + * to be thrown. + * @return built exception + */ + public static IllegalArgumentException createIllegalArgumentException(final Throwable rootCause) { + IllegalArgumentException iae = new IllegalArgumentException(rootCause.getLocalizedMessage()); + iae.initCause(rootCause); + return iae; + } + /** * Constructs a new IllegalStateException with specified formatted detail message. * Message formatting is delegated to {@link java.text.MessageFormat}. diff --git a/src/java/org/apache/commons/math/MessagesResources_fr.java b/src/java/org/apache/commons/math/MessagesResources_fr.java index c738ea1ea..63f23ad11 100644 --- a/src/java/org/apache/commons/math/MessagesResources_fr.java +++ b/src/java/org/apache/commons/math/MessagesResources_fr.java @@ -46,11 +46,23 @@ public class MessagesResources_fr private static final Object[][] contents = { // org.apache.commons.math.util.MathUtils + { "must have n >= k for binomial coefficient (n,k), got n = {0}, k = {1}", + "n doit \u00eatre sup\u00e9rieur ou \u00e9gal \u00e0 k " + + "pour le coefficient du bin\u00f4me (n,k), or n = {0}, k = {1}" }, + { "must have n >= 0 for binomial coefficient (n,k), got n = {0}", + "n doit \u00eatre positif pour le coefficient du bin\u00f4me (n,k), or n = {0}" }, + { "must have n >= 0 for n!, got n = {0}", + "n doit \u00eatre positif pour le calcul de n!, or n = {0}" }, { "overflow: gcd({0}, {1}) is 2^31", "d\u00e9passement de capacit\u00e9 : le PGCD de {0} et {1} vaut 2^31" }, { "cannot raise an integral value to a negative power ({0}^{1})", - "impossible d''\u00e9lever une valeur enti\u00e8re \u00e0 une puissance n\u00e9gative ({0}^{1})" }, - + "impossible d''\u00e9lever une valeur enti\u00e8re " + + "\u00e0 une puissance n\u00e9gative ({0}^{1})" }, + { "invalid rounding method {0}, valid methods: {1} ({2}), {3} ({4})," + + " {5} ({6}), {7} ({8}), {9} ({10}), {11} ({12}), {13} ({14}), {15} ({16})", + "m\u00e9thode d''arondi {0} invalide, m\u00e9thodes valides : {1} ({2}), {3} ({4})," + + " {5} ({6}), {7} ({8}), {9} ({10}), {11} ({12}), {13} ({14}), {15} ({16})" }, + // org.apache.commons.math.FunctionEvaluationException { "evaluation failed for argument = {0}", "erreur d''\u00e9valuation pour l''argument {0}" }, @@ -77,6 +89,8 @@ public class MessagesResources_fr // org.apache.commons.math.optimization.LeastSquaresConverter // org.apache.commons.math.optimization.direct.DirectSearchOptimizer // org.apache.commons.math.optimization.general.AbstractLeastSquaresOptimizer + // org.apache.commons.math.ode.ContinuousOutputModel + // org.apache.commons.math.random.UncorrelatedRandomVectorGenerator { "dimension mismatch {0} != {1}", "dimensions incompatibles {0} != {1}" }, @@ -265,20 +279,58 @@ public class MessagesResources_fr // org.apache.commons.math.optimization.direct.DirectSearchOptimizer { "unexpected exception caught", "exception inattendue lev\u00e9e" }, + { "propagation direction mismatch", + "directions de propagation incoh\u00e9rentes" }, + { "{0} wide hole between models time ranges", + "trou de longueur {0} entre les domaines temporels des mod\u00e8les" }, // org.apache.commons.math.optimization.direct.DirectSearchOptimizer { "none of the {0} start points lead to convergence", "aucun des {0} points de d\u00e9part n''aboutit \u00e0 une convergence" }, + // org.apache.commons.math.random.ValueServer + { "unknown mode {0}, known modes: {1} ({2}), {3} ({4}), {5} ({6}), {7} ({8}), {9} ({10}) and {11} ({12})", + "mode {0} inconnu, modes connus : {1} ({2}), {3} ({4}), {5} ({6}), {7} ({8}), {9} ({10}) et {11} ({12})" }, + { "digest not initialized", + "mod\u00e8le empirique non initialis\u00e9" }, + // org.apache.commons.math.random.EmpiricalDistributionImpl + { "distribution not loaded", + "aucune distribution n''a \u00e9t\u00e9 charg\u00e9e" }, { "no bin selected", "aucun compartiment s\u00e9lectionn\u00e9" }, + { "input data comes from unsupported datasource: {0}, supported sources: {1}, {2}", + "les donn\u00e9es d''entr\u00e9e proviennent " + + "d''une source non support\u00e9e : {0}, sources support\u00e9es : {1}, {2}" }, + + // org.apache.commons.math.random.EmpiricalDistributionImpl + // org.apache.commons.math.random.ValueServer + { "URL {0} contains no data", + "l''adresse {0} ne contient aucune donn\u00e9e" }, + + // org.apache.commons.math.random.AbstractRandomGenerator + { "upper bound must be positive ({0})", + "la borne sup\u00e9rieure doit \u00eatre positive ({0})" }, + + // org.apache.commons.math.random.RandomDataImpl + { "length must be positive ({0})", + "la longueur doit \u00eatre positive ({0})" }, + { "upper bound ({0}) must be greater than lower bound ({1})", + "la borne sup\u00e9rieure ({0}) doit \u00eatre sup\u00e9rieure" + + " \u00e0 la borne inf\u00e9rieure ({1})" }, + { "permutation k ({0}) exceeds n ({1})", + "la permutation k ({0}) d\u00e9passe n ({1})" }, + { "permutation k ({0}) must be positive", + "la permutation k ({0}) doit \u00eatre positive" }, + { "sample size ({0}) exceeds collection size ({1})", + "la taille de l''\u00e9chantillon ({0}) d\u00e9passe la taille de la collection ({1})" }, // org.apache.commons.math.linear.decomposition.EigenDecompositionImpl { "cannot solve degree {0} equation", "impossible de r\u00e9soudre une \u00e9quation de degr\u00e9 {0}" }, { "eigen decomposition of assymetric matrices not supported yet", - "la d\u00e9composition en valeurs/vecteurs propres de matrices non sym\u00e9triques n''est pas encore disponible" }, + "la d\u00e9composition en valeurs/vecteurs propres de matrices " + + "non sym\u00e9triques n''est pas encore disponible" }, // org.apache.commons.math.linear.decomposition.NonSquareMatrixException { "a {0}x{1} matrix was provided instead of a square matrix", @@ -332,6 +384,20 @@ public class MessagesResources_fr "une matrice doit comporter au moins une colonne" }, { "some rows have length {0} while others have length {1}", "certaines lignes ont une longueur de {0} alors que d''autres ont une longueur de {1}" }, + + // org.apache.commons.math.linear.MatrixUtils + { "row index {0} out of allowed range [{1}, {2}]", + "index de ligne {0} hors de la plage autoris\u00e9e [{1}, {2}]" }, + { "column index {0} out of allowed range [{1}, {2}]", + "index de colonne {0} hors de la plage autoris\u00e9e [{1}, {2}]" }, + { "initial row {0} after final row {1}", + "ligne initiale {0} apr\u00e8s la ligne finale {1}" }, + { "initial column {0} after final column {1}", + "colonne initiale {0} apr\u00e8s la colonne finale {1}" }, + { "empty selected row index array", + "tableau des indices de lignes s\u00e9lectionn\u00e9es vide" }, + { "empty selected column index array", + "tableau des indices de colonnes s\u00e9lectionn\u00e9es vide" }, { "{0}x{1} and {2}x{3} matrices are not addition compatible", "les dimensions {0}x{1} et {2}x{3} sont incompatibles pour l'addition matricielle" }, { "{0}x{1} and {2}x{3} matrices are not subtraction compatible", @@ -343,43 +409,37 @@ public class MessagesResources_fr { "wrong array shape (block length = {0}, expected {1})", "forme de tableau erron\u00e9e (bloc de longueur {0} au lieu des {1} attendus)" }, - // org.apache.commons.math.linear.BigMatrixImpl - // org.apache.commons.math.linear.RealMatrixImpl - { "row index {0} out of allowed range [{1}, {2}]", - "index de ligne {0} hors de la plage autoris\u00e9e [{1}, {2}]" }, - { "column index {0} out of allowed range [{1}, {2}]", - "index de colonne {0} hors de la plage autoris\u00e9e [{1}, {2}]" }, - { "no entry at indices ({0}, {1}) in a {2}x{3} matrix", - "pas d''entr\u00e9e aux indices ({0}, {1}) dans une matrice {2}x{3}" }, - { "initial row {0} after final row {1}", - "ligne initiale {0} apr\u00e8s la ligne finale {1}" }, - { "initial column {0} after final column {1}", - "colonne initiale {0} apr\u00e8s la colonne finale {1}" }, - { "empty selected row index array", - "tableau des indices de lignes s\u00e9lectionn\u00e9es vide" }, - { "empty selected column index array", - "tableau des indices de colonnes s\u00e9lectionn\u00e9es vide" }, - - // org.apache.commons.math.random.EmpiricalDistributionImpl - // org.apache.commons.math.random.ValueServer - { "URL {0} contains no data", - "l''adresse {0} ne contient aucune donn\u00e9e" }, - - // org.apache.commons.math.complex.Complex - { "cannot compute nth root for null or negative n: {0}", + // org.apache.commons.math.complex.Complex + { "cannot compute nth root for null or negative n: {0}", "impossible de calculer la racine ni\u00e8me pour n n\u00e9gatif ou nul : {0}" }, // org.apache.commons.math.complex.ComplexFormat { "unparseable complex number: \"{0}\"", "\u00e9chec d''analyse du nombre complexe \"{0}\"" }, + { "cannot format a {0} instance as a complex number", + "impossible de formater une instance de {0} comme un nombre complexe" }, + { "empty string for imaginary character", + "cha\u00eene vide pour le caract\u00e8 imaginaire" }, + { "null imaginary format", + "format imaginaire nul" }, + { "null real format", + "format r\u00e9el nul" }, + + // org.apache.commons.math.complex.ComplexUtils + { "negative complex module {0}", + "module n\u00e9gatif ({0}) pour un nombre complexe" }, // org.apache.commons.math.geometry.Vector3DFormat { "unparseable 3D vector: \"{0}\"", "\u00e9chec d''analyse du vecteur de dimension 3 \"{0}\"" }, + { "cannot format a {0} instance as a 3D vector", + "impossible de formater une instance de {0} comme un vecteur de dimension 3" }, // org.apache.commons.math.linear.RealVectorFormat { "unparseable real vector: \"{0}\"", "\u00e9chec d''analyse du vecteur r\u00e9el \"{0}\"" }, + { "cannot format a {0} instance as a real vector", + "impossible de formater une instance de {0} comme un vecteur r\u00e9el" }, // org.apache.commons.math.util.ResizableDoubleArray { "the index specified: {0} is larger than the current maximal index {1}", @@ -480,10 +540,14 @@ public class MessagesResources_fr "d\u00e9passement de capacit\u00e9 pour le num\u00e9rateur apr\u00e8s multiplication : {0}" }, { "the fraction to divide by must not be zero: {0}/{1}", "division par un nombre rationnel nul : {0}/{1}" }, + { "null fraction", + "fraction nulle" }, // org.apache.commons.math.geometry.Rotation { "zero norm for rotation axis", "norme nulle pour un axe de rotation" }, + { "zero norm for rotation defining vector", + "norme nulle pour un axe de d\u00e9finition de rotation" }, // org.apache.commons.math.geometry.Vector3D // org.apache.commons.math.linear.RealVectorImpl @@ -502,20 +566,24 @@ public class MessagesResources_fr { "first {0} columns are not initialized yet", "les {0} premi\u00e8res colonnes ne sont pas encore initialis\u00e9es" }, - // org.apache.commons.math.random.EmpiricalDistributionImpl - { "distribution not loaded", - "aucune distribution n''a \u00e9t\u00e9 charg\u00e9e" }, + // org.apache.commons.math.stat.Frequency + { "class ({0}) does not implement Comparable", + "la classe ({0}) n''implante pas l''interface Comparable" }, + { "instance of class {0} not comparable to existing values", + "l''instance de la classe {0} n''est pas comparable aux valeurs existantes" }, - // org.apache.commons.math.random.ValueServer - { "unknown mode {0}, known modes: {1} ({2}), {3} ({4}), {5} ({6}), {7} ({8}), {9} ({10}) and {11} ({12})", - "mode {0} inconnu, modes connus : {1} ({2}), {3} ({4}), {5} ({6}), {7} ({8}), {9} ({10}) et {11} ({12})" }, - { "digest not initialized", - "mod\u00e8le empirique non initialis\u00e9" }, + // org.apache.commons.math.stat.StatUtils + { "input arrays must have the same positive length ({0} and {1})", + "les tableaux d''entr\u00e9e doivent avoir la m\u00eame taille positive ({0} et {1})" }, + { "input arrays must have the same length and at least two elements ({0} and {1})", + "les tableaux d''entr\u00e9e doivent avoir la m\u00eame taille" + + " et au moins deux \u00e9l\u00e9ments ({0} et {1})" }, // org.apache.commons.math.stat.correlation.Covariance { "arrays must have the same length and both must have at " + "least two elements. xArray has size {0}, yArray has {1} elements", - "les tableaux doivent avoir la m\u00eame taille et comporter au moins deux \u00e9l\u00e9ments. " + + "les tableaux doivent avoir la m\u00eame taille " + + "et comporter au moins deux \u00e9l\u00e9ments. " + "xArray a une taille de {0}, yArray a {1} \u00e9l\u00e9ments"}, { "insufficient data: only {0} rows and {1} columns.", "donn\u00e9es insuffisantes : seulement {0} lignes et {1} colonnes." }, @@ -524,19 +592,127 @@ public class MessagesResources_fr { "covariance matrix is null", "la matrice de covariance est nulle" }, { "invalid array dimensions. xArray has size {0}; yArray has {1} elements", - "dimensions de tableaux invalides. xArray a une taille de {0}, yArray a {1} \u00e9l\u00e9ments" }, + "dimensions de tableaux invalides. xArray a une taille de {0}, " + + "yArray a {1} \u00e9l\u00e9ments" }, + + // org.apache.commons.math.stat.descriptive.DescriptiveStatistics + { "window size must be positive ({0})", + "la taille de la fen\u00eatre doit \u00eatre positive ({0})" }, + { "percentile implementation {0} does not support setQuantile", + "l''implantation de pourcentage {0} ne dispose pas de la m\u00e9thode setQuantile" }, + { "cannot access setQuantile method in percentile implementation {0}", + "acc\u00e8s impossible \u00e0 la m\u00e9thode setQuantile" + + " dans l''implantation de pourcentage {0}" }, + { "out of bounds quantile value: {0}, must be in (0, 100]", + "valeur de quantile {0} hors bornes, doit \u00eatre dans l''intervalle ]0, 100]" }, + + // org.apache.commons.math.stat.descriptive.moment.Variance + // org.apache.commons.math.stat.descriptive.AbstractStorelessUnivariateStatistic + // org.apache.commons.math.stat.descriptive.AbstractUnivariateStatistic + { "input values array is null", + "le tableau des valeurs d''entr\u00e9es est nul" }, + + // org.apache.commons.math.stat.descriptive.AbstractUnivariateStatistic + { "start position cannot be negative ({0})", + "la position de d\u00e9part ne peut pas \u00eatre n\u00e9gative" }, + { "length cannot be negative ({0})", + "la longueur ne peut pas \u00eatre n\u00e9gative" }, + { "subarray ends after array end", + "le sous-tableau se termine apr\u00e8s la fin du tableau" }, // org.apache.commons.math.stat.descriptive.moment.GeometricMean // org.apache.commons.math.stat.descriptive.MultivariateSummaryStatistics // org.apache.commons.math.stat.descriptive.SummaryStatistics { "{0} values have been added before statistic is configured", - "{0} valeurs ont \u00e9t\u00e9 ajout\u00e9es avant que la statistique ne soit configur\u00e9e" }, + "{0} valeurs ont \u00e9t\u00e9 ajout\u00e9es " + + "avant que la statistique ne soit configur\u00e9e" }, // org.apache.commons.math.stat.descriptive.moment.Kurtosis { "statistics constructed from external moments cannot be incremented", - "les statistiques bas\u00e9es sur des moments externes ne peuvent pas \u00eatre incr\u00e9ment\u00e9es" }, + "les statistiques bas\u00e9es sur des moments externes " + + "ne peuvent pas \u00eatre incr\u00e9ment\u00e9es" }, { "statistics constructed from external moments cannot be cleared", - "les statistiques bas\u00e9es sur des moments externes ne peuvent pas \u00eatre remises \u00e0 z\u00e9ro" }, + "les statistiques bas\u00e9es sur des moments externes " + + "ne peuvent pas \u00eatre remises \u00e0 z\u00e9ro" }, + + // org.apache.commons.math.stat.Regression + { "out of bounds significance level {0}, must be in (0, 1)", + "niveau de signification {0} hors domaine, doit \u00eatre dans l''intervalle ]0, 1[" }, + + // org.apache.commons.math.distribution.AbstractContinuousDistribution + // org.apache.commons.math.distribution.AbstractIntegerDistribution + // org.apache.commons.math.distribution.ExponentialDistributionImpl + // org.apache.commons.math.distribution.BinomialDistributionImpl + // org.apache.commons.math.distribution.CauchyDistributionImpl + // org.apache.commons.math.distribution.PascalDistributionImpl + // org.apache.commons.math.distribution.WeibullDistributionImpl + { "{0} out of [{1}, {2}] range", + "{0} hors du domaine [{1}, {2}]" }, + + // org.apache.commons.math.distribution.AbstractDistribution + // org.apache.commons.math.distribution.AbstractIntegerDistribution + { "lower endpoint ({0}) must be less than or equal to upper endpoint ({1})", + "la borne inf\u00e9rieure ({0}) devrait \u00eatre inf\u00e9rieure " + + "ou \u00e9gale \u00e0 la borne sup\u00e9rieure ({1})" }, + + // org.apache.commons.math.distribution.BinomialDistributionImpl + { "number of trials must be non-negative ({0})", + "le nombre d''essais ne doit pas \u00eatre n\u00e9gatif ({0})" }, + + // org.apache.commons.math.distribution.ExponentialDistributionImpl + // org.apache.commons.math.random.RandomDataImpl + { "mean must be positive ({0})", + "la moyenne doit \u00eatre positive ({0})" }, + + // org.apache.commons.math.distribution.FDistributionImpl + // org.apache.commons.math.distribution.TDistributionImpl + { "degrees of freedom must be positive ({0})", + "les degr\u00e9s de libert\u00e9 doivent \u00eatre positifs ({0})" }, + + // org.apache.commons.math.distribution.GammaDistributionImpl + { "alpha must be positive ({0})", + "alpha doit \u00eatre positif ({0})" }, + { "beta must be positive ({0})", + "beta doit \u00eatre positif ({0})" }, + + // org.apache.commons.math.distribution.HypergeometricDistributionImpl + { "number of successes ({0}) must be less than or equal to population size ({1})", + "le nombre de succ\u00e8s doit \u00eatre inf\u00e9rieur " + + "ou \u00e9gal \u00e0 la taille de la population ({1})" }, + { "sample size ({0}) must be less than or equal to population size ({1})", + "la taille de l''\u00e9chantillon doit \u00eatre inf\u00e9rieure " + + "ou \u00e9gale \u00e0 la taille de la population ({1})" }, + { "population size must be positive ({0})", + "la taille de la population doit \u00eatre positive ({0})" }, + + // org.apache.commons.math.distribution.HypergeometricDistributionImpl + // org.apache.commons.math.random.RandomDataImpl + { "sample size must be positive ({0})", + "la taille de l''\u00e9chantillon doit \u00eatre positive ({0})" }, + + // org.apache.commons.math.distribution.HypergeometricDistributionImpl + // org.apache.commons.math.distribution.PascalDistributionImpl + { "number of successes must be non-negative ({0})", + "le nombre de succ\u00e8s ne doit pas \u00eatre n\u00e9gatif ({0})" }, + + // org.apache.commons.math.distribution.NormalDistributionImpl + // org.apache.commons.math.random.RandomDataImpl + { "standard deviation must be positive ({0})", + "l''\u00e9cart type doit \u00eatre positif ({0})" }, + + // org.apache.commons.math.distribution.PoissonDistributionImpl + // org.apache.commons.math.random.RandomDataImpl + { "the Poisson mean must be positive ({0})", + "la moyenne de Poisson doit \u00eatre positive ({0})" }, + + // org.apache.commons.math.distribution.WeibullDistributionImpl + { "shape must be positive ({0})", + "le facteur de forme doit \u00eatre positif ({0})" }, + + // org.apache.commons.math.distribution.WeibullDistributionImpl + // org.apache.commons.math.distribution.CauchyDistributionImpl + { "scale must be positive ({0})", + "l''\u00e9chelle doit \u00eatre positive ({0})" }, // org.apache.commons.math.distribution.ZipfDistributionImpl { "invalid number of elements {0} (must be positive)", @@ -550,7 +726,8 @@ public class MessagesResources_fr // org.apache.commons.math.transform.FastFourierTransformer { "cannot compute 0-th root of unity, indefinite result", - "impossible de calculer la racine z\u00e9roi\u00e8me de l''unit\u00e9, r\u00e9sultat ind\u00e9fini" }, + "impossible de calculer la racine z\u00e9roi\u00e8me de l''unit\u00e9, " + + "r\u00e9sultat ind\u00e9fini" }, { "roots of unity have not been computed yet", "les racines de l''unit\u00e9 n''ont pas encore \u00e9t\u00e9 calcul\u00e9es" }, { "out of range root of unity index {0} (must be in [{1};{2}])", diff --git a/src/java/org/apache/commons/math/complex/ComplexFormat.java b/src/java/org/apache/commons/math/complex/ComplexFormat.java index d46f914df..9d30ec6a6 100644 --- a/src/java/org/apache/commons/math/complex/ComplexFormat.java +++ b/src/java/org/apache/commons/math/complex/ComplexFormat.java @@ -192,7 +192,9 @@ public class ComplexFormat extends CompositeFormat { ret = format( new Complex(((Number)obj).doubleValue(), 0.0), toAppendTo, pos); } else { - throw new IllegalArgumentException("Cannot format given Object as a Complex"); + throw MathRuntimeException.createIllegalArgumentException( + "cannot format a {0} instance as a complex number", + obj.getClass().getName()); } return ret; @@ -347,8 +349,8 @@ public class ComplexFormat extends CompositeFormat { */ public void setImaginaryCharacter(String imaginaryCharacter) { if (imaginaryCharacter == null || imaginaryCharacter.length() == 0) { - throw new IllegalArgumentException( - "imaginaryCharacter must be a non-empty string."); + throw MathRuntimeException.createIllegalArgumentException( + "empty string for imaginary character"); } this.imaginaryCharacter = imaginaryCharacter; } @@ -361,8 +363,8 @@ public class ComplexFormat extends CompositeFormat { */ public void setImaginaryFormat(NumberFormat imaginaryFormat) { if (imaginaryFormat == null) { - throw new IllegalArgumentException( - "imaginaryFormat can not be null."); + throw MathRuntimeException.createIllegalArgumentException( + "null imaginary format"); } this.imaginaryFormat = imaginaryFormat; } @@ -375,8 +377,8 @@ public class ComplexFormat extends CompositeFormat { */ public void setRealFormat(NumberFormat realFormat) { if (realFormat == null) { - throw new IllegalArgumentException( - "realFormat can not be null."); + throw MathRuntimeException.createIllegalArgumentException( + "null real format"); } this.realFormat = realFormat; } diff --git a/src/java/org/apache/commons/math/complex/ComplexUtils.java b/src/java/org/apache/commons/math/complex/ComplexUtils.java index 80faa9e05..cc28a2662 100644 --- a/src/java/org/apache/commons/math/complex/ComplexUtils.java +++ b/src/java/org/apache/commons/math/complex/ComplexUtils.java @@ -17,6 +17,8 @@ package org.apache.commons.math.complex; +import org.apache.commons.math.MathRuntimeException; + /** * Static implementations of common * {@link org.apache.commons.math.complex.Complex} utilities functions. @@ -59,8 +61,8 @@ public class ComplexUtils { */ public static Complex polar2Complex(double r, double theta) { if (r < 0) { - throw new IllegalArgumentException - ("Complex modulus must not be negative"); + throw MathRuntimeException.createIllegalArgumentException( + "negative complex module {0}", r); } return new Complex(r * Math.cos(theta), r * Math.sin(theta)); } diff --git a/src/java/org/apache/commons/math/distribution/AbstractContinuousDistribution.java b/src/java/org/apache/commons/math/distribution/AbstractContinuousDistribution.java index 4d32d1fc0..484355d14 100644 --- a/src/java/org/apache/commons/math/distribution/AbstractContinuousDistribution.java +++ b/src/java/org/apache/commons/math/distribution/AbstractContinuousDistribution.java @@ -21,6 +21,7 @@ import java.io.Serializable; import org.apache.commons.math.ConvergenceException; import org.apache.commons.math.FunctionEvaluationException; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.analysis.UnivariateRealFunction; import org.apache.commons.math.analysis.solvers.UnivariateRealSolverUtils; @@ -59,7 +60,8 @@ public abstract class AbstractContinuousDistribution public double inverseCumulativeProbability(final double p) throws MathException { if (p < 0.0 || p > 1.0) { - throw new IllegalArgumentException("p must be between 0.0 and 1.0, inclusive."); + throw MathRuntimeException.createIllegalArgumentException( + "{0} out of [{1}, {2}] range", p, 0.0, 1.0); } // by default, do simple root finding using bracketing and default solver. diff --git a/src/java/org/apache/commons/math/distribution/AbstractDistribution.java b/src/java/org/apache/commons/math/distribution/AbstractDistribution.java index eece53cf5..a695eb338 100644 --- a/src/java/org/apache/commons/math/distribution/AbstractDistribution.java +++ b/src/java/org/apache/commons/math/distribution/AbstractDistribution.java @@ -19,6 +19,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; /** * Base class for probability distributions. @@ -58,8 +59,9 @@ public abstract class AbstractDistribution public double cumulativeProbability(double x0, double x1) throws MathException { if (x0 > x1) { - throw new IllegalArgumentException - ("lower endpoint must be less than or equal to upper endpoint"); + throw MathRuntimeException.createIllegalArgumentException( + "lower endpoint ({0}) must be less than or equal to upper endpoint ({1})", + x0, x1); } return cumulativeProbability(x1) - cumulativeProbability(x0); } diff --git a/src/java/org/apache/commons/math/distribution/AbstractIntegerDistribution.java b/src/java/org/apache/commons/math/distribution/AbstractIntegerDistribution.java index b6fe5f1e2..b6e0d9526 100644 --- a/src/java/org/apache/commons/math/distribution/AbstractIntegerDistribution.java +++ b/src/java/org/apache/commons/math/distribution/AbstractIntegerDistribution.java @@ -19,6 +19,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; /** @@ -77,8 +78,9 @@ public abstract class AbstractIntegerDistribution extends AbstractDistribution public double cumulativeProbability(double x0, double x1) throws MathException { if (x0 > x1) { - throw new IllegalArgumentException - ("lower endpoint must be less than or equal to upper endpoint"); + throw MathRuntimeException.createIllegalArgumentException( + "lower endpoint ({0}) must be less than or equal to upper endpoint ({1})", + x0, x1); } if (Math.floor(x0) < x0) { return cumulativeProbability(((int) Math.floor(x0)) + 1, @@ -134,8 +136,9 @@ public abstract class AbstractIntegerDistribution extends AbstractDistribution */ public double cumulativeProbability(int x0, int x1) throws MathException { if (x0 > x1) { - throw new IllegalArgumentException - ("lower endpoint must be less than or equal to upper endpoint"); + throw MathRuntimeException.createIllegalArgumentException( + "lower endpoint ({0}) must be less than or equal to upper endpoint ({1})", + x0, x1); } return cumulativeProbability(x1) - cumulativeProbability(x0 - 1); } @@ -153,8 +156,8 @@ public abstract class AbstractIntegerDistribution extends AbstractDistribution */ public int inverseCumulativeProbability(final double p) throws MathException{ if (p < 0.0 || p > 1.0) { - throw new IllegalArgumentException( - "p must be between 0 and 1.0 (inclusive)"); + throw MathRuntimeException.createIllegalArgumentException( + "{0} out of [{1}, {2}] range", p, 0.0, 1.0); } // by default, do simple bisection. diff --git a/src/java/org/apache/commons/math/distribution/BinomialDistributionImpl.java b/src/java/org/apache/commons/math/distribution/BinomialDistributionImpl.java index 685151eae..b9cb396e6 100644 --- a/src/java/org/apache/commons/math/distribution/BinomialDistributionImpl.java +++ b/src/java/org/apache/commons/math/distribution/BinomialDistributionImpl.java @@ -19,6 +19,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.special.Beta; import org.apache.commons.math.util.MathUtils; @@ -76,7 +77,8 @@ public class BinomialDistributionImpl */ public void setNumberOfTrials(int trials) { if (trials < 0) { - throw new IllegalArgumentException("number of trials must be non-negative."); + throw MathRuntimeException.createIllegalArgumentException( + "number of trials must be non-negative ({0})", trials); } numberOfTrials = trials; } @@ -89,7 +91,8 @@ public class BinomialDistributionImpl */ public void setProbabilityOfSuccess(double p) { if (p < 0.0 || p > 1.0) { - throw new IllegalArgumentException("probability of success must be between 0.0 and 1.0, inclusive."); + throw MathRuntimeException.createIllegalArgumentException( + "{0} out of [{1}, {2}] range", p, 0.0, 1.0); } probabilityOfSuccess = p; } diff --git a/src/java/org/apache/commons/math/distribution/CauchyDistributionImpl.java b/src/java/org/apache/commons/math/distribution/CauchyDistributionImpl.java index 23847a23b..0ce9acfad 100644 --- a/src/java/org/apache/commons/math/distribution/CauchyDistributionImpl.java +++ b/src/java/org/apache/commons/math/distribution/CauchyDistributionImpl.java @@ -19,6 +19,8 @@ package org.apache.commons.math.distribution; import java.io.Serializable; +import org.apache.commons.math.MathRuntimeException; + /** * Default implementation of * {@link org.apache.commons.math.distribution.CauchyDistribution}. @@ -98,8 +100,8 @@ public class CauchyDistributionImpl extends AbstractContinuousDistribution public double inverseCumulativeProbability(double p) { double ret; if (p < 0.0 || p > 1.0) { - throw new IllegalArgumentException - ("probability argument must be between 0 and 1 (inclusive)"); + throw MathRuntimeException.createIllegalArgumentException( + "{0} out of [{1}, {2}] range", p, 0.0, 1.0); } else if (p == 0) { ret = Double.NEGATIVE_INFINITY; } else if (p == 1) { @@ -125,8 +127,8 @@ public class CauchyDistributionImpl extends AbstractContinuousDistribution */ public void setScale(double s) { if (s <= 0.0) { - throw new IllegalArgumentException( - "Scale must be positive."); + throw MathRuntimeException.createIllegalArgumentException( + "scale must be positive ({0})", s); } scale = s; } diff --git a/src/java/org/apache/commons/math/distribution/ExponentialDistributionImpl.java b/src/java/org/apache/commons/math/distribution/ExponentialDistributionImpl.java index 79529f918..0f29b7a5d 100644 --- a/src/java/org/apache/commons/math/distribution/ExponentialDistributionImpl.java +++ b/src/java/org/apache/commons/math/distribution/ExponentialDistributionImpl.java @@ -19,6 +19,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; /** * The default implementation of {@link ExponentialDistribution}. @@ -50,7 +51,8 @@ public class ExponentialDistributionImpl extends AbstractContinuousDistribution */ public void setMean(double mean) { if (mean <= 0.0) { - throw new IllegalArgumentException("mean must be positive."); + throw MathRuntimeException.createIllegalArgumentException( + "mean must be positive ({0})", mean); } this.mean = mean; } @@ -118,8 +120,8 @@ public class ExponentialDistributionImpl extends AbstractContinuousDistribution double ret; if (p < 0.0 || p > 1.0) { - throw new IllegalArgumentException - ("probability argument must be between 0 and 1 (inclusive)"); + throw MathRuntimeException.createIllegalArgumentException( + "{0} out of [{1}, {2}] range", p, 0.0, 1.0); } else if (p == 1.0) { ret = Double.POSITIVE_INFINITY; } else { diff --git a/src/java/org/apache/commons/math/distribution/FDistributionImpl.java b/src/java/org/apache/commons/math/distribution/FDistributionImpl.java index 02fe62bbd..10da08846 100644 --- a/src/java/org/apache/commons/math/distribution/FDistributionImpl.java +++ b/src/java/org/apache/commons/math/distribution/FDistributionImpl.java @@ -19,6 +19,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.special.Beta; /** @@ -162,8 +163,9 @@ public class FDistributionImpl */ public void setNumeratorDegreesOfFreedom(double degreesOfFreedom) { if (degreesOfFreedom <= 0.0) { - throw new IllegalArgumentException( - "degrees of freedom must be positive."); + throw MathRuntimeException.createIllegalArgumentException( + "degrees of freedom must be positive ({0})", + degreesOfFreedom); } this.numeratorDegreesOfFreedom = degreesOfFreedom; } @@ -184,8 +186,9 @@ public class FDistributionImpl */ public void setDenominatorDegreesOfFreedom(double degreesOfFreedom) { if (degreesOfFreedom <= 0.0) { - throw new IllegalArgumentException( - "degrees of freedom must be positive."); + throw MathRuntimeException.createIllegalArgumentException( + "degrees of freedom must be positive ({0})", + degreesOfFreedom); } this.denominatorDegreesOfFreedom = degreesOfFreedom; } diff --git a/src/java/org/apache/commons/math/distribution/GammaDistributionImpl.java b/src/java/org/apache/commons/math/distribution/GammaDistributionImpl.java index 8bd4e2c76..e1ab2e103 100644 --- a/src/java/org/apache/commons/math/distribution/GammaDistributionImpl.java +++ b/src/java/org/apache/commons/math/distribution/GammaDistributionImpl.java @@ -19,6 +19,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.special.Gamma; /** @@ -110,7 +111,9 @@ public class GammaDistributionImpl extends AbstractContinuousDistribution */ public void setAlpha(double alpha) { if (alpha <= 0.0) { - throw new IllegalArgumentException("alpha must be positive"); + throw MathRuntimeException.createIllegalArgumentException( + "alpha must be positive ({0})", + alpha); } this.alpha = alpha; } @@ -130,7 +133,9 @@ public class GammaDistributionImpl extends AbstractContinuousDistribution */ public void setBeta(double beta) { if (beta <= 0.0) { - throw new IllegalArgumentException("beta must be positive"); + throw MathRuntimeException.createIllegalArgumentException( + "beta must be positive ({0})", + beta); } this.beta = beta; } diff --git a/src/java/org/apache/commons/math/distribution/HypergeometricDistributionImpl.java b/src/java/org/apache/commons/math/distribution/HypergeometricDistributionImpl.java index 6e3d98401..c6f5e91c3 100644 --- a/src/java/org/apache/commons/math/distribution/HypergeometricDistributionImpl.java +++ b/src/java/org/apache/commons/math/distribution/HypergeometricDistributionImpl.java @@ -19,6 +19,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.util.MathUtils; /** @@ -53,13 +54,14 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution int numberOfSuccesses, int sampleSize) { super(); if (numberOfSuccesses > populationSize) { - throw new IllegalArgumentException( - "number of successes must be less than or equal to " + - "population size"); + throw MathRuntimeException.createIllegalArgumentException( + "number of successes ({0}) must be less than or equal to population size ({1})", + numberOfSuccesses, populationSize); } if (sampleSize > populationSize) { - throw new IllegalArgumentException( - "sample size must be less than or equal to population size"); + throw MathRuntimeException.createIllegalArgumentException( + "sample size ({0}) must be less than or equal to population size ({1})", + sampleSize, populationSize); } setPopulationSize(populationSize); setSampleSize(sampleSize); @@ -226,8 +228,9 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution */ public void setNumberOfSuccesses(int num) { if(num < 0){ - throw new IllegalArgumentException( - "number of successes must be non-negative."); + throw MathRuntimeException.createIllegalArgumentException( + "number of successes must be non-negative ({0})", + num); } numberOfSuccesses = num; } @@ -239,8 +242,9 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution */ public void setPopulationSize(int size) { if(size <= 0){ - throw new IllegalArgumentException( - "population size must be positive."); + throw MathRuntimeException.createIllegalArgumentException( + "population size must be positive ({0})", + size); } populationSize = size; } @@ -252,8 +256,9 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution */ public void setSampleSize(int size) { if (size < 0) { - throw new IllegalArgumentException( - "sample size must be non-negative."); + throw MathRuntimeException.createIllegalArgumentException( + "sample size must be positive ({0})", + size); } sampleSize = size; } diff --git a/src/java/org/apache/commons/math/distribution/NormalDistributionImpl.java b/src/java/org/apache/commons/math/distribution/NormalDistributionImpl.java index e386a195f..19ad7662f 100644 --- a/src/java/org/apache/commons/math/distribution/NormalDistributionImpl.java +++ b/src/java/org/apache/commons/math/distribution/NormalDistributionImpl.java @@ -20,6 +20,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.MaxIterationsExceededException; import org.apache.commons.math.special.Erf; @@ -94,8 +95,9 @@ public class NormalDistributionImpl extends AbstractContinuousDistribution */ public void setStandardDeviation(double sd) { if (sd <= 0.0) { - throw new IllegalArgumentException( - "Standard deviation must be positive."); + throw MathRuntimeException.createIllegalArgumentException( + "standard deviation must be positive ({0})", + sd); } standardDeviation = sd; } diff --git a/src/java/org/apache/commons/math/distribution/PascalDistributionImpl.java b/src/java/org/apache/commons/math/distribution/PascalDistributionImpl.java index 9cb63831f..5a632b0db 100644 --- a/src/java/org/apache/commons/math/distribution/PascalDistributionImpl.java +++ b/src/java/org/apache/commons/math/distribution/PascalDistributionImpl.java @@ -19,6 +19,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.special.Beta; import org.apache.commons.math.util.MathUtils; @@ -75,8 +76,9 @@ public class PascalDistributionImpl extends AbstractIntegerDistribution */ public void setNumberOfSuccesses(int successes) { if (successes < 0) { - throw new IllegalArgumentException( - "number of successes must be non-negative."); + throw MathRuntimeException.createIllegalArgumentException( + "number of successes must be non-negative ({0})", + successes); } numberOfSuccesses = successes; } @@ -89,8 +91,8 @@ public class PascalDistributionImpl extends AbstractIntegerDistribution */ public void setProbabilityOfSuccess(double p) { if (p < 0.0 || p > 1.0) { - throw new IllegalArgumentException( - "probability of success must be between 0.0 and 1.0, inclusive."); + throw MathRuntimeException.createIllegalArgumentException( + "{0} out of [{1}, {2}] range", p, 0.0, 1.0); } probabilityOfSuccess = p; } diff --git a/src/java/org/apache/commons/math/distribution/PoissonDistributionImpl.java b/src/java/org/apache/commons/math/distribution/PoissonDistributionImpl.java index 2cb5e4828..a9e55b95e 100644 --- a/src/java/org/apache/commons/math/distribution/PoissonDistributionImpl.java +++ b/src/java/org/apache/commons/math/distribution/PoissonDistributionImpl.java @@ -19,6 +19,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.special.Gamma; import org.apache.commons.math.util.MathUtils; @@ -88,8 +89,9 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution */ public void setMean(double p) { if (p <= 0) { - throw new IllegalArgumentException( - "The Poisson mean must be positive"); + throw MathRuntimeException.createIllegalArgumentException( + "the Poisson mean must be positive ({0})", + p); } this.mean = p; normal.setMean(p); diff --git a/src/java/org/apache/commons/math/distribution/TDistributionImpl.java b/src/java/org/apache/commons/math/distribution/TDistributionImpl.java index dfe1698b5..4af2261a5 100644 --- a/src/java/org/apache/commons/math/distribution/TDistributionImpl.java +++ b/src/java/org/apache/commons/math/distribution/TDistributionImpl.java @@ -19,6 +19,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.special.Beta; /** @@ -52,7 +53,9 @@ public class TDistributionImpl */ public void setDegreesOfFreedom(double degreesOfFreedom) { if (degreesOfFreedom <= 0.0) { - throw new IllegalArgumentException("degrees of freedom must be positive."); + throw MathRuntimeException.createIllegalArgumentException( + "degrees of freedom must be positive ({0})", + degreesOfFreedom); } this.degreesOfFreedom = degreesOfFreedom; } diff --git a/src/java/org/apache/commons/math/distribution/WeibullDistributionImpl.java b/src/java/org/apache/commons/math/distribution/WeibullDistributionImpl.java index 1aa1383a5..37a8d9daf 100644 --- a/src/java/org/apache/commons/math/distribution/WeibullDistributionImpl.java +++ b/src/java/org/apache/commons/math/distribution/WeibullDistributionImpl.java @@ -19,6 +19,8 @@ package org.apache.commons.math.distribution; import java.io.Serializable; +import org.apache.commons.math.MathRuntimeException; + /** * Default implementation of * {@link org.apache.commons.math.distribution.WeibullDistribution}. @@ -97,8 +99,8 @@ public class WeibullDistributionImpl extends AbstractContinuousDistribution public double inverseCumulativeProbability(double p) { double ret; if (p < 0.0 || p > 1.0) { - throw new IllegalArgumentException - ("probability argument must be between 0 and 1 (inclusive)"); + throw MathRuntimeException.createIllegalArgumentException( + "{0} out of [{1}, {2}] range", p, 0.0, 1.0); } else if (p == 0) { ret = 0.0; } else if (p == 1) { @@ -115,8 +117,9 @@ public class WeibullDistributionImpl extends AbstractContinuousDistribution */ public void setShape(double alpha) { if (alpha <= 0.0) { - throw new IllegalArgumentException( - "Shape must be positive."); + throw MathRuntimeException.createIllegalArgumentException( + "shape must be positive ({0})", + alpha); } this.alpha = alpha; } @@ -127,8 +130,9 @@ public class WeibullDistributionImpl extends AbstractContinuousDistribution */ public void setScale(double beta) { if (beta <= 0.0) { - throw new IllegalArgumentException( - "Scale must be positive."); + throw MathRuntimeException.createIllegalArgumentException( + "scale must be positive ({0})", + beta); } this.beta = beta; } diff --git a/src/java/org/apache/commons/math/fraction/Fraction.java b/src/java/org/apache/commons/math/fraction/Fraction.java index 1177ec30b..463b3e889 100644 --- a/src/java/org/apache/commons/math/fraction/Fraction.java +++ b/src/java/org/apache/commons/math/fraction/Fraction.java @@ -476,7 +476,7 @@ public class Fraction extends Number implements FieldElement, Comparab */ private Fraction addSub(Fraction fraction, boolean isAdd) { if (fraction == null) { - throw new IllegalArgumentException("The fraction must not be null"); + throw MathRuntimeException.createIllegalArgumentException("null fraction"); } // zero is identity for addition. if (numerator == 0) { @@ -533,7 +533,7 @@ public class Fraction extends Number implements FieldElement, Comparab */ public Fraction multiply(Fraction fraction) { if (fraction == null) { - throw new IllegalArgumentException("The fraction must not be null"); + throw MathRuntimeException.createIllegalArgumentException("null fraction"); } if (numerator == 0 || fraction.numerator == 0) { return ZERO; @@ -568,7 +568,7 @@ public class Fraction extends Number implements FieldElement, Comparab */ public Fraction divide(Fraction fraction) { if (fraction == null) { - throw new IllegalArgumentException("The fraction must not be null"); + throw MathRuntimeException.createIllegalArgumentException("null fraction"); } if (fraction.numerator == 0) { throw MathRuntimeException.createArithmeticException( diff --git a/src/java/org/apache/commons/math/geometry/Rotation.java b/src/java/org/apache/commons/math/geometry/Rotation.java index 2819006c4..bf62cca37 100644 --- a/src/java/org/apache/commons/math/geometry/Rotation.java +++ b/src/java/org/apache/commons/math/geometry/Rotation.java @@ -300,7 +300,7 @@ public class Rotation implements Serializable { double v1v1 = Vector3D.dotProduct(v1, v1); double v2v2 = Vector3D.dotProduct(v2, v2); if ((u1u1 == 0) || (u2u2 == 0) || (v1v1 == 0) || (v2v2 == 0)) { - throw new IllegalArgumentException("zero norm for rotation defining vector"); + throw MathRuntimeException.createIllegalArgumentException("zero norm for rotation defining vector"); } double u1x = u1.getX(); @@ -431,7 +431,7 @@ public class Rotation implements Serializable { double normProduct = u.getNorm() * v.getNorm(); if (normProduct == 0) { - throw new IllegalArgumentException("zero norm for rotation defining vector"); + throw MathRuntimeException.createIllegalArgumentException("zero norm for rotation defining vector"); } double dot = Vector3D.dotProduct(u, v); diff --git a/src/java/org/apache/commons/math/geometry/Vector3DFormat.java b/src/java/org/apache/commons/math/geometry/Vector3DFormat.java index ccdb1a68e..e3e21dd26 100644 --- a/src/java/org/apache/commons/math/geometry/Vector3DFormat.java +++ b/src/java/org/apache/commons/math/geometry/Vector3DFormat.java @@ -241,7 +241,8 @@ public class Vector3DFormat extends CompositeFormat { return format( (Vector3D)obj, toAppendTo, pos); } - throw new IllegalArgumentException("Cannot format given Object as a Vector3D"); + throw MathRuntimeException.createIllegalArgumentException("cannot format a {0} instance as a 3D vector", + obj.getClass().getName()); } diff --git a/src/java/org/apache/commons/math/linear/AbstractRealMatrix.java b/src/java/org/apache/commons/math/linear/AbstractRealMatrix.java index 6f8fd9668..fd54813a0 100644 --- a/src/java/org/apache/commons/math/linear/AbstractRealMatrix.java +++ b/src/java/org/apache/commons/math/linear/AbstractRealMatrix.java @@ -85,7 +85,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public RealMatrix add(RealMatrix m) throws IllegalArgumentException { // safety check - checkAdditionCompatible(m); + MatrixUtils.checkAdditionCompatible(this, m); final int rowCount = getRowDimension(); final int columnCount = getColumnDimension(); @@ -104,7 +104,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public RealMatrix subtract(final RealMatrix m) throws IllegalArgumentException { // safety check - checkSubtractionCompatible(m); + MatrixUtils.checkSubtractionCompatible(this, m); final int rowCount = getRowDimension(); final int columnCount = getColumnDimension(); @@ -156,7 +156,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { throws IllegalArgumentException { // safety check - checkMultiplicationCompatible(m); + MatrixUtils.checkMultiplicationCompatible(this, m); final int nRows = getRowDimension(); final int nCols = m.getColumnDimension(); @@ -275,7 +275,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { final int startColumn, final int endColumn) throws MatrixIndexException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); final RealMatrix subMatrix = createMatrix(endRow - startRow + 1, endColumn - startColumn + 1); @@ -294,7 +294,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { throws MatrixIndexException { // safety checks - checkSubMatrixIndex(selectedRows, selectedColumns); + MatrixUtils.checkSubMatrixIndex(this, selectedRows, selectedColumns); // copy entries final RealMatrix subMatrix = @@ -323,7 +323,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { throws MatrixIndexException, IllegalArgumentException { // safety checks - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); final int rowsCount = endRow + 1 - startRow; final int columnsCount = endColumn + 1 - startColumn; if ((destination.length < rowsCount) || (destination[0].length < columnsCount)) { @@ -369,7 +369,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { throws MatrixIndexException, IllegalArgumentException { // safety checks - checkSubMatrixIndex(selectedRows, selectedColumns); + MatrixUtils.checkSubMatrixIndex(this, selectedRows, selectedColumns); if ((destination.length < selectedRows.length) || (destination[0].length < selectedColumns.length)) { throw MathRuntimeException.createIllegalArgumentException( @@ -410,10 +410,10 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { } } - checkRowIndex(row); - checkColumnIndex(column); - checkRowIndex(nRows + row - 1); - checkColumnIndex(nCols + column - 1); + MatrixUtils.checkRowIndex(this, row); + MatrixUtils.checkColumnIndex(this, column); + MatrixUtils.checkRowIndex(this, nRows + row - 1); + MatrixUtils.checkColumnIndex(this, nCols + column - 1); for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols; ++j) { @@ -429,7 +429,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public RealMatrix getRowMatrix(final int row) throws MatrixIndexException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final int nCols = getColumnDimension(); final RealMatrix out = createMatrix(1, nCols); for (int i = 0; i < nCols; ++i) { @@ -444,7 +444,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public void setRowMatrix(final int row, final RealMatrix matrix) throws MatrixIndexException, InvalidMatrixException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final int nCols = getColumnDimension(); if ((matrix.getRowDimension() != 1) || (matrix.getColumnDimension() != nCols)) { @@ -462,7 +462,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public RealMatrix getColumnMatrix(final int column) throws MatrixIndexException { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); final int nRows = getRowDimension(); final RealMatrix out = createMatrix(nRows, 1); for (int i = 0; i < nRows; ++i) { @@ -477,7 +477,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public void setColumnMatrix(final int column, final RealMatrix matrix) throws MatrixIndexException, InvalidMatrixException { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); final int nRows = getRowDimension(); if ((matrix.getRowDimension() != nRows) || (matrix.getColumnDimension() != 1)) { @@ -501,7 +501,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public void setRowVector(final int row, final RealVector vector) throws MatrixIndexException, InvalidMatrixException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final int nCols = getColumnDimension(); if (vector.getDimension() != nCols) { throw new InvalidMatrixException( @@ -524,7 +524,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public void setColumnVector(final int column, final RealVector vector) throws MatrixIndexException, InvalidMatrixException { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); final int nRows = getRowDimension(); if (vector.getDimension() != nRows) { throw new InvalidMatrixException( @@ -541,7 +541,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public double[] getRow(final int row) throws MatrixIndexException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final int nCols = getColumnDimension(); final double[] out = new double[nCols]; for (int i = 0; i < nCols; ++i) { @@ -556,7 +556,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public void setRow(final int row, final double[] array) throws MatrixIndexException, InvalidMatrixException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final int nCols = getColumnDimension(); if (array.length != nCols) { throw new InvalidMatrixException( @@ -573,7 +573,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public double[] getColumn(final int column) throws MatrixIndexException { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); final int nRows = getRowDimension(); final double[] out = new double[nRows]; for (int i = 0; i < nRows; ++i) { @@ -588,7 +588,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { public void setColumn(final int column, final double[] array) throws MatrixIndexException, InvalidMatrixException { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); final int nRows = getRowDimension(); if (array.length != nRows) { throw new InvalidMatrixException( @@ -834,7 +834,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(getRowDimension(), getColumnDimension(), startRow, endRow, startColumn, endColumn); for (int row = startRow; row <= endRow; ++row) { @@ -853,7 +853,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(getRowDimension(), getColumnDimension(), startRow, endRow, startColumn, endColumn); for (int row = startRow; row <= endRow; ++row) { @@ -900,7 +900,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(getRowDimension(), getColumnDimension(), startRow, endRow, startColumn, endColumn); for (int column = startColumn; column <= endColumn; ++column) { @@ -919,7 +919,7 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(getRowDimension(), getColumnDimension(), startRow, endRow, startColumn, endColumn); for (int column = startColumn; column <= endColumn; ++column) { @@ -1090,126 +1090,4 @@ public abstract class AbstractRealMatrix implements RealMatrix, Serializable { return ret; } - /** - * Check if a row index is valid. - * @param row row index to check - * @exception MatrixIndexException if index is not valid - */ - protected void checkRowIndex(final int row) { - if (row < 0 || row >= getRowDimension()) { - throw new MatrixIndexException("row index {0} out of allowed range [{1}, {2}]", - row, 0, getRowDimension() - 1); - } - } - - /** - * Check if a column index is valid. - * @param column column index to check - * @exception MatrixIndexException if index is not valid - */ - protected void checkColumnIndex(final int column) - throws MatrixIndexException { - if (column < 0 || column >= getColumnDimension()) { - throw new MatrixIndexException("column index {0} out of allowed range [{1}, {2}]", - column, 0, getColumnDimension() - 1); - } - } - - /** - * Check if submatrix ranges indices are valid. - * Rows and columns are indicated counting from 0 to n-1. - * - * @param startRow Initial row index - * @param endRow Final row index - * @param startColumn Initial column index - * @param endColumn Final column index - * @exception MatrixIndexException if the indices are not valid - */ - protected void checkSubMatrixIndex(final int startRow, final int endRow, - final int startColumn, final int endColumn) { - checkRowIndex(startRow); - checkRowIndex(endRow); - if (startRow > endRow) { - throw new MatrixIndexException("initial row {0} after final row {1}", - startRow, endRow); - } - - checkColumnIndex(startColumn); - checkColumnIndex(endColumn); - if (startColumn > endColumn) { - throw new MatrixIndexException("initial column {0} after final column {1}", - startColumn, endColumn); - } - - - } - - /** - * Check if submatrix ranges indices are valid. - * Rows and columns are indicated counting from 0 to n-1. - * - * @param selectedRows Array of row indices. - * @param selectedColumns Array of column indices. - * @exception MatrixIndexException if row or column selections are not valid - */ - protected void checkSubMatrixIndex(final int[] selectedRows, final int[] selectedColumns) { - if (selectedRows.length * selectedColumns.length == 0) { - if (selectedRows.length == 0) { - throw new MatrixIndexException("empty selected row index array"); - } - throw new MatrixIndexException("empty selected column index array"); - } - - for (final int row : selectedRows) { - checkRowIndex(row); - } - for (final int column : selectedColumns) { - checkColumnIndex(column); - } - } - - /** - * Check if a matrix is addition compatible with the instance - * @param m matrix to check - * @exception IllegalArgumentException if matrix is not addition compatible with instance - */ - protected void checkAdditionCompatible(final RealMatrix m) { - if ((getRowDimension() != m.getRowDimension()) || - (getColumnDimension() != m.getColumnDimension())) { - throw MathRuntimeException.createIllegalArgumentException( - "{0}x{1} and {2}x{3} matrices are not addition compatible", - getRowDimension(), getColumnDimension(), - m.getRowDimension(), m.getColumnDimension()); - } - } - - /** - * Check if a matrix is subtraction compatible with the instance - * @param m matrix to check - * @exception IllegalArgumentException if matrix is not subtraction compatible with instance - */ - protected void checkSubtractionCompatible(final RealMatrix m) { - if ((getRowDimension() != m.getRowDimension()) || - (getColumnDimension() != m.getColumnDimension())) { - throw MathRuntimeException.createIllegalArgumentException( - "{0}x{1} and {2}x{3} matrices are not subtraction compatible", - getRowDimension(), getColumnDimension(), - m.getRowDimension(), m.getColumnDimension()); - } - } - - /** - * Check if a matrix is multiplication compatible with the instance - * @param m matrix to check - * @exception IllegalArgumentException if matrix is not multiplication compatible with instance - */ - protected void checkMultiplicationCompatible(final RealMatrix m) { - if (getColumnDimension() != m.getRowDimension()) { - throw MathRuntimeException.createIllegalArgumentException( - "{0}x{1} and {2}x{3} matrices are not multiplication compatible", - getRowDimension(), getColumnDimension(), - m.getRowDimension(), m.getColumnDimension()); - } - } - } diff --git a/src/java/org/apache/commons/math/linear/AnyMatrix.java b/src/java/org/apache/commons/math/linear/AnyMatrix.java new file mode 100644 index 000000000..6626e8fe8 --- /dev/null +++ b/src/java/org/apache/commons/math/linear/AnyMatrix.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.math.linear; + + +/** + * Interface defining very basic matrix operations. + * @version $Revision$ $Date$ + * @since 2.0 + */ +public interface AnyMatrix { + + /** + * Is this a square matrix? + * @return true if the matrix is square (rowDimension = columnDimension) + */ + boolean isSquare(); + + /** + * Returns the number of rows in the matrix. + * + * @return rowDimension + */ + int getRowDimension(); + + /** + * Returns the number of columns in the matrix. + * + * @return columnDimension + */ + int getColumnDimension(); + +} diff --git a/src/java/org/apache/commons/math/linear/BigMatrix.java b/src/java/org/apache/commons/math/linear/BigMatrix.java index 14a37d9c0..4d89e2185 100644 --- a/src/java/org/apache/commons/math/linear/BigMatrix.java +++ b/src/java/org/apache/commons/math/linear/BigMatrix.java @@ -31,7 +31,7 @@ import java.math.BigDecimal; * org.apache.commons.math.util.BigReal} parameter */ @Deprecated -public interface BigMatrix { +public interface BigMatrix extends AnyMatrix { /** * Returns a (deep) copy of this. @@ -278,32 +278,6 @@ public interface BigMatrix { */ BigDecimal getDeterminant() throws InvalidMatrixException; - /** - * Is this a square matrix? - * @return true if the matrix is square (rowDimension = columnDimension) - */ - boolean isSquare(); - - /** - * Is this a singular matrix? - * @return true if the matrix is singular - */ - boolean isSingular(); - - /** - * Returns the number of rows in the matrix. - * - * @return rowDimension - */ - int getRowDimension(); - - /** - * Returns the number of columns in the matrix. - * - * @return columnDimension - */ - int getColumnDimension(); - /** * Returns the * trace of the matrix (the sum of the elements on the main diagonal). diff --git a/src/java/org/apache/commons/math/linear/BigMatrixImpl.java b/src/java/org/apache/commons/math/linear/BigMatrixImpl.java index c34c72778..3ac8f5682 100644 --- a/src/java/org/apache/commons/math/linear/BigMatrixImpl.java +++ b/src/java/org/apache/commons/math/linear/BigMatrixImpl.java @@ -102,9 +102,15 @@ public class BigMatrixImpl implements BigMatrix, Serializable { * positive */ public BigMatrixImpl(int rowDimension, int columnDimension) { - if (rowDimension <=0 || columnDimension <=0) { - throw new IllegalArgumentException - ("row and column dimensions must be positive"); + if (rowDimension <= 0 ) { + throw MathRuntimeException.createIllegalArgumentException( + "invalid row dimension {0} (must be positive)", + rowDimension); + } + if (columnDimension <= 0) { + throw MathRuntimeException.createIllegalArgumentException( + "invalid column dimension {0} (must be positive)", + columnDimension); } data = new BigDecimal[rowDimension][columnDimension]; lu = null; @@ -151,15 +157,18 @@ public class BigMatrixImpl implements BigMatrix, Serializable { } final int nRows = d.length; if (nRows == 0) { - throw new IllegalArgumentException("Matrix must have at least one row."); + throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one row"); } + final int nCols = d[0].length; if (nCols == 0) { - throw new IllegalArgumentException("Matrix must have at least one column."); + throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one column"); } for (int r = 1; r < nRows; r++) { if (d[r].length != nCols) { - throw new IllegalArgumentException("All input rows must have the same length."); + throw MathRuntimeException.createIllegalArgumentException( + "some rows have length {0} while others have length {1}", + nCols, d[r].length); } } data = d; @@ -181,18 +190,18 @@ public class BigMatrixImpl implements BigMatrix, Serializable { public BigMatrixImpl(double[][] d) { final int nRows = d.length; if (nRows == 0) { - throw new IllegalArgumentException( - "Matrix must have at least one row."); + throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one row"); } + final int nCols = d[0].length; if (nCols == 0) { - throw new IllegalArgumentException( - "Matrix must have at least one column."); + throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one column"); } for (int row = 1; row < nRows; row++) { if (d[row].length != nCols) { - throw new IllegalArgumentException( - "All input rows must have the same length."); + throw MathRuntimeException.createIllegalArgumentException( + "some rows have length {0} while others have length {1}", + nCols, d[row].length); } } this.copyIn(d); @@ -211,18 +220,18 @@ public class BigMatrixImpl implements BigMatrix, Serializable { public BigMatrixImpl(String[][] d) { final int nRows = d.length; if (nRows == 0) { - throw new IllegalArgumentException( - "Matrix must have at least one row."); + throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one row"); } + final int nCols = d[0].length; if (nCols == 0) { - throw new IllegalArgumentException( - "Matrix must have at least one column."); + throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one column"); } for (int row = 1; row < nRows; row++) { if (d[row].length != nCols) { - throw new IllegalArgumentException( - "All input rows must have the same length."); + throw MathRuntimeException.createIllegalArgumentException( + "some rows have length {0} while others have length {1}", + nCols, d[row].length); } } this.copyIn(d); @@ -266,11 +275,12 @@ public class BigMatrixImpl implements BigMatrix, Serializable { try { return add((BigMatrixImpl) m); } catch (ClassCastException cce) { + + // safety check + MatrixUtils.checkAdditionCompatible(this, m); + final int rowCount = getRowDimension(); final int columnCount = getColumnDimension(); - if (columnCount != m.getColumnDimension() || rowCount != m.getRowDimension()) { - throw new IllegalArgumentException("matrix dimension mismatch"); - } final BigDecimal[][] outData = new BigDecimal[rowCount][columnCount]; for (int row = 0; row < rowCount; row++) { final BigDecimal[] dataRow = data[row]; @@ -291,11 +301,12 @@ public class BigMatrixImpl implements BigMatrix, Serializable { * @throws IllegalArgumentException if m is not the same size as this */ public BigMatrixImpl add(BigMatrixImpl m) throws IllegalArgumentException { + + // safety check + MatrixUtils.checkAdditionCompatible(this, m); + final int rowCount = getRowDimension(); final int columnCount = getColumnDimension(); - if (columnCount != m.getColumnDimension() || rowCount != m.getRowDimension()) { - throw new IllegalArgumentException("matrix dimension mismatch"); - } final BigDecimal[][] outData = new BigDecimal[rowCount][columnCount]; for (int row = 0; row < rowCount; row++) { final BigDecimal[] dataRow = data[row]; @@ -319,11 +330,12 @@ public class BigMatrixImpl implements BigMatrix, Serializable { try { return subtract((BigMatrixImpl) m); } catch (ClassCastException cce) { + + // safety check + MatrixUtils.checkSubtractionCompatible(this, m); + final int rowCount = getRowDimension(); final int columnCount = getColumnDimension(); - if (columnCount != m.getColumnDimension() || rowCount != m.getRowDimension()) { - throw new IllegalArgumentException("matrix dimension mismatch"); - } final BigDecimal[][] outData = new BigDecimal[rowCount][columnCount]; for (int row = 0; row < rowCount; row++) { final BigDecimal[] dataRow = data[row]; @@ -344,11 +356,12 @@ public class BigMatrixImpl implements BigMatrix, Serializable { * @throws IllegalArgumentException if m is not the same size as this */ public BigMatrixImpl subtract(BigMatrixImpl m) throws IllegalArgumentException { + + // safety check + MatrixUtils.checkSubtractionCompatible(this, m); + final int rowCount = getRowDimension(); final int columnCount = getColumnDimension(); - if (columnCount != m.getColumnDimension() || rowCount != m.getRowDimension()) { - throw new IllegalArgumentException("matrix dimension mismatch"); - } final BigDecimal[][] outData = new BigDecimal[rowCount][columnCount]; for (int row = 0; row < rowCount; row++) { final BigDecimal[] dataRow = data[row]; @@ -411,9 +424,10 @@ public class BigMatrixImpl implements BigMatrix, Serializable { try { return multiply((BigMatrixImpl) m); } catch (ClassCastException cce) { - if (this.getColumnDimension() != m.getRowDimension()) { - throw new IllegalArgumentException("Matrices are not multiplication compatible."); - } + + // safety check + MatrixUtils.checkMultiplicationCompatible(this, m); + final int nRows = this.getRowDimension(); final int nCols = m.getColumnDimension(); final int nSum = this.getColumnDimension(); @@ -441,9 +455,10 @@ public class BigMatrixImpl implements BigMatrix, Serializable { * if columnDimension(this) != rowDimension(m) */ public BigMatrixImpl multiply(BigMatrixImpl m) throws IllegalArgumentException { - if (this.getColumnDimension() != m.getRowDimension()) { - throw new IllegalArgumentException("Matrices are not multiplication compatible."); - } + + // safety check + MatrixUtils.checkMultiplicationCompatible(this, m); + final int nRows = this.getRowDimension(); final int nCols = m.getColumnDimension(); final int nSum = this.getColumnDimension(); @@ -587,15 +602,15 @@ public class BigMatrixImpl implements BigMatrix, Serializable { int startColumn, int endColumn) throws MatrixIndexException { - checkRowIndex(startRow); - checkRowIndex(endRow); + MatrixUtils.checkRowIndex(this, startRow); + MatrixUtils.checkRowIndex(this, endRow); if (startRow > endRow) { throw new MatrixIndexException("initial row {0} after final row {1}", startRow, endRow); } - checkColumnIndex(startColumn); - checkColumnIndex(endColumn); + MatrixUtils.checkColumnIndex(this, startColumn); + MatrixUtils.checkColumnIndex(this, endColumn); if (startColumn > endColumn) { throw new MatrixIndexException("initial column {0} after final column {1}", startColumn, endColumn); @@ -648,10 +663,10 @@ public class BigMatrixImpl implements BigMatrix, Serializable { // we redo the loop with checks enabled // in order to generate an appropriate message for (final int row : selectedRows) { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); } for (final int column : selectedColumns) { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); } } return new BigMatrixImpl(subMatrixData, false); @@ -688,18 +703,20 @@ public class BigMatrixImpl implements BigMatrix, Serializable { throws MatrixIndexException { final int nRows = subMatrix.length; - final int nCols = subMatrix[0].length; - if (nRows == 0) { - throw new IllegalArgumentException("Matrix must have at least one row."); + throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one row"); } + + final int nCols = subMatrix[0].length; if (nCols == 0) { - throw new IllegalArgumentException("Matrix must have at least one column."); + throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one column"); } for (int r = 1; r < nRows; r++) { if (subMatrix[r].length != nCols) { - throw new IllegalArgumentException("All input rows must have the same length."); + throw MathRuntimeException.createIllegalArgumentException( + "some rows have length {0} while others have length {1}", + nCols, subMatrix[r].length); } } @@ -717,10 +734,10 @@ public class BigMatrixImpl implements BigMatrix, Serializable { data = new BigDecimal[nRows][nCols]; System.arraycopy(subMatrix, 0, data, 0, subMatrix.length); } else { - checkRowIndex(row); - checkColumnIndex(column); - checkRowIndex(nRows + row - 1); - checkColumnIndex(nCols + column - 1); + MatrixUtils.checkRowIndex(this, row); + MatrixUtils.checkColumnIndex(this, column); + MatrixUtils.checkRowIndex(this, nRows + row - 1); + MatrixUtils.checkColumnIndex(this, nCols + column - 1); } for (int i = 0; i < nRows; i++) { System.arraycopy(subMatrix[i], 0, data[row + i], column, nCols); @@ -739,7 +756,7 @@ public class BigMatrixImpl implements BigMatrix, Serializable { * @throws MatrixIndexException if the specified row index is invalid */ public BigMatrix getRowMatrix(int row) throws MatrixIndexException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final int ncols = this.getColumnDimension(); final BigDecimal[][] out = new BigDecimal[1][ncols]; System.arraycopy(data[row], 0, out[0], 0, ncols); @@ -755,7 +772,7 @@ public class BigMatrixImpl implements BigMatrix, Serializable { * @throws MatrixIndexException if the specified column index is invalid */ public BigMatrix getColumnMatrix(int column) throws MatrixIndexException { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); final int nRows = this.getRowDimension(); final BigDecimal[][] out = new BigDecimal[nRows][1]; for (int row = 0; row < nRows; row++) { @@ -775,7 +792,7 @@ public class BigMatrixImpl implements BigMatrix, Serializable { * @throws MatrixIndexException if the specified row index is not valid */ public BigDecimal[] getRow(int row) throws MatrixIndexException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final int ncols = this.getColumnDimension(); final BigDecimal[] out = new BigDecimal[ncols]; System.arraycopy(data[row], 0, out, 0, ncols); @@ -794,7 +811,7 @@ public class BigMatrixImpl implements BigMatrix, Serializable { * @throws MatrixIndexException if the specified row index is not valid */ public double[] getRowAsDoubleArray(int row) throws MatrixIndexException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final int ncols = this.getColumnDimension(); final double[] out = new double[ncols]; for (int i=0;i= getRowDimension()) { - throw new MatrixIndexException( - "row index {0} out of allowed range [{1}, {2}]", - row, 0, getRowDimension() - 1); - } - } - - /** - * Check if a column index is valid. - * @param column column index to check - * @exception MatrixIndexException if index is not valid - */ - private void checkColumnIndex(final int column) - throws MatrixIndexException { - if (column < 0 || column >= getColumnDimension()) { - throw new MatrixIndexException( - "column index {0} out of allowed range [{1}, {2}]", - column, 0, getColumnDimension() - 1); - } - } - } diff --git a/src/java/org/apache/commons/math/linear/DenseRealMatrix.java b/src/java/org/apache/commons/math/linear/DenseRealMatrix.java index 144f13819..13ae0f046 100644 --- a/src/java/org/apache/commons/math/linear/DenseRealMatrix.java +++ b/src/java/org/apache/commons/math/linear/DenseRealMatrix.java @@ -311,7 +311,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable } catch (ClassCastException cce) { // safety check - checkAdditionCompatible(m); + MatrixUtils.checkAdditionCompatible(this, m); final DenseRealMatrix out = new DenseRealMatrix(rows, columns); @@ -355,7 +355,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable throws IllegalArgumentException { // safety check - checkAdditionCompatible(m); + MatrixUtils.checkAdditionCompatible(this, m); final DenseRealMatrix out = new DenseRealMatrix(rows, columns); @@ -382,7 +382,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable } catch (ClassCastException cce) { // safety check - checkSubtractionCompatible(m); + MatrixUtils.checkSubtractionCompatible(this, m); final DenseRealMatrix out = new DenseRealMatrix(rows, columns); @@ -426,7 +426,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable throws IllegalArgumentException { // safety check - checkSubtractionCompatible(m); + MatrixUtils.checkSubtractionCompatible(this, m); final DenseRealMatrix out = new DenseRealMatrix(rows, columns); @@ -493,7 +493,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable } catch (ClassCastException cce) { // safety check - checkMultiplicationCompatible(m); + MatrixUtils.checkMultiplicationCompatible(this, m); final DenseRealMatrix out = new DenseRealMatrix(rows, m.getColumnDimension()); @@ -552,7 +552,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable public DenseRealMatrix multiply(DenseRealMatrix m) throws IllegalArgumentException { // safety check - checkMultiplicationCompatible(m); + MatrixUtils.checkMultiplicationCompatible(this, m); final DenseRealMatrix out = new DenseRealMatrix(rows, m.columns); @@ -686,7 +686,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable throws MatrixIndexException { // safety checks - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); // create the output matrix final DenseRealMatrix out = @@ -815,7 +815,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable } final int endRow = row + subMatrix.length - 1; final int endColumn = column + refLength - 1; - checkSubMatrixIndex(row, endRow, column, endColumn); + MatrixUtils.checkSubMatrixIndex(this, row, endRow, column, endColumn); for (final double[] subRow : subMatrix) { if (subRow.length != refLength) { throw MathRuntimeException.createIllegalArgumentException( @@ -861,7 +861,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable public RealMatrix getRowMatrix(final int row) throws MatrixIndexException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final DenseRealMatrix out = new DenseRealMatrix(1, columns); // perform copy block-wise, to ensure good cache behavior @@ -914,7 +914,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable public void setRowMatrix(final int row, final DenseRealMatrix matrix) throws MatrixIndexException, InvalidMatrixException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final int nCols = getColumnDimension(); if ((matrix.getRowDimension() != 1) || (matrix.getColumnDimension() != nCols)) { @@ -952,7 +952,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable public RealMatrix getColumnMatrix(final int column) throws MatrixIndexException { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); final DenseRealMatrix out = new DenseRealMatrix(rows, 1); // perform copy block-wise, to ensure good cache behavior @@ -1003,7 +1003,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable void setColumnMatrix(final int column, final DenseRealMatrix matrix) throws MatrixIndexException, InvalidMatrixException { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); final int nRows = getRowDimension(); if ((matrix.getRowDimension() != nRows) || (matrix.getColumnDimension() != 1)) { @@ -1039,7 +1039,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable public RealVector getRowVector(final int row) throws MatrixIndexException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final double[] outData = new double[columns]; // perform copy block-wise, to ensure good cache behavior @@ -1073,7 +1073,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable public RealVector getColumnVector(final int column) throws MatrixIndexException { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); final double[] outData = new double[rows]; // perform copy block-wise, to ensure good cache behavior @@ -1109,7 +1109,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable public double[] getRow(final int row) throws MatrixIndexException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final double[] out = new double[columns]; // perform copy block-wise, to ensure good cache behavior @@ -1132,7 +1132,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable public void setRow(final int row, final double[] array) throws MatrixIndexException, InvalidMatrixException { - checkRowIndex(row); + MatrixUtils.checkRowIndex(this, row); final int nCols = getColumnDimension(); if (array.length != nCols) { throw new InvalidMatrixException( @@ -1158,7 +1158,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable public double[] getColumn(final int column) throws MatrixIndexException { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); final double[] out = new double[rows]; // perform copy block-wise, to ensure good cache behavior @@ -1183,7 +1183,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable public void setColumn(final int column, final double[] array) throws MatrixIndexException, InvalidMatrixException { - checkColumnIndex(column); + MatrixUtils.checkColumnIndex(this, column); final int nRows = getRowDimension(); if (array.length != nRows) { throw new InvalidMatrixException( @@ -1467,7 +1467,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { final int p0 = iBlock * BLOCK_SIZE; @@ -1495,7 +1495,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { final int p0 = iBlock * BLOCK_SIZE; @@ -1567,7 +1567,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { final int p0 = iBlock * BLOCK_SIZE; @@ -1595,7 +1595,7 @@ public class DenseRealMatrix extends AbstractRealMatrix implements Serializable final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { final int p0 = iBlock * BLOCK_SIZE; diff --git a/src/java/org/apache/commons/math/linear/FieldMatrix.java b/src/java/org/apache/commons/math/linear/FieldMatrix.java index dc8217969..3ffa6c6f6 100644 --- a/src/java/org/apache/commons/math/linear/FieldMatrix.java +++ b/src/java/org/apache/commons/math/linear/FieldMatrix.java @@ -32,7 +32,7 @@ import org.apache.commons.math.linear.decomposition.NonSquareMatrixException; * @param the type of the field elements * @version $Revision$ $Date$ */ -public interface FieldMatrix> extends Serializable { +public interface FieldMatrix> extends AnyMatrix, Serializable { /** * Get the type of field elements of the matrix. @@ -431,26 +431,6 @@ public interface FieldMatrix> extends Serializable { */ FieldMatrix transpose(); - /** - * Is this a square matrix? - * @return true if the matrix is square (rowDimension = columnDimension) - */ - boolean isSquare(); - - /** - * Returns the number of rows in the matrix. - * - * @return rowDimension - */ - int getRowDimension(); - - /** - * Returns the number of columns in the matrix. - * - * @return columnDimension - */ - int getColumnDimension(); - /** * Returns the * trace of the matrix (the sum of the elements on the main diagonal). diff --git a/src/java/org/apache/commons/math/linear/MatrixUtils.java b/src/java/org/apache/commons/math/linear/MatrixUtils.java index 1570c4686..182d2bfed 100644 --- a/src/java/org/apache/commons/math/linear/MatrixUtils.java +++ b/src/java/org/apache/commons/math/linear/MatrixUtils.java @@ -491,6 +491,140 @@ public class MatrixUtils { } return new BigMatrixImpl(data, false); } - -} + /** + * Check if a row index is valid. + * @param m matrix containing the submatrix + * @param row row index to check + * @exception MatrixIndexException if index is not valid + */ + public static void checkRowIndex(final AnyMatrix m, final int row) { + if (row < 0 || row >= m.getRowDimension()) { + throw new MatrixIndexException("row index {0} out of allowed range [{1}, {2}]", + row, 0, m.getRowDimension() - 1); + } + } + + /** + * Check if a column index is valid. + * @param m matrix containing the submatrix + * @param column column index to check + * @exception MatrixIndexException if index is not valid + */ + public static void checkColumnIndex(final AnyMatrix m, final int column) + throws MatrixIndexException { + if (column < 0 || column >= m.getColumnDimension()) { + throw new MatrixIndexException("column index {0} out of allowed range [{1}, {2}]", + column, 0, m.getColumnDimension() - 1); + } + } + + /** + * Check if submatrix ranges indices are valid. + * Rows and columns are indicated counting from 0 to n-1. + * + * @param m matrix containing the submatrix + * @param startRow Initial row index + * @param endRow Final row index + * @param startColumn Initial column index + * @param endColumn Final column index + * @exception MatrixIndexException if the indices are not valid + */ + public static void checkSubMatrixIndex(final AnyMatrix m, + final int startRow, final int endRow, + final int startColumn, final int endColumn) { + checkRowIndex(m, startRow); + checkRowIndex(m, endRow); + if (startRow > endRow) { + throw new MatrixIndexException("initial row {0} after final row {1}", + startRow, endRow); + } + + checkColumnIndex(m, startColumn); + checkColumnIndex(m, endColumn); + if (startColumn > endColumn) { + throw new MatrixIndexException("initial column {0} after final column {1}", + startColumn, endColumn); + } + + + } + + /** + * Check if submatrix ranges indices are valid. + * Rows and columns are indicated counting from 0 to n-1. + * + * @param m matrix containing the submatrix + * @param selectedRows Array of row indices. + * @param selectedColumns Array of column indices. + * @exception MatrixIndexException if row or column selections are not valid + */ + public static void checkSubMatrixIndex(final AnyMatrix m, + final int[] selectedRows, final int[] selectedColumns) + throws MatrixIndexException { + if (selectedRows.length * selectedColumns.length == 0) { + if (selectedRows.length == 0) { + throw new MatrixIndexException("empty selected row index array"); + } + throw new MatrixIndexException("empty selected column index array"); + } + + for (final int row : selectedRows) { + checkRowIndex(m, row); + } + for (final int column : selectedColumns) { + checkColumnIndex(m, column); + } + } + + /** + * Check if matrices are addition compatible + * @param left left hand side matrix + * @param right right hand side matrix + * @exception IllegalArgumentException if matrices are not addition compatible + */ + public static void checkAdditionCompatible(final AnyMatrix left, final AnyMatrix right) + throws IllegalArgumentException { + if ((left.getRowDimension() != right.getRowDimension()) || + (left.getColumnDimension() != right.getColumnDimension())) { + throw MathRuntimeException.createIllegalArgumentException( + "{0}x{1} and {2}x{3} matrices are not addition compatible", + left.getRowDimension(), left.getColumnDimension(), + right.getRowDimension(), right.getColumnDimension()); + } + } + + /** + * Check if matrices are subtraction compatible + * @param left left hand side matrix + * @param right right hand side matrix + * @exception IllegalArgumentException if matrices are not subtraction compatible + */ + public static void checkSubtractionCompatible(final AnyMatrix left, final AnyMatrix right) + throws IllegalArgumentException { + if ((left.getRowDimension() != right.getRowDimension()) || + (left.getColumnDimension() != right.getColumnDimension())) { + throw MathRuntimeException.createIllegalArgumentException( + "{0}x{1} and {2}x{3} matrices are not subtraction compatible", + left.getRowDimension(), left.getColumnDimension(), + right.getRowDimension(), right.getColumnDimension()); + } + } + + /** + * Check if matrices are multiplication compatible + * @param left left hand side matrix + * @param right right hand side matrix + * @exception IllegalArgumentException if matrices are not multiplication compatible + */ + public static void checkMultiplicationCompatible(final AnyMatrix left, final AnyMatrix right) + throws IllegalArgumentException { + if (left.getColumnDimension() != right.getRowDimension()) { + throw MathRuntimeException.createIllegalArgumentException( + "{0}x{1} and {2}x{3} matrices are not multiplication compatible", + left.getRowDimension(), left.getColumnDimension(), + right.getRowDimension(), right.getColumnDimension()); + } + } + +} diff --git a/src/java/org/apache/commons/math/linear/RealMatrix.java b/src/java/org/apache/commons/math/linear/RealMatrix.java index d95cc5f8b..54f8f611a 100644 --- a/src/java/org/apache/commons/math/linear/RealMatrix.java +++ b/src/java/org/apache/commons/math/linear/RealMatrix.java @@ -31,7 +31,7 @@ import org.apache.commons.math.linear.decomposition.NonSquareMatrixException; * * @version $Revision$ $Date$ */ -public interface RealMatrix extends Serializable { +public interface RealMatrix extends AnyMatrix, Serializable { /** * Create a new RealMatrix of the same type as the instance with the supplied @@ -459,12 +459,6 @@ public interface RealMatrix extends Serializable { @Deprecated double getDeterminant(); - /** - * Is this a square matrix? - * @return true if the matrix is square (rowDimension = columnDimension) - */ - boolean isSquare(); - /** * Is this a singular matrix? * @return true if the matrix is singular @@ -474,20 +468,6 @@ public interface RealMatrix extends Serializable { @Deprecated boolean isSingular(); - /** - * Returns the number of rows in the matrix. - * - * @return rowDimension - */ - int getRowDimension(); - - /** - * Returns the number of columns in the matrix. - * - * @return columnDimension - */ - int getColumnDimension(); - /** * Returns the * trace of the matrix (the sum of the elements on the main diagonal). diff --git a/src/java/org/apache/commons/math/linear/RealMatrixImpl.java b/src/java/org/apache/commons/math/linear/RealMatrixImpl.java index 06c8049b0..fb40d97f3 100644 --- a/src/java/org/apache/commons/math/linear/RealMatrixImpl.java +++ b/src/java/org/apache/commons/math/linear/RealMatrixImpl.java @@ -188,7 +188,7 @@ public class RealMatrixImpl extends AbstractRealMatrix implements Serializable { throws IllegalArgumentException { // safety check - checkAdditionCompatible(m); + MatrixUtils.checkAdditionCompatible(this, m); final int rowCount = getRowDimension(); final int columnCount = getColumnDimension(); @@ -228,7 +228,7 @@ public class RealMatrixImpl extends AbstractRealMatrix implements Serializable { throws IllegalArgumentException { // safety check - checkSubtractionCompatible(m); + MatrixUtils.checkSubtractionCompatible(this, m); final int rowCount = getRowDimension(); final int columnCount = getColumnDimension(); @@ -268,7 +268,7 @@ public class RealMatrixImpl extends AbstractRealMatrix implements Serializable { throws IllegalArgumentException { // safety check - checkMultiplicationCompatible(m); + MatrixUtils.checkMultiplicationCompatible(this, m); final int nRows = this.getRowDimension(); final int nCols = m.getColumnDimension(); @@ -497,7 +497,7 @@ public class RealMatrixImpl extends AbstractRealMatrix implements Serializable { final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(getRowDimension(), getColumnDimension(), startRow, endRow, startColumn, endColumn); for (int i = startRow; i <= endRow; ++i) { @@ -515,7 +515,7 @@ public class RealMatrixImpl extends AbstractRealMatrix implements Serializable { final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(getRowDimension(), getColumnDimension(), startRow, endRow, startColumn, endColumn); for (int i = startRow; i <= endRow; ++i) { @@ -564,7 +564,7 @@ public class RealMatrixImpl extends AbstractRealMatrix implements Serializable { final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(getRowDimension(), getColumnDimension(), startRow, endRow, startColumn, endColumn); for (int j = startColumn; j <= endColumn; ++j) { @@ -582,7 +582,7 @@ public class RealMatrixImpl extends AbstractRealMatrix implements Serializable { final int startRow, final int endRow, final int startColumn, final int endColumn) throws MatrixIndexException, MatrixVisitorException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); + MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(getRowDimension(), getColumnDimension(), startRow, endRow, startColumn, endColumn); for (int j = startColumn; j <= endColumn; ++j) { diff --git a/src/java/org/apache/commons/math/linear/RealVectorFormat.java b/src/java/org/apache/commons/math/linear/RealVectorFormat.java index 4ecc0bdf8..180db2583 100644 --- a/src/java/org/apache/commons/math/linear/RealVectorFormat.java +++ b/src/java/org/apache/commons/math/linear/RealVectorFormat.java @@ -245,7 +245,9 @@ public class RealVectorFormat extends CompositeFormat { return format( (RealVector)obj, toAppendTo, pos); } - throw new IllegalArgumentException("Cannot format given Object as a RealVector"); + throw MathRuntimeException.createIllegalArgumentException( + "cannot format a {0} instance as a real vector", + obj.getClass().getName()); } diff --git a/src/java/org/apache/commons/math/linear/SparseRealMatrix.java b/src/java/org/apache/commons/math/linear/SparseRealMatrix.java index 85bd2efec..0a1c3da34 100644 --- a/src/java/org/apache/commons/math/linear/SparseRealMatrix.java +++ b/src/java/org/apache/commons/math/linear/SparseRealMatrix.java @@ -101,7 +101,7 @@ public class SparseRealMatrix extends AbstractRealMatrix { public RealMatrix add(SparseRealMatrix m) throws IllegalArgumentException { // safety check - checkAdditionCompatible(m); + MatrixUtils.checkAdditionCompatible(this, m); final RealMatrix out = new SparseRealMatrix(this); for (OpenIntToDoubleHashMap.Iterator iterator = m.entries.iterator(); iterator.hasNext();) { @@ -136,7 +136,7 @@ public class SparseRealMatrix extends AbstractRealMatrix { public RealMatrix subtract(SparseRealMatrix m) throws IllegalArgumentException { // safety check - checkAdditionCompatible(m); + MatrixUtils.checkAdditionCompatible(this, m); final RealMatrix out = new SparseRealMatrix(this); for (OpenIntToDoubleHashMap.Iterator iterator = m.entries.iterator(); iterator.hasNext();) { @@ -159,7 +159,7 @@ public class SparseRealMatrix extends AbstractRealMatrix { } catch (ClassCastException cce) { // safety check - checkMultiplicationCompatible(m); + MatrixUtils.checkMultiplicationCompatible(this, m); final int outCols = m.getColumnDimension(); final DenseRealMatrix out = new DenseRealMatrix(rowDimension, outCols); @@ -190,7 +190,7 @@ public class SparseRealMatrix extends AbstractRealMatrix { public SparseRealMatrix multiply(SparseRealMatrix m) throws IllegalArgumentException { // safety check - checkMultiplicationCompatible(m); + MatrixUtils.checkMultiplicationCompatible(this, m); final int outCols = m.getColumnDimension(); SparseRealMatrix out = new SparseRealMatrix(rowDimension, outCols); @@ -222,8 +222,8 @@ public class SparseRealMatrix extends AbstractRealMatrix { /** {@inheritDoc} */ @Override public double getEntry(int row, int column) throws MatrixIndexException { - checkRowIndex(row); - checkColumnIndex(column); + MatrixUtils.checkRowIndex(this, row); + MatrixUtils.checkColumnIndex(this, column); return entries.get(computeKey(row, column)); } @@ -237,8 +237,8 @@ public class SparseRealMatrix extends AbstractRealMatrix { @Override public void setEntry(int row, int column, double value) throws MatrixIndexException { - checkRowIndex(row); - checkColumnIndex(column); + MatrixUtils.checkRowIndex(this, row); + MatrixUtils.checkColumnIndex(this, column); if (value == 0.0) { entries.remove(computeKey(row, column)); } else { @@ -250,8 +250,8 @@ public class SparseRealMatrix extends AbstractRealMatrix { @Override public void addToEntry(int row, int column, double increment) throws MatrixIndexException { - checkRowIndex(row); - checkColumnIndex(column); + MatrixUtils.checkRowIndex(this, row); + MatrixUtils.checkColumnIndex(this, column); final int key = computeKey(row, column); final double value = entries.get(key) + increment; if (value == 0.0) { @@ -265,8 +265,8 @@ public class SparseRealMatrix extends AbstractRealMatrix { @Override public void multiplyEntry(int row, int column, double factor) throws MatrixIndexException { - checkRowIndex(row); - checkColumnIndex(column); + MatrixUtils.checkRowIndex(this, row); + MatrixUtils.checkColumnIndex(this, column); final int key = computeKey(row, column); final double value = entries.get(key) * factor; if (value == 0.0) { diff --git a/src/java/org/apache/commons/math/ode/ContinuousOutputModel.java b/src/java/org/apache/commons/math/ode/ContinuousOutputModel.java index f798b2294..053984915 100644 --- a/src/java/org/apache/commons/math/ode/ContinuousOutputModel.java +++ b/src/java/org/apache/commons/math/ode/ContinuousOutputModel.java @@ -115,11 +115,14 @@ public class ContinuousOutputModel } else { if (getInterpolatedState().length != model.getInterpolatedState().length) { - throw new IllegalArgumentException("state vector dimension mismatch"); + throw MathRuntimeException.createIllegalArgumentException( + "dimension mismatch {0} != {1}", + getInterpolatedState().length, model.getInterpolatedState().length); } if (forward ^ model.forward) { - throw new IllegalArgumentException("propagation direction mismatch"); + throw MathRuntimeException.createIllegalArgumentException( + "propagation direction mismatch"); } final StepInterpolator lastInterpolator = steps.get(index); @@ -128,7 +131,8 @@ public class ContinuousOutputModel final double step = current - previous; final double gap = model.getInitialTime() - current; if (Math.abs(gap) > 1.0e-3 * Math.abs(step)) { - throw new IllegalArgumentException("hole between time ranges"); + throw MathRuntimeException.createIllegalArgumentException( + "{0} wide hole between models time ranges", Math.abs(gap)); } } diff --git a/src/java/org/apache/commons/math/ode/NordsieckTransformer.java b/src/java/org/apache/commons/math/ode/NordsieckTransformer.java index 9d27e1787..1280c8a68 100644 --- a/src/java/org/apache/commons/math/ode/NordsieckTransformer.java +++ b/src/java/org/apache/commons/math/ode/NordsieckTransformer.java @@ -53,7 +53,9 @@ import org.apache.commons.math.linear.decomposition.FieldLUDecompositionImpl; * org.apache.commons.math.ode.nonstiff.AdamsBashforthIntegrator Adams-Bashforth} * integrator uses p=1, q=2, r=1, s=n. The {@link * org.apache.commons.math.ode.nonstiff.AdamsMoultonIntegrator Adams-Moulton} - * integrator uses p=1, q=2, r=0, s=n-1. + * integrator uses p=1, q=2, r=0, s=n-1. The {@link + * org.apache.commons.math.ode.stiff.BDFIntegrator BDF} integrator uses p=1, q=n, + * r=0, s=1. *

*

* The Nordsieck form for a dimension n state history at step k is composed of the @@ -81,6 +83,7 @@ import org.apache.commons.math.linear.decomposition.FieldLUDecompositionImpl; * @see org.apache.commons.math.ode.MultistepIntegrator * @see org.apache.commons.math.ode.nonstiff.AdamsBashforthIntegrator * @see org.apache.commons.math.ode.nonstiff.AdamsMoultonIntegrator + * @see org.apache.commons.math.ode.stiff.BDFIntegrator * @version $Revision$ $Date$ * @since 2.0 */ diff --git a/src/java/org/apache/commons/math/random/AbstractRandomGenerator.java b/src/java/org/apache/commons/math/random/AbstractRandomGenerator.java index aee3b37c2..6d4a477a8 100644 --- a/src/java/org/apache/commons/math/random/AbstractRandomGenerator.java +++ b/src/java/org/apache/commons/math/random/AbstractRandomGenerator.java @@ -16,6 +16,8 @@ */ package org.apache.commons.math.random; +import org.apache.commons.math.MathRuntimeException; + /** * Abstract class implementing the {@link RandomGenerator} interface. * Default implementations for all methods other than {@link #nextDouble()} and @@ -138,7 +140,8 @@ public abstract class AbstractRandomGenerator implements RandomGenerator { */ public int nextInt(int n) { if (n <= 0 ) { - throw new IllegalArgumentException("upper bound must be positive"); + throw MathRuntimeException.createIllegalArgumentException( + "upper bound must be positive ({0})", n); } int result = (int) (nextDouble() * n); return result < n ? result : n - 1; diff --git a/src/java/org/apache/commons/math/random/EmpiricalDistributionImpl.java b/src/java/org/apache/commons/math/random/EmpiricalDistributionImpl.java index 959ea2fe7..893cb0954 100644 --- a/src/java/org/apache/commons/math/random/EmpiricalDistributionImpl.java +++ b/src/java/org/apache/commons/math/random/EmpiricalDistributionImpl.java @@ -228,8 +228,11 @@ public class EmpiricalDistributionImpl implements Serializable, EmpiricalDistrib double[] inputArray = (double[]) in; return new ArrayDataAdapter(inputArray); } else { - throw new IllegalArgumentException( - "Input data comes from the" + " unsupported source"); + throw MathRuntimeException.createIllegalArgumentException( + "input data comes from unsupported datasource: {0}, " + + "supported sources: {1}, {2}", + in.getClass().getName(), + BufferedReader.class.getName(), double[].class.getName()); } } } diff --git a/src/java/org/apache/commons/math/random/RandomDataImpl.java b/src/java/org/apache/commons/math/random/RandomDataImpl.java index e785f47ab..cded24f36 100644 --- a/src/java/org/apache/commons/math/random/RandomDataImpl.java +++ b/src/java/org/apache/commons/math/random/RandomDataImpl.java @@ -24,6 +24,7 @@ import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.util.Collection; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.util.MathUtils; /** @@ -132,7 +133,8 @@ public class RandomDataImpl implements RandomData, Serializable { */ public String nextHexString(int len) { if (len <= 0) { - throw new IllegalArgumentException("length must be positive"); + throw MathRuntimeException.createIllegalArgumentException( + "length must be positive ({0})", len); } // Get a random number generator @@ -177,8 +179,9 @@ public class RandomDataImpl implements RandomData, Serializable { */ public int nextInt(int lower, int upper) { if (lower >= upper) { - throw new IllegalArgumentException( - "upper bound must be > lower bound"); + throw MathRuntimeException.createIllegalArgumentException( + "upper bound ({0}) must be greater than lower bound ({1})", + upper, lower); } RandomGenerator rand = getRan(); double r = rand.nextDouble(); @@ -197,8 +200,9 @@ public class RandomDataImpl implements RandomData, Serializable { */ public long nextLong(long lower, long upper) { if (lower >= upper) { - throw new IllegalArgumentException( - "upper bound must be > lower bound"); + throw MathRuntimeException.createIllegalArgumentException( + "upper bound ({0}) must be greater than lower bound ({1})", + upper, lower); } RandomGenerator rand = getRan(); double r = rand.nextDouble(); @@ -227,7 +231,8 @@ public class RandomDataImpl implements RandomData, Serializable { */ public String nextSecureHexString(int len) { if (len <= 0) { - throw new IllegalArgumentException("length must be positive"); + throw MathRuntimeException.createIllegalArgumentException( + "length must be positive ({0})", len); } // Get SecureRandom and setup Digest provider @@ -286,8 +291,9 @@ public class RandomDataImpl implements RandomData, Serializable { */ public int nextSecureInt(int lower, int upper) { if (lower >= upper) { - throw new IllegalArgumentException( - "lower bound must be < upper bound"); + throw MathRuntimeException.createIllegalArgumentException( + "upper bound ({0}) must be greater than lower bound ({1})", + upper, lower); } SecureRandom sec = getSecRan(); return lower + (int) (sec.nextDouble() * (upper - lower + 1)); @@ -306,8 +312,9 @@ public class RandomDataImpl implements RandomData, Serializable { */ public long nextSecureLong(long lower, long upper) { if (lower >= upper) { - throw new IllegalArgumentException( - "lower bound must be < upper bound"); + throw MathRuntimeException.createIllegalArgumentException( + "upper bound ({0}) must be greater than lower bound ({1})", + upper, lower); } SecureRandom sec = getSecRan(); return lower + (long) (sec.nextDouble() * (upper - lower + 1)); @@ -344,7 +351,8 @@ public class RandomDataImpl implements RandomData, Serializable { */ public long nextPoisson(double mean) { if (mean <= 0) { - throw new IllegalArgumentException("Poisson mean must be > 0"); + throw MathRuntimeException.createIllegalArgumentException( + "the Poisson mean must be positive ({0})", mean); } RandomGenerator rand = getRan(); @@ -446,7 +454,8 @@ public class RandomDataImpl implements RandomData, Serializable { */ public double nextGaussian(double mu, double sigma) { if (sigma <= 0) { - throw new IllegalArgumentException("Gaussian std dev must be > 0"); + throw MathRuntimeException.createIllegalArgumentException( + "standard deviation must be positive ({0})", sigma); } RandomGenerator rand = getRan(); return sigma * rand.nextGaussian() + mu; @@ -468,7 +477,8 @@ public class RandomDataImpl implements RandomData, Serializable { */ public double nextExponential(double mean) { if (mean < 0.0) { - throw new IllegalArgumentException("Exponential mean must be >= 0"); + throw MathRuntimeException.createIllegalArgumentException( + "mean must be positive ({0})", mean); } RandomGenerator rand = getRan(); double unif = rand.nextDouble(); @@ -496,8 +506,9 @@ public class RandomDataImpl implements RandomData, Serializable { */ public double nextUniform(double lower, double upper) { if (lower >= upper) { - throw new IllegalArgumentException( - "lower bound must be < upper bound"); + throw MathRuntimeException.createIllegalArgumentException( + "upper bound ({0}) must be greater than lower bound ({1})", + upper, lower); } RandomGenerator rand = getRan(); @@ -655,10 +666,12 @@ public class RandomDataImpl implements RandomData, Serializable { */ public int[] nextPermutation(int n, int k) { if (k > n) { - throw new IllegalArgumentException("permutation k exceeds n"); + throw MathRuntimeException.createIllegalArgumentException( + "permutation k ({0}) exceeds n ({1})", k, n); } if (k == 0) { - throw new IllegalArgumentException("permutation k must be > 0"); + throw MathRuntimeException.createIllegalArgumentException( + "permutation k ({0}) must be positive", k); } int[] index = getNatural(n); @@ -690,11 +703,12 @@ public class RandomDataImpl implements RandomData, Serializable { public Object[] nextSample(Collection c, int k) { int len = c.size(); if (k > len) { - throw new IllegalArgumentException( - "sample size exceeds collection size"); + throw MathRuntimeException.createIllegalArgumentException( + "sample size ({0}) exceeds collection size ({1})"); } - if (k == 0) { - throw new IllegalArgumentException("sample size must be > 0"); + if (k <= 0) { + throw MathRuntimeException.createIllegalArgumentException( + "sample size must be positive ({0})", k); } Object[] objects = c.toArray(); @@ -745,4 +759,5 @@ public class RandomDataImpl implements RandomData, Serializable { } return natural; } + } diff --git a/src/java/org/apache/commons/math/random/UncorrelatedRandomVectorGenerator.java b/src/java/org/apache/commons/math/random/UncorrelatedRandomVectorGenerator.java index cf0ee0e63..5f86a1262 100644 --- a/src/java/org/apache/commons/math/random/UncorrelatedRandomVectorGenerator.java +++ b/src/java/org/apache/commons/math/random/UncorrelatedRandomVectorGenerator.java @@ -19,6 +19,8 @@ package org.apache.commons.math.random; import java.util.Arrays; +import org.apache.commons.math.MathRuntimeException; + /** * A {@link RandomVectorGenerator} that generates vectors with uncorrelated * components. Components of generated vectors follow (independent) Gaussian @@ -46,7 +48,9 @@ public class UncorrelatedRandomVectorGenerator double[] standardDeviation, NormalizedRandomGenerator generator) { if (mean.length != standardDeviation.length) { - throw new IllegalArgumentException("dimension mismatch"); + throw MathRuntimeException.createIllegalArgumentException( + "dimension mismatch {0} != {1}", + mean.length, standardDeviation.length); } this.mean = mean.clone(); this.standardDeviation = standardDeviation.clone(); diff --git a/src/java/org/apache/commons/math/stat/Frequency.java b/src/java/org/apache/commons/math/stat/Frequency.java index 7780b7f9f..4cf1da589 100644 --- a/src/java/org/apache/commons/math/stat/Frequency.java +++ b/src/java/org/apache/commons/math/stat/Frequency.java @@ -22,6 +22,8 @@ import java.util.Iterator; import java.util.Comparator; import java.util.TreeMap; +import org.apache.commons.math.MathRuntimeException; + /** * Maintains a frequency distribution. *

@@ -110,7 +112,9 @@ public class Frequency implements Serializable { if (v instanceof Comparable){ addValue((Comparable) v); } else { - throw new IllegalArgumentException("Object must implement Comparable"); + throw MathRuntimeException.createIllegalArgumentException( + "class ({0}) does not implement Comparable", + v.getClass().getName()); } } @@ -138,7 +142,9 @@ public class Frequency implements Serializable { } } catch (ClassCastException ex) { //TreeMap will throw ClassCastException if v is not comparable - throw new IllegalArgumentException("Value not comparable to existing values."); + throw MathRuntimeException.createIllegalArgumentException( + "instance of class {0} not comparable to existing values", + v.getClass().getName()); } } diff --git a/src/java/org/apache/commons/math/stat/StatUtils.java b/src/java/org/apache/commons/math/stat/StatUtils.java index cf1d4b521..389013d35 100644 --- a/src/java/org/apache/commons/math/stat/StatUtils.java +++ b/src/java/org/apache/commons/math/stat/StatUtils.java @@ -16,6 +16,7 @@ */ package org.apache.commons.math.stat; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.stat.descriptive.UnivariateStatistic; import org.apache.commons.math.stat.descriptive.moment.GeometricMean; import org.apache.commons.math.stat.descriptive.moment.Mean; @@ -563,9 +564,10 @@ public final class StatUtils { public static double sumDifference(final double[] sample1, final double[] sample2) throws IllegalArgumentException { int n = sample1.length; - if (n != sample2.length || n < 1) { - throw new IllegalArgumentException - ("Input arrays must have the same (positive) length."); + if ((n != sample2.length) || (n < 1)) { + throw MathRuntimeException.createIllegalArgumentException( + "input arrays must have the same positive length ({0} and {1})", + n, sample2.length); } double result = 0; for (int i = 0; i < n; i++) { @@ -608,7 +610,9 @@ public final class StatUtils { double diff = 0d; int n = sample1.length; if (n < 2 || n != sample2.length) { - throw new IllegalArgumentException("Input array lengths must be equal and at least 2."); + throw MathRuntimeException.createIllegalArgumentException( + "input arrays must have the same length and at least two elements ({0} and {1})", + n, sample2.length); } for (int i = 0; i < n; i++) { diff = sample1[i] - sample2[i]; diff --git a/src/java/org/apache/commons/math/stat/descriptive/AbstractStorelessUnivariateStatistic.java b/src/java/org/apache/commons/math/stat/descriptive/AbstractStorelessUnivariateStatistic.java index bfe8e8b6f..27dcc80b4 100644 --- a/src/java/org/apache/commons/math/stat/descriptive/AbstractStorelessUnivariateStatistic.java +++ b/src/java/org/apache/commons/math/stat/descriptive/AbstractStorelessUnivariateStatistic.java @@ -16,6 +16,7 @@ */ package org.apache.commons.math.stat.descriptive; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.util.MathUtils; import java.io.Serializable; @@ -58,7 +59,7 @@ public abstract class AbstractStorelessUnivariateStatistic @Override public double evaluate(final double[] values) { if (values == null) { - throw new IllegalArgumentException("input value array is null"); + throw MathRuntimeException.createIllegalArgumentException("input values array is null"); } return evaluate(values, 0, values.length); } @@ -126,7 +127,7 @@ public abstract class AbstractStorelessUnivariateStatistic */ public void incrementAll(double[] values) { if (values == null) { - throw new IllegalArgumentException("input values array is null"); + throw MathRuntimeException.createIllegalArgumentException("input values array is null"); } incrementAll(values, 0, values.length); } diff --git a/src/java/org/apache/commons/math/stat/descriptive/AbstractUnivariateStatistic.java b/src/java/org/apache/commons/math/stat/descriptive/AbstractUnivariateStatistic.java index 68281f69f..0bcdb1823 100644 --- a/src/java/org/apache/commons/math/stat/descriptive/AbstractUnivariateStatistic.java +++ b/src/java/org/apache/commons/math/stat/descriptive/AbstractUnivariateStatistic.java @@ -18,6 +18,8 @@ package org.apache.commons.math.stat.descriptive; import java.io.Serializable; +import org.apache.commons.math.MathRuntimeException; + /** * Abstract base class for all implementations of the * {@link UnivariateStatistic} interface. @@ -80,20 +82,22 @@ public abstract class AbstractUnivariateStatistic final int length) { if (values == null) { - throw new IllegalArgumentException("input value array is null"); + throw MathRuntimeException.createIllegalArgumentException("input values array is null"); } if (begin < 0) { - throw new IllegalArgumentException("start position cannot be negative"); + throw MathRuntimeException.createIllegalArgumentException( + "start position cannot be negative ({0})", begin); } if (length < 0) { - throw new IllegalArgumentException("length cannot be negative"); + throw MathRuntimeException.createIllegalArgumentException( + "length cannot be negative ({0})", length); } if (begin + length > values.length) { - throw new IllegalArgumentException( - "begin + length > values.length"); + throw MathRuntimeException.createIllegalArgumentException( + "subarray ends after array end"); } if (length == 0) { diff --git a/src/java/org/apache/commons/math/stat/descriptive/DescriptiveStatistics.java b/src/java/org/apache/commons/math/stat/descriptive/DescriptiveStatistics.java index 4066f30b4..288b0807f 100644 --- a/src/java/org/apache/commons/math/stat/descriptive/DescriptiveStatistics.java +++ b/src/java/org/apache/commons/math/stat/descriptive/DescriptiveStatistics.java @@ -20,6 +20,7 @@ import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.stat.descriptive.moment.GeometricMean; import org.apache.commons.math.stat.descriptive.moment.Kurtosis; import org.apache.commons.math.stat.descriptive.moment.Mean; @@ -301,7 +302,8 @@ public class DescriptiveStatistics implements StatisticalSummary, Serializable { public void setWindowSize(int windowSize) { if (windowSize < 1) { if (windowSize != INFINITE_WINDOW) { - throw new IllegalArgumentException("window size must be positive."); + throw MathRuntimeException.createIllegalArgumentException( + "window size must be positive ({0})", windowSize); } } @@ -379,14 +381,15 @@ public class DescriptiveStatistics implements StatisticalSummary, Serializable { new Class[] {Double.TYPE}).invoke(percentileImpl, new Object[] {Double.valueOf(p)}); } catch (NoSuchMethodException e1) { // Setter guard should prevent - throw new IllegalArgumentException( - "Percentile implementation does not support setQuantile"); + throw MathRuntimeException.createIllegalArgumentException( + "percentile implementation {0} does not support setQuantile", + percentileImpl.getClass().getName()); } catch (IllegalAccessException e2) { - throw new IllegalArgumentException( - "IllegalAccessException setting quantile"); + throw MathRuntimeException.createIllegalArgumentException( + "cannot access setQuantile method in percentile implementation {0}", + percentileImpl.getClass().getName()); } catch (InvocationTargetException e3) { - throw new IllegalArgumentException( - "Error setting quantile" + e3.toString()); + throw MathRuntimeException.createIllegalArgumentException(e3.getCause()); } } return apply(percentileImpl); @@ -561,14 +564,15 @@ public class DescriptiveStatistics implements StatisticalSummary, Serializable { new Class[] {Double.TYPE}).invoke(percentileImpl, new Object[] {Double.valueOf(50.0d)}); } catch (NoSuchMethodException e1) { - throw new IllegalArgumentException( - "Percentile implementation does not support setQuantile"); + throw MathRuntimeException.createIllegalArgumentException( + "percentile implementation {0} does not support setQuantile", + percentileImpl.getClass().getName()); } catch (IllegalAccessException e2) { - throw new IllegalArgumentException( - "IllegalAccessException setting quantile"); + throw MathRuntimeException.createIllegalArgumentException( + "cannot access setQuantile method in percentile implementation {0}", + percentileImpl.getClass().getName()); } catch (InvocationTargetException e3) { - throw new IllegalArgumentException( - "Error setting quantile" + e3.toString()); + throw MathRuntimeException.createIllegalArgumentException(e3.getCause()); } this.percentileImpl = percentileImpl; } diff --git a/src/java/org/apache/commons/math/stat/descriptive/moment/Variance.java b/src/java/org/apache/commons/math/stat/descriptive/moment/Variance.java index f3d8903d2..ed259e483 100644 --- a/src/java/org/apache/commons/math/stat/descriptive/moment/Variance.java +++ b/src/java/org/apache/commons/math/stat/descriptive/moment/Variance.java @@ -18,6 +18,7 @@ package org.apache.commons.math.stat.descriptive.moment; import java.io.Serializable; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.stat.descriptive.AbstractStorelessUnivariateStatistic; /** @@ -211,7 +212,7 @@ public class Variance extends AbstractStorelessUnivariateStatistic implements Se @Override public double evaluate(final double[] values) { if (values == null) { - throw new IllegalArgumentException("input values array is null"); + throw MathRuntimeException.createIllegalArgumentException("input values array is null"); } return evaluate(values, 0, values.length); } diff --git a/src/java/org/apache/commons/math/stat/descriptive/rank/Percentile.java b/src/java/org/apache/commons/math/stat/descriptive/rank/Percentile.java index 30fa01f4e..267ed018d 100644 --- a/src/java/org/apache/commons/math/stat/descriptive/rank/Percentile.java +++ b/src/java/org/apache/commons/math/stat/descriptive/rank/Percentile.java @@ -18,6 +18,8 @@ package org.apache.commons.math.stat.descriptive.rank; import java.io.Serializable; import java.util.Arrays; + +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.stat.descriptive.AbstractUnivariateStatistic; /** @@ -196,7 +198,8 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa test(values, begin, length); if ((p > 100) || (p <= 0)) { - throw new IllegalArgumentException("invalid quantile value: " + p); + throw MathRuntimeException.createIllegalArgumentException( + "out of bounds quantile value: {0}, must be in (0, 100]", p); } if (length == 0) { return Double.NaN; @@ -244,7 +247,8 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa */ public void setQuantile(final double p) { if (p <= 0 || p > 100) { - throw new IllegalArgumentException("Illegal quantile value: " + p); + throw MathRuntimeException.createIllegalArgumentException( + "out of bounds quantile value: {0}, must be in (0, 100]", p); } quantile = p; } diff --git a/src/java/org/apache/commons/math/stat/regression/AbstractMultipleLinearRegression.java b/src/java/org/apache/commons/math/stat/regression/AbstractMultipleLinearRegression.java index fb2825ffc..64716d5ec 100644 --- a/src/java/org/apache/commons/math/stat/regression/AbstractMultipleLinearRegression.java +++ b/src/java/org/apache/commons/math/stat/regression/AbstractMultipleLinearRegression.java @@ -18,6 +18,8 @@ package org.apache.commons.math.stat.regression; import org.apache.commons.math.linear.RealMatrix; import org.apache.commons.math.linear.RealMatrixImpl; +import org.apache.commons.math.linear.RealVector; +import org.apache.commons.math.linear.RealVectorImpl; /** * Abstract base class for implementations of MultipleLinearRegression. @@ -31,7 +33,7 @@ public abstract class AbstractMultipleLinearRegression implements protected RealMatrix X; /** Y sample data. */ - protected RealMatrix Y; + protected RealVector Y; /** * Loads model x and y sample data from a flat array of data, overriding any previous sample. @@ -39,7 +41,7 @@ public abstract class AbstractMultipleLinearRegression implements * * @param data input data array * @param nobs number of observations (rows) - * @param nvars number of independent variables (columnns, not counting y) + * @param nvars number of independent variables (columns, not counting y) */ public void newSampleData(double[] data, int nobs, int nvars) { double[] y = new double[nobs]; @@ -53,7 +55,7 @@ public abstract class AbstractMultipleLinearRegression implements } } this.X = new RealMatrixImpl(x); - this.Y = new RealMatrixImpl(y); + this.Y = new RealVectorImpl(y); } /** @@ -62,7 +64,7 @@ public abstract class AbstractMultipleLinearRegression implements * @param y the [n,1] array representing the y sample */ protected void newYSampleData(double[] y) { - this.Y = new RealMatrixImpl(y); + this.Y = new RealVectorImpl(y); } /** @@ -120,17 +122,17 @@ public abstract class AbstractMultipleLinearRegression implements * {@inheritDoc} */ public double[] estimateRegressionParameters() { - RealMatrix b = calculateBeta(); - return b.getColumn(0); + RealVector b = calculateBeta(); + return b.getData(); } /** * {@inheritDoc} */ public double[] estimateResiduals() { - RealMatrix b = calculateBeta(); - RealMatrix e = Y.subtract(X.multiply(b)); - return e.getColumn(0); + RealVector b = calculateBeta(); + RealVector e = Y.subtract(X.operate(b)); + return e.getData(); } /** @@ -166,7 +168,7 @@ public abstract class AbstractMultipleLinearRegression implements * * @return beta */ - protected abstract RealMatrix calculateBeta(); + protected abstract RealVector calculateBeta(); /** * Calculates the beta variance of multiple linear regression in matrix @@ -193,9 +195,9 @@ public abstract class AbstractMultipleLinearRegression implements * * @return The residuals [n,1] matrix */ - protected RealMatrix calculateResiduals() { - RealMatrix b = calculateBeta(); - return Y.subtract(X.multiply(b)); + protected RealVector calculateResiduals() { + RealVector b = calculateBeta(); + return Y.subtract(X.operate(b)); } } diff --git a/src/java/org/apache/commons/math/stat/regression/SimpleRegression.java b/src/java/org/apache/commons/math/stat/regression/SimpleRegression.java index aea4a0cd2..64d5f8209 100644 --- a/src/java/org/apache/commons/math/stat/regression/SimpleRegression.java +++ b/src/java/org/apache/commons/math/stat/regression/SimpleRegression.java @@ -19,6 +19,7 @@ package org.apache.commons.math.stat.regression; import java.io.Serializable; import org.apache.commons.math.MathException; +import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.distribution.TDistribution; import org.apache.commons.math.distribution.TDistributionImpl; @@ -546,7 +547,9 @@ public class SimpleRegression implements Serializable { public double getSlopeConfidenceInterval(double alpha) throws MathException { if (alpha >= 1 || alpha <= 0) { - throw new IllegalArgumentException(); + throw MathRuntimeException.createIllegalArgumentException( + "out of bounds significance level {0}, must be in (0, 1)", + alpha); } return getSlopeStdErr() * distribution.inverseCumulativeProbability(1d - alpha / 2d); diff --git a/src/java/org/apache/commons/math/util/MathUtils.java b/src/java/org/apache/commons/math/util/MathUtils.java index d8d3e3741..28ee4a937 100644 --- a/src/java/org/apache/commons/math/util/MathUtils.java +++ b/src/java/org/apache/commons/math/util/MathUtils.java @@ -176,14 +176,7 @@ public final class MathUtils { * by a long integer. */ public static long binomialCoefficient(final int n, final int k) { - if (n < k) { - throw new IllegalArgumentException( - "must have n >= k for binomial coefficient (n,k)"); - } - if (n < 0) { - throw new IllegalArgumentException( - "must have n >= 0 for binomial coefficient (n,k)"); - } + checkBinomial(n, k); if ((n == k) || (k == 0)) { return 1; } @@ -253,14 +246,7 @@ public final class MathUtils { * @throws IllegalArgumentException if preconditions are not met. */ public static double binomialCoefficientDouble(final int n, final int k) { - if (n < k) { - throw new IllegalArgumentException( - "must have n >= k for binomial coefficient (n,k)"); - } - if (n < 0) { - throw new IllegalArgumentException( - "must have n >= 0 for binomial coefficient (n,k)"); - } + checkBinomial(n, k); if ((n == k) || (k == 0)) { return 1d; } @@ -301,14 +287,7 @@ public final class MathUtils { * @throws IllegalArgumentException if preconditions are not met. */ public static double binomialCoefficientLog(final int n, final int k) { - if (n < k) { - throw new IllegalArgumentException( - "must have n >= k for binomial coefficient (n,k)"); - } - if (n < 0) { - throw new IllegalArgumentException( - "must have n >= 0 for binomial coefficient (n,k)"); - } + checkBinomial(n, k); if ((n == k) || (k == 0)) { return 0; } @@ -353,6 +332,26 @@ public final class MathUtils { return logSum; } + + /** + * Check binomial preconditions. + * @param n the size of the set + * @param k the size of the subsets to be counted + * @exception IllegalArgumentException if preconditions are not met. + */ + private static void checkBinomial(final int n, final int k) + throws IllegalArgumentException { + if (n < k) { + throw MathRuntimeException.createIllegalArgumentException( + "must have n >= k for binomial coefficient (n,k), got n = {0}, k = {1}", + n, k); + } + if (n < 0) { + throw MathRuntimeException.createIllegalArgumentException( + "must have n >= 0 for binomial coefficient (n,k), got n = {0}", + n); + } + } /** * Compares two numbers given some amount of allowed error. @@ -501,7 +500,9 @@ public final class MathUtils { */ public static long factorial(final int n) { if (n < 0) { - throw new IllegalArgumentException("must have n >= 0 for n!"); + throw MathRuntimeException.createIllegalArgumentException( + "must have n >= 0 for n!, got n = {0}", + n); } if (n > 20) { throw new ArithmeticException( @@ -532,7 +533,9 @@ public final class MathUtils { */ public static double factorialDouble(final int n) { if (n < 0) { - throw new IllegalArgumentException("must have n >= 0 for n!"); + throw MathRuntimeException.createIllegalArgumentException( + "must have n >= 0 for n!, got n = {0}", + n); } if (n < 21) { return factorial(n); @@ -555,7 +558,9 @@ public final class MathUtils { */ public static double factorialLog(final int n) { if (n < 0) { - throw new IllegalArgumentException("must have n > 0 for n!"); + throw MathRuntimeException.createIllegalArgumentException( + "must have n >= 0 for n!, got n = {0}", + n); } if (n < 21) { return Math.log(factorial(n)); @@ -1132,7 +1137,18 @@ public final class MathUtils { unscaled = Math.ceil(nextAfter(unscaled, Double.POSITIVE_INFINITY)); break; default : - throw new IllegalArgumentException("Invalid rounding method."); + throw MathRuntimeException.createIllegalArgumentException( + "invalid rounding method {0}, valid methods: {1} ({2}), {3} ({4})," + + " {5} ({6}), {7} ({8}), {9} ({10}), {11} ({12}), {13} ({14}), {15} ({16})", + roundingMethod, + "ROUND_CEILING", BigDecimal.ROUND_CEILING, + "ROUND_DOWN", BigDecimal.ROUND_DOWN, + "ROUND_FLOOR", BigDecimal.ROUND_FLOOR, + "ROUND_HALF_DOWN", BigDecimal.ROUND_HALF_DOWN, + "ROUND_HALF_EVEN", BigDecimal.ROUND_HALF_EVEN, + "ROUND_HALF_UP", BigDecimal.ROUND_HALF_UP, + "ROUND_UNNECESSARY", BigDecimal.ROUND_UNNECESSARY, + "ROUND_UP", BigDecimal.ROUND_UP); } return unscaled; }