本文整理汇总了Java中org.apache.commons.math3.linear.SingularMatrixException类的典型用法代码示例。如果您正苦于以下问题:Java SingularMatrixException类的具体用法?Java SingularMatrixException怎么用?Java SingularMatrixException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
SingularMatrixException类属于org.apache.commons.math3.linear包,在下文中一共展示了SingularMatrixException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testNonInvertible
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
@Override
@Test(expected=SingularMatrixException.class)
public void testNonInvertible() {
/*
* Overrides the method from parent class, since the default singularity
* threshold (1e-14) does not trigger the expected exception.
*/
LinearProblem problem = new LinearProblem(new double[][] {
{ 1, 2, -3 },
{ 2, 1, 3 },
{ -3, 0, -9 }
}, new double[] { 1, 1, 1 });
AbstractLeastSquaresOptimizer optimizer = createOptimizer();
PointVectorValuePair optimum = optimizer.optimize(100, problem, problem.target, new double[] { 1, 1, 1 }, new double[] { 0, 0, 0 });
Assert.assertTrue(FastMath.sqrt(problem.target.length) * optimizer.getRMS() > 0.6);
optimizer.computeCovariances(optimum.getPoint(), 1.5e-14);
}
示例2: testNonInvertible
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
@Override
@Test(expected=SingularMatrixException.class)
public void testNonInvertible() {
/*
* Overrides the method from parent class, since the default singularity
* threshold (1e-14) does not trigger the expected exception.
*/
LinearProblem problem = new LinearProblem(new double[][] {
{ 1, 2, -3 },
{ 2, 1, 3 },
{ -3, 0, -9 }
}, new double[] { 1, 1, 1 });
AbstractLeastSquaresOptimizer optimizer = createOptimizer();
PointVectorValuePair optimum
= optimizer.optimize(new MaxEval(100),
problem.getModelFunction(),
problem.getModelFunctionJacobian(),
problem.getTarget(),
new Weight(new double[] { 1, 1, 1 }),
new InitialGuess(new double[] { 0, 0, 0 }));
Assert.assertTrue(FastMath.sqrt(optimizer.getTargetSize()) * optimizer.getRMS() > 0.6);
optimizer.computeCovariances(optimum.getPoint(), 1.5e-14);
}
示例3: update
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
/**
* This method updates the Kalman-Filter with the last known state/measurement of the observed value.
*
* @param xMeasured time step of measurement.
* It is measured in full, i.e. as {@link Long}, seconds since midnight, January 1, 1970 UTC.
* @param yMeasured Current measurement.
* @return True if the update was successful.
*/
public boolean update(long xMeasured, double yMeasured) {
boolean success = false;
try {
// Call predict(0), if no prediction was made since the last update
// Reason: The Kalman-Filter needs a predict-update(correct)-cycle.
if (!predictedSinceUpdate && lastUpdate != Constants.NO_PREDICTION) {
predict(0);
}
filter.correct(new double[] {xMeasured, 0, yMeasured, 0 });
// When an older value is updated/corrected the attributes 'lastUpdated' and 'lastUpdate' do not change.
if (lastUpdated < xMeasured) {
lastUpdated = xMeasured;
lastUpdate = yMeasured;
}
success = true;
predictedSinceUpdate = false;
lastMemUpdated();
} catch (NullArgumentException | DimensionMismatchException | SingularMatrixException e) {
LogManager.getLogger(Kalman.class).error(e.getMessage(), e);
}
return success;
}
示例4: testNonInvertible
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
@Override
@Test(expected=SingularMatrixException.class)
public void testNonInvertible() {
/*
* Overrides the method from parent class, since the default singularity
* threshold (1e-14) does not trigger the expected exception.
*/
LinearProblem problem = new LinearProblem(new double[][] {
{ 1, 2, -3 },
{ 2, 1, 3 },
{ -3, 0, -9 }
}, new double[] { 1, 1, 1 });
AbstractLeastSquaresOptimizer optimizer = createOptimizer();
optimizer.optimize(100, problem, problem.target, new double[] { 1, 1, 1 }, new double[] { 0, 0, 0 });
Assert.assertTrue(FastMath.sqrt(problem.target.length) * optimizer.getRMS() > 0.6);
optimizer.getCovariances(1.5e-14);
}
示例5: outputResult
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
private void outputResult() {
output = new StringBuilder();
printDoubleArray("expectedPosition: ", expectedPosition);
printDoubleArray("linear calculatedPosition: ", linearCalculatedPosition.toArray());
printDoubleArray("non-linear calculatedPosition: ", nonLinearOptimum.getPoint().toArray());
output.append("numberOfIterations: ").append(nonLinearOptimum.getIterations()).append("\n");
output.append("numberOfEvaluations: ").append(nonLinearOptimum.getEvaluations()).append("\n");
try {
RealVector standardDeviation = nonLinearOptimum.getSigma(0);
printDoubleArray("standardDeviation: ", standardDeviation.toArray());
output.append("Norm of deviation: ").append(standardDeviation.getNorm()).append("\n");
RealMatrix covarianceMatrix = nonLinearOptimum.getCovariances(0);
output.append("covarianceMatrix: ").append(covarianceMatrix).append("\n");
} catch (SingularMatrixException e) {
System.err.println(e.getMessage());
}
System.out.println(output.toString());
}
示例6: inverse
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
/**
* @param A a square matrix.
* @return the inverse of A or null if A is non-square or singular.
*/
public static double[][] inverse(final double[][] A) {
RealMatrix M = MatrixUtils.createRealMatrix(A);
if (!M.isSquare())
return null;
else {
double[][] Ai = null;
try {
RealMatrix Mi = MatrixUtils.inverse(M); //new LUDecomposition(M).getSolver().getInverse();
Ai = Mi.getData();
} catch (SingularMatrixException e) {}
return Ai;
}
}
示例7: solve
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
public static double[] solve(final double[][] A, double[] b) {
RealMatrix AA = MatrixUtils.createRealMatrix(A);
RealVector bb = MatrixUtils.createRealVector(b);
DecompositionSolver solver = new LUDecomposition(AA).getSolver();
double[] x = null;
try {
x = solver.solve(bb).toArray();
} catch (SingularMatrixException e) {}
return x;
}
示例8: inverse
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
@Nonnull
public static RealMatrix inverse(@Nonnull final RealMatrix m, final boolean exact)
throws SingularMatrixException {
LUDecomposition LU = new LUDecomposition(m);
DecompositionSolver solver = LU.getSolver();
final RealMatrix inv;
if (exact || solver.isNonSingular()) {
inv = solver.getInverse();
} else {
SingularValueDecomposition SVD = new SingularValueDecomposition(m);
inv = SVD.getSolver().getInverse();
}
return inv;
}
示例9: solve
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
/**
* L = A x R
*
* @return a matrix A that minimizes A x R - L
*/
@Nonnull
public static RealMatrix solve(@Nonnull final RealMatrix L, @Nonnull final RealMatrix R,
final boolean exact) throws SingularMatrixException {
LUDecomposition LU = new LUDecomposition(R);
DecompositionSolver solver = LU.getSolver();
final RealMatrix A;
if (exact || solver.isNonSingular()) {
A = LU.getSolver().solve(L);
} else {
SingularValueDecomposition SVD = new SingularValueDecomposition(R);
A = SVD.getSolver().solve(L);
}
return A;
}
示例10: testNonInvertible
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
@Override
@Test
public void testNonInvertible() {
try{
/*
* Overrides the method from parent class, since the default singularity
* threshold (1e-14) does not trigger the expected exception.
*/
LinearProblem problem = new LinearProblem(new double[][] {
{ 1, 2, -3 },
{ 2, 1, 3 },
{ -3, 0, -9 }
}, new double[] { 1, 1, 1 });
final Optimum optimum = optimizer.optimize(
problem.getBuilder().maxIterations(20).build());
//TODO check that it is a bad fit? Why the extra conditions?
Assert.assertTrue(FastMath.sqrt(problem.getTarget().length) * optimum.getRMS() > 0.6);
optimum.getCovariances(1.5e-14);
fail(optimizer);
}catch (SingularMatrixException e){
//expected
}
}
示例11: testQRSingular
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
@Test(expected=SingularMatrixException.class)
public void testQRSingular() {
final RealMatrix a = MatrixUtils.createRealMatrix(new double[][] {
{ 1, 6, 4 }, { 2, 4, -1 }, { -1, 2, 5 }
});
final RealVector b = new ArrayRealVector(new double[]{ 5, 6, 1 });
new QRDecomposition(a, 1.0e-15).getSolver().solve(b);
}
示例12: guessStartLine
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
/** Guess a start line using the last four results.
* @param n number of cached results available
* @param target target ground point
* @return guessed start line
*/
private double guessStartLine(final int n, final Vector3D target) {
try {
// assume a linear model of the form: l = ax + by + cz + d
final RealMatrix m = new Array2DRowRealMatrix(n, 4);
final RealVector v = new ArrayRealVector(n);
for (int i = 0; i < n; ++i) {
m.setEntry(i, 0, cachedResults[i].getTarget().getX());
m.setEntry(i, 1, cachedResults[i].getTarget().getY());
m.setEntry(i, 2, cachedResults[i].getTarget().getZ());
m.setEntry(i, 3, 1.0);
v.setEntry(i, cachedResults[i].getLine());
}
final DecompositionSolver solver = new QRDecomposition(m, Precision.SAFE_MIN).getSolver();
final RealVector coefficients = solver.solve(v);
// apply the linear model
return target.getX() * coefficients.getEntry(0) +
target.getY() * coefficients.getEntry(1) +
target.getZ() * coefficients.getEntry(2) +
coefficients.getEntry(3);
} catch (SingularMatrixException sme) {
// the points are not independent
return Double.NaN;
}
}
示例13: retrieveGaussianMixtureModelForFilteredTargets
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
/** <p>Produces a Gaussian mixture model based on the difference between targets and segment means.</p>
* <p>Filters targets to populations where more than the minProportion lie in a single segment.</p>
* <p>Returns null if no pass filtering. Please note that in these cases,
* in the rest of this class, we use this to assume that a GMM is not a good model.</p>
*
* @param segments -- segments with segment mean in log2 copy ratio space
* @param targets -- targets with a log2 copy ratio estimate
* @param minProportion -- minimum proportion of all targets that a given segment must have in order to be used
* in the evaluation
* @param numComponents -- number of components to use in the GMM. Usually, this is 2.
* @return never {@code null}. Fitting result with indications whether it converged or was even attempted.
*/
private MixtureMultivariateNormalFitResult retrieveGaussianMixtureModelForFilteredTargets(final List<ModeledSegment> segments,
final TargetCollection<ReadCountRecord.SingleSampleRecord> targets, double minProportion, int numComponents){
// For each target in a segment that contains enough targets, normalize the difference against the segment mean
// and collapse the filtered targets into the copy ratio estimates.
final List<Double> filteredTargetsSegDiff = getNumProbeFilteredTargetList(segments, targets, minProportion);
if (filteredTargetsSegDiff.size() < numComponents) {
return new MixtureMultivariateNormalFitResult(null, false, false);
}
// Assume that Apache Commons wants data points in the first dimension.
// Note that second dimension of length 2 (instead of 1) is to wrok around funny Apache commons API.
final double[][] filteredTargetsSegDiff2d = new double[filteredTargetsSegDiff.size()][2];
// Convert the filtered targets into 2d array (even if second dimension is length 1). The second dimension is
// uncorrelated Gaussian. This is only to get around funny API in Apache Commons, which will throw an
// exception if the length of the second dimension is < 2
final RandomGenerator rng = RandomGeneratorFactory.createRandomGenerator(new Random(RANDOM_SEED));
final NormalDistribution nd = new NormalDistribution(rng, 0, .1);
for (int i = 0; i < filteredTargetsSegDiff.size(); i++) {
filteredTargetsSegDiff2d[i][0] = filteredTargetsSegDiff.get(i);
filteredTargetsSegDiff2d[i][1] = nd.sample();
}
final MixtureMultivariateNormalDistribution estimateEM0 = MultivariateNormalMixtureExpectationMaximization.estimate(filteredTargetsSegDiff2d, numComponents);
final MultivariateNormalMixtureExpectationMaximization multivariateNormalMixtureExpectationMaximization = new MultivariateNormalMixtureExpectationMaximization(filteredTargetsSegDiff2d);
try {
multivariateNormalMixtureExpectationMaximization.fit(estimateEM0);
} catch (final MaxCountExceededException | ConvergenceException | SingularMatrixException e) {
// We are done, we cannot make a fitting. We should return a result that we attempted a fitting, but it
// did not converge. Include the model as it was when the exception was thrown.
return new MixtureMultivariateNormalFitResult(multivariateNormalMixtureExpectationMaximization.getFittedModel(), false, true);
}
return new MixtureMultivariateNormalFitResult(multivariateNormalMixtureExpectationMaximization.getFittedModel(), true, true);
}
示例14: updateInverseCovariance
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
private void updateInverseCovariance() {
try {
inverseCov = new LUDecomposition(cov).getSolver().getInverse();
} catch (SingularMatrixException e) {
singularCovariances.inc();
inverseCov = new SingularValueDecomposition(cov).getSolver().getInverse();
}
}
示例15: correct
import org.apache.commons.math3.linear.SingularMatrixException; //导入依赖的package包/类
/**
* Correct the current state estimate with an actual measurement.
*
* @param z
* the measurement vector
* @throws NullArgumentException
* if the measurement vector is {@code null}
* @throws DimensionMismatchException
* if the dimension of the measurement vector does not fit
* @throws SingularMatrixException
* if the covariance matrix could not be inverted
*/
public void correct(final RealVector z)
throws NullArgumentException, DimensionMismatchException, SingularMatrixException {
// sanity checks
MathUtils.checkNotNull(z);
if (z.getDimension() != measurementMatrix.getRowDimension()) {
throw new DimensionMismatchException(z.getDimension(),
measurementMatrix.getRowDimension());
}
// S = H * P(k) - * H' + R
RealMatrix s = measurementMatrix.multiply(errorCovariance)
.multiply(measurementMatrixT)
.add(measurementModel.getMeasurementNoise());
// invert S
// as the error covariance matrix is a symmetric positive
// semi-definite matrix, we can use the cholesky decomposition
DecompositionSolver solver = new CholeskyDecomposition(s).getSolver();
RealMatrix invertedS = solver.getInverse();
// Inn = z(k) - H * xHat(k)-
RealVector innovation = z.subtract(measurementMatrix.operate(stateEstimation));
// calculate gain matrix
// K(k) = P(k)- * H' * (H * P(k)- * H' + R)^-1
// K(k) = P(k)- * H' * S^-1
RealMatrix kalmanGain = errorCovariance.multiply(measurementMatrixT).multiply(invertedS);
// update estimate with measurement z(k)
// xHat(k) = xHat(k)- + K * Inn
stateEstimation = stateEstimation.add(kalmanGain.operate(innovation));
// update covariance of prediction error
// P(k) = (I - K * H) * P(k)-
RealMatrix identity = MatrixUtils.createRealIdentityMatrix(kalmanGain.getRowDimension());
errorCovariance = identity.subtract(kalmanGain.multiply(measurementMatrix)).multiply(errorCovariance);
}