|
Java example source code file (MatrixUtils.java)
The MatrixUtils.java Java example source code/* * 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.math3.linear; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import org.apache.commons.math3.Field; import org.apache.commons.math3.FieldElement; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathArithmeticException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.exception.ZeroException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.fraction.BigFraction; import org.apache.commons.math3.fraction.Fraction; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathArrays; import org.apache.commons.math3.util.MathUtils; import org.apache.commons.math3.util.Precision; /** * A collection of static methods that operate on or return matrices. * */ public class MatrixUtils { /** * The default format for {@link RealMatrix} objects. * @since 3.1 */ public static final RealMatrixFormat DEFAULT_FORMAT = RealMatrixFormat.getInstance(); /** * A format for {@link RealMatrix} objects compatible with octave. * @since 3.1 */ public static final RealMatrixFormat OCTAVE_FORMAT = new RealMatrixFormat("[", "]", "", "", "; ", ", "); /** * Private constructor. */ private MatrixUtils() { super(); } /** * Returns a {@link RealMatrix} with specified dimensions. * <p>The type of matrix returned depends on the dimension. Below * 2<sup>12 elements (i.e. 4096 elements or 64×64 for a * square matrix) which can be stored in a 32kB array, a {@link * Array2DRowRealMatrix} instance is built. Above this threshold a {@link * BlockRealMatrix} instance is built.</p> * <p>The matrix elements are all set to 0.0. * @param rows number of rows of the matrix * @param columns number of columns of the matrix * @return RealMatrix with specified dimensions * @see #createRealMatrix(double[][]) */ public static RealMatrix createRealMatrix(final int rows, final int columns) { return (rows * columns <= 4096) ? new Array2DRowRealMatrix(rows, columns) : new BlockRealMatrix(rows, columns); } /** * Returns a {@link FieldMatrix} with specified dimensions. * <p>The type of matrix returned depends on the dimension. Below * 2<sup>12 elements (i.e. 4096 elements or 64×64 for a * square matrix), a {@link FieldMatrix} instance is built. Above * this threshold a {@link BlockFieldMatrix} instance is built.</p> * <p>The matrix elements are all set to field.getZero(). * @param <T> the type of the field elements * @param field field to which the matrix elements belong * @param rows number of rows of the matrix * @param columns number of columns of the matrix * @return FieldMatrix with specified dimensions * @see #createFieldMatrix(FieldElement[][]) * @since 2.0 */ public static <T extends FieldElement
* </p>
*
* @param vector real vector to serialize
* @param oos stream where the real vector should be written
* @exception IOException if object cannot be written to stream
* @see #deserializeRealVector(Object, String, ObjectInputStream)
*/
public static void serializeRealVector(final RealVector vector,
final ObjectOutputStream oos)
throws IOException {
final int n = vector.getDimension();
oos.writeInt(n);
for (int i = 0; i < n; ++i) {
oos.writeDouble(vector.getEntry(i));
}
}
/** Deserialize a {@link RealVector} field in a class.
* <p>
* This method is intended to be called from within a private
* <code>readObject method (after a call to
* <code>ois.defaultReadObject()) in a class that has a
* {@link RealVector} field, which should be declared <code>transient.
* This way, the default handling does not deserialize the vector (the {@link
* RealVector} interface is not serializable by default) but this method does
* deserialize it specifically.
* </p>
* @param instance instance in which the field must be set up
* @param fieldName name of the field within the class (may be private and final)
* @param ois stream from which the real vector should be read
* @exception ClassNotFoundException if a class in the stream cannot be found
* @exception IOException if object cannot be read from the stream
* @see #serializeRealVector(RealVector, ObjectOutputStream)
*/
public static void deserializeRealVector(final Object instance,
final String fieldName,
final ObjectInputStream ois)
throws ClassNotFoundException, IOException {
try {
// read the vector data
final int n = ois.readInt();
final double[] data = new double[n];
for (int i = 0; i < n; ++i) {
data[i] = ois.readDouble();
}
// create the instance
final RealVector vector = new ArrayRealVector(data, false);
// set up the field
final java.lang.reflect.Field f =
instance.getClass().getDeclaredField(fieldName);
f.setAccessible(true);
f.set(instance, vector);
} catch (NoSuchFieldException nsfe) {
IOException ioe = new IOException();
ioe.initCause(nsfe);
throw ioe;
} catch (IllegalAccessException iae) {
IOException ioe = new IOException();
ioe.initCause(iae);
throw ioe;
}
}
/** Serialize a {@link RealMatrix}.
* <p>
* This method is intended to be called from within a private
* <code>writeObject method (after a call to
* <code>oos.defaultWriteObject()) in a class that has a
* {@link RealMatrix} field, which should be declared <code>transient.
* This way, the default handling does not serialize the matrix (the {@link
* RealMatrix} interface is not serializable by default) but this method does
* serialize it specifically.
* </p>
* <p>
* The following example shows how a simple class with a name and a real matrix
* should be written:
* <pre>
* public class NamedMatrix implements Serializable {
*
* private final String name;
* private final transient RealMatrix coefficients;
*
* // omitted constructors, getters ...
*
* private void writeObject(ObjectOutputStream oos) throws IOException {
* oos.defaultWriteObject(); // takes care of name field
* MatrixUtils.serializeRealMatrix(coefficients, oos);
* }
*
* private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
* ois.defaultReadObject(); // takes care of name field
* MatrixUtils.deserializeRealMatrix(this, "coefficients", ois);
* }
*
* }
* </code>
* </p>
*
* @param matrix real matrix to serialize
* @param oos stream where the real matrix should be written
* @exception IOException if object cannot be written to stream
* @see #deserializeRealMatrix(Object, String, ObjectInputStream)
*/
public static void serializeRealMatrix(final RealMatrix matrix,
final ObjectOutputStream oos)
throws IOException {
final int n = matrix.getRowDimension();
final int m = matrix.getColumnDimension();
oos.writeInt(n);
oos.writeInt(m);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
oos.writeDouble(matrix.getEntry(i, j));
}
}
}
/** Deserialize a {@link RealMatrix} field in a class.
* <p>
* This method is intended to be called from within a private
* <code>readObject method (after a call to
* <code>ois.defaultReadObject()) in a class that has a
* {@link RealMatrix} field, which should be declared <code>transient.
* This way, the default handling does not deserialize the matrix (the {@link
* RealMatrix} interface is not serializable by default) but this method does
* deserialize it specifically.
* </p>
* @param instance instance in which the field must be set up
* @param fieldName name of the field within the class (may be private and final)
* @param ois stream from which the real matrix should be read
* @exception ClassNotFoundException if a class in the stream cannot be found
* @exception IOException if object cannot be read from the stream
* @see #serializeRealMatrix(RealMatrix, ObjectOutputStream)
*/
public static void deserializeRealMatrix(final Object instance,
final String fieldName,
final ObjectInputStream ois)
throws ClassNotFoundException, IOException {
try {
// read the matrix data
final int n = ois.readInt();
final int m = ois.readInt();
final double[][] data = new double[n][m];
for (int i = 0; i < n; ++i) {
final double[] dataI = data[i];
for (int j = 0; j < m; ++j) {
dataI[j] = ois.readDouble();
}
}
// create the instance
final RealMatrix matrix = new Array2DRowRealMatrix(data, false);
// set up the field
final java.lang.reflect.Field f =
instance.getClass().getDeclaredField(fieldName);
f.setAccessible(true);
f.set(instance, matrix);
} catch (NoSuchFieldException nsfe) {
IOException ioe = new IOException();
ioe.initCause(nsfe);
throw ioe;
} catch (IllegalAccessException iae) {
IOException ioe = new IOException();
ioe.initCause(iae);
throw ioe;
}
}
/**Solve a system of composed of a Lower Triangular Matrix
* {@link RealMatrix}.
* <p>
* This method is called to solve systems of equations which are
* of the lower triangular form. The matrix {@link RealMatrix}
* is assumed, though not checked, to be in lower triangular form.
* The vector {@link RealVector} is overwritten with the solution.
* The matrix is checked that it is square and its dimensions match
* the length of the vector.
* </p>
* @param rm RealMatrix which is lower triangular
* @param b RealVector this is overwritten
* @throws DimensionMismatchException if the matrix and vector are not
* conformable
* @throws NonSquareMatrixException if the matrix {@code rm} is not square
* @throws MathArithmeticException if the absolute value of one of the diagonal
* coefficient of {@code rm} is lower than {@link Precision#SAFE_MIN}
*/
public static void solveLowerTriangularSystem(RealMatrix rm, RealVector b)
throws DimensionMismatchException, MathArithmeticException,
NonSquareMatrixException {
if ((rm == null) || (b == null) || ( rm.getRowDimension() != b.getDimension())) {
throw new DimensionMismatchException(
(rm == null) ? 0 : rm.getRowDimension(),
(b == null) ? 0 : b.getDimension());
}
if( rm.getColumnDimension() != rm.getRowDimension() ){
throw new NonSquareMatrixException(rm.getRowDimension(),
rm.getColumnDimension());
}
int rows = rm.getRowDimension();
for( int i = 0 ; i < rows ; i++ ){
double diag = rm.getEntry(i, i);
if( FastMath.abs(diag) < Precision.SAFE_MIN ){
throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR);
}
double bi = b.getEntry(i)/diag;
b.setEntry(i, bi );
for( int j = i+1; j< rows; j++ ){
b.setEntry(j, b.getEntry(j)-bi*rm.getEntry(j,i) );
}
}
}
/** Solver a system composed of an Upper Triangular Matrix
* {@link RealMatrix}.
* <p>
* This method is called to solve systems of equations which are
* of the lower triangular form. The matrix {@link RealMatrix}
* is assumed, though not checked, to be in upper triangular form.
* The vector {@link RealVector} is overwritten with the solution.
* The matrix is checked that it is square and its dimensions match
* the length of the vector.
* </p>
* @param rm RealMatrix which is upper triangular
* @param b RealVector this is overwritten
* @throws DimensionMismatchException if the matrix and vector are not
* conformable
* @throws NonSquareMatrixException if the matrix {@code rm} is not
* square
* @throws MathArithmeticException if the absolute value of one of the diagonal
* coefficient of {@code rm} is lower than {@link Precision#SAFE_MIN}
*/
public static void solveUpperTriangularSystem(RealMatrix rm, RealVector b)
throws DimensionMismatchException, MathArithmeticException,
NonSquareMatrixException {
if ((rm == null) || (b == null) || ( rm.getRowDimension() != b.getDimension())) {
throw new DimensionMismatchException(
(rm == null) ? 0 : rm.getRowDimension(),
(b == null) ? 0 : b.getDimension());
}
if( rm.getColumnDimension() != rm.getRowDimension() ){
throw new NonSquareMatrixException(rm.getRowDimension(),
rm.getColumnDimension());
}
int rows = rm.getRowDimension();
for( int i = rows-1 ; i >-1 ; i-- ){
double diag = rm.getEntry(i, i);
if( FastMath.abs(diag) < Precision.SAFE_MIN ){
throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR);
}
double bi = b.getEntry(i)/diag;
b.setEntry(i, bi );
for( int j = i-1; j>-1; j-- ){
b.setEntry(j, b.getEntry(j)-bi*rm.getEntry(j,i) );
}
}
}
/**
* Computes the inverse of the given matrix by splitting it into
* 4 sub-matrices.
*
* @param m Matrix whose inverse must be computed.
* @param splitIndex Index that determines the "split" line and
* column.
* The element corresponding to this index will part of the
* upper-left sub-matrix.
* @return the inverse of {@code m}.
* @throws NonSquareMatrixException if {@code m} is not square.
*/
public static RealMatrix blockInverse(RealMatrix m,
int splitIndex) {
final int n = m.getRowDimension();
if (m.getColumnDimension() != n) {
throw new NonSquareMatrixException(m.getRowDimension(),
m.getColumnDimension());
}
final int splitIndex1 = splitIndex + 1;
final RealMatrix a = m.getSubMatrix(0, splitIndex, 0, splitIndex);
final RealMatrix b = m.getSubMatrix(0, splitIndex, splitIndex1, n - 1);
final RealMatrix c = m.getSubMatrix(splitIndex1, n - 1, 0, splitIndex);
final RealMatrix d = m.getSubMatrix(splitIndex1, n - 1, splitIndex1, n - 1);
final SingularValueDecomposition aDec = new SingularValueDecomposition(a);
final DecompositionSolver aSolver = aDec.getSolver();
if (!aSolver.isNonSingular()) {
throw new SingularMatrixException();
}
final RealMatrix aInv = aSolver.getInverse();
final SingularValueDecomposition dDec = new SingularValueDecomposition(d);
final DecompositionSolver dSolver = dDec.getSolver();
if (!dSolver.isNonSingular()) {
throw new SingularMatrixException();
}
final RealMatrix dInv = dSolver.getInverse();
final RealMatrix tmp1 = a.subtract(b.multiply(dInv).multiply(c));
final SingularValueDecomposition tmp1Dec = new SingularValueDecomposition(tmp1);
final DecompositionSolver tmp1Solver = tmp1Dec.getSolver();
if (!tmp1Solver.isNonSingular()) {
throw new SingularMatrixException();
}
final RealMatrix result00 = tmp1Solver.getInverse();
final RealMatrix tmp2 = d.subtract(c.multiply(aInv).multiply(b));
final SingularValueDecomposition tmp2Dec = new SingularValueDecomposition(tmp2);
final DecompositionSolver tmp2Solver = tmp2Dec.getSolver();
if (!tmp2Solver.isNonSingular()) {
throw new SingularMatrixException();
}
final RealMatrix result11 = tmp2Solver.getInverse();
final RealMatrix result01 = aInv.multiply(b).multiply(result11).scalarMultiply(-1);
final RealMatrix result10 = dInv.multiply(c).multiply(result00).scalarMultiply(-1);
final RealMatrix result = new Array2DRowRealMatrix(n, n);
result.setSubMatrix(result00.getData(), 0, 0);
result.setSubMatrix(result01.getData(), 0, splitIndex1);
result.setSubMatrix(result10.getData(), splitIndex1, 0);
result.setSubMatrix(result11.getData(), splitIndex1, splitIndex1);
return result;
}
/**
* Computes the inverse of the given matrix.
* <p>
* By default, the inverse of the matrix is computed using the QR-decomposition,
* unless a more efficient method can be determined for the input matrix.
* <p>
* Note: this method will use a singularity threshold of 0,
* use {@link #inverse(RealMatrix, double)} if a different threshold is needed.
*
* @param matrix Matrix whose inverse shall be computed
* @return the inverse of {@code matrix}
* @throws NullArgumentException if {@code matrix} is {@code null}
* @throws SingularMatrixException if m is singular
* @throws NonSquareMatrixException if matrix is not square
* @since 3.3
*/
public static RealMatrix inverse(RealMatrix matrix)
throws NullArgumentException, SingularMatrixException, NonSquareMatrixException {
return inverse(matrix, 0);
}
/**
* Computes the inverse of the given matrix.
* <p>
* By default, the inverse of the matrix is computed using the QR-decomposition,
* unless a more efficient method can be determined for the input matrix.
*
* @param matrix Matrix whose inverse shall be computed
* @param threshold Singularity threshold
* @return the inverse of {@code m}
* @throws NullArgumentException if {@code matrix} is {@code null}
* @throws SingularMatrixException if matrix is singular
* @throws NonSquareMatrixException if matrix is not square
* @since 3.3
*/
public static RealMatrix inverse(RealMatrix matrix, double threshold)
throws NullArgumentException, SingularMatrixException, NonSquareMatrixException {
MathUtils.checkNotNull(matrix);
if (!matrix.isSquare()) {
throw new NonSquareMatrixException(matrix.getRowDimension(),
matrix.getColumnDimension());
}
if (matrix instanceof DiagonalMatrix) {
return ((DiagonalMatrix) matrix).inverse(threshold);
} else {
QRDecomposition decomposition = new QRDecomposition(matrix, threshold);
return decomposition.getSolver().getInverse();
}
}
}
Other Java examples (source code examples)Here is a short list of links related to this Java MatrixUtils.java source code file: |
... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.