Java Code Examples for org.apache.commons.math3.linear.RealMatrix#getColumn()

The following examples show how to use org.apache.commons.math3.linear.RealMatrix#getColumn() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SumColumnsEvaluator.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public Object doWork(Object value) throws IOException{
  if(null == value){
    return null;
  } else if (value instanceof Matrix) {

    //First transpose the matrix
    Matrix matrix = (Matrix) value;
    double[][] data = matrix.getData();
    RealMatrix realMatrix = new Array2DRowRealMatrix(data, false);

    List<Number> sums = new ArrayList<>(data[0].length);

    for(int i=0; i<data[0].length; i++) {
      double sum = 0;
      double[] col = realMatrix.getColumn(i);
      for(int j=0; j<col.length; j++){
        sum+=col[j];
      }

      sums.add(sum);
    }

    return sums;
  } else {
    throw new IOException("Grand sum function only operates on a matrix");
  }
}
 
Example 2
Source File: ENU.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Converts an Earth-Centered Earth-Fixed (ECEF) coordinate to ENU. 
 * 
 * @param cEcef the ECEF coordinate.
 * @return the ENU coordinate.
 * @throws MatrixException 
 */
public Coordinate ecefToEnu( Coordinate cEcef ) {
    double deltaX = cEcef.x - _ecefROriginX;
    double deltaY = cEcef.y - _ecefROriginY;
    double deltaZ = cEcef.z - _ecefROriginZ;

    double[][] deltas = new double[][]{{deltaX}, {deltaY}, {deltaZ}};
    RealMatrix deltaMatrix = MatrixUtils.createRealMatrix(deltas);

    RealMatrix enuMatrix = _rotationMatrix.multiply(deltaMatrix);
    double[] column = enuMatrix.getColumn(0);

    return new Coordinate(column[0], column[1], column[2]);
}
 
Example 3
Source File: SpearmansRankCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new SpearmansCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new SpearmansCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 4
Source File: PearsonsCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new PearsonsCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new PearsonsCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 5
Source File: SpearmansRankCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new SpearmansCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new SpearmansCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 6
Source File: PearsonsCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new PearsonsCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new PearsonsCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 7
Source File: SpearmansRankCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new SpearmansCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new SpearmansCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 8
Source File: PearsonsCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new PearsonsCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new PearsonsCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 9
Source File: SpearmansRankCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new SpearmansCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new SpearmansCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 10
Source File: PearsonsCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new PearsonsCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new PearsonsCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 11
Source File: SpearmansRankCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new SpearmansCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new SpearmansCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 12
Source File: PearsonsCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new PearsonsCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new PearsonsCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 13
Source File: PearsonsCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new PearsonsCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new PearsonsCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 14
Source File: PearsonsCorrelationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsistency() {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix);
    double[][] data = matrix.getData();
    double[] x = matrix.getColumn(0);
    double[] y = matrix.getColumn(1);
    Assert.assertEquals(new PearsonsCorrelation().correlation(x, y),
            corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE);
    TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(),
            new PearsonsCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE);
}
 
Example 15
Source File: ENU.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Converts an ENU coordinate to Earth-Centered Earth-Fixed (ECEF).
 * 
 * @param cEnu the enu coordinate.
 * @return the ecef coordinate.
 */
public Coordinate enuToEcef( Coordinate cEnu ) {
    double[][] enu = new double[][]{{cEnu.x}, {cEnu.y}, {cEnu.z}};
    RealMatrix enuMatrix = MatrixUtils.createRealMatrix(enu);

    RealMatrix deltasMatrix = _inverseRotationMatrix.multiply(enuMatrix);

    double[] column = deltasMatrix.getColumn(0);
    double cecfX = column[0] + _ecefROriginX;
    double cecfY = column[1] + _ecefROriginY;
    double cecfZ = column[2] + _ecefROriginZ;

    return new Coordinate(cecfX, cecfY, cecfZ);
}
 
Example 16
Source File: IntegerCopyNumberTransitionProbabilityCacheUnitTest.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testBasicSoundness() {
    for (final RealMatrix transitionMatrix : TRANSITION_MATRICES) {
        final IntegerCopyNumberTransitionProbabilityCache cache = new IntegerCopyNumberTransitionProbabilityCache(
                new IntegerCopyNumberTransitionMatrix(transitionMatrix, 0));
        for (final int dist : DISTANCES) {
            final RealMatrix transitionMatrixExponentiated = cache.getTransitionProbabilityMatrix(dist);

            /* assert positivity */
            Assert.assertTrue(Arrays.stream(transitionMatrixExponentiated.getData())
                    .flatMapToDouble(Arrays::stream)
                    .allMatch(d -> d >= 0));

            /* assert conservation of probability */
            for (int c = 0; c < transitionMatrix.getColumnDimension(); c++) {
                Assert.assertEquals(Arrays.stream(transitionMatrixExponentiated.getColumn(c)).sum(), 1.0, EPSILON);
            }

            /* assert correctness, T(2*d) = T(d)*T(d) */
            assertEqualMatrices(cache.getTransitionProbabilityMatrix(2*dist),
                    transitionMatrixExponentiated.multiply(transitionMatrixExponentiated));
        }

        /* assert loss of initial state over long distances, i.e. all columns must be equal */
        final RealMatrix longRangeTransitionMatrix = cache.getTransitionProbabilityMatrix(Integer.MAX_VALUE);
        final double[] firstColumn = longRangeTransitionMatrix.getColumn(0);
        final RealMatrix syntheticLongRangeTransitionMatrix = new Array2DRowRealMatrix(firstColumn.length,
                firstColumn.length);
        for (int i = 0; i < firstColumn.length; i++) {
            syntheticLongRangeTransitionMatrix.setColumn(i, firstColumn);
        }
        assertEqualMatrices(longRangeTransitionMatrix, syntheticLongRangeTransitionMatrix);

        final double[] stationary = cache.getStationaryProbabilityVector().toArray();
        ArrayAsserts.assertArrayEquals(stationary, firstColumn, EPSILON);
    }
}
 
Example 17
Source File: Math.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
public static double[] rlsInterpolation(double[] x, double[] y, int pow) {
	if (pow < 1) {
		return null;
	}

	double[] coeffs = new double[pow + 1];
	double d = 1000d;
	for (int i = 0; i < pow + 1; i++) {
		coeffs[i] = 0d;
	}
	double[][] pMtx = new double[pow + 1][pow + 1];
	for (int i = 0; i < pow + 1; i++) {
		for (int j = 0; j < pow + 1; j++) {
			pMtx[i][j] = (i == j) ? d : 0;
		}
	}

	RealMatrix wV = new Array2DRowRealMatrix(coeffs);
	RealMatrix pM = new Array2DRowRealMatrix(pMtx);

	for (int k = 0; k < x.length; k++) {
		double xx = x[k];
		double yy = y[k];

		RealMatrix xV = new Array2DRowRealMatrix(pow + 1, 1);

		double aPow = 1;
		for (int i = 0; i < pow + 1; i++) {
			xV.setEntry(i, 0, aPow);
			aPow *= xx;
		}

		double alpha = yy - wV.transpose().multiply(xV).getEntry(0, 0);
		RealMatrix gV = pM.multiply(xV).scalarMultiply(1 / (1d + xV.transpose().multiply(pM).multiply(xV).getEntry(0, 0)));
		pM = pM.subtract(gV.multiply(xV.transpose()).multiply(pM));
		wV = wV.add(gV.scalarMultiply(alpha));
	}
	return wV.getColumn(0);
}
 
Example 18
Source File: BlackScholesTheta.java    From finmath-lib with Apache License 2.0 4 votes vote down vote up
public double[][] solve() {
	// Create interior spatial vector for heat equation
	final int len = numberOfPointsPositive - numberOfPointsNegative - 1;
	final double[] x = new double[len];
	for (int i = 0; i < len; i++) {
		x[i] = (numberOfPointsNegative + 1) * dx + dx * i;
	}

	// Create time vector for heat equation
	final double[] tau = new double[numTimesteps + 1];
	for (int i = 0; i < numTimesteps + 1; i++) {
		tau[i] = i * dtau;
	}

	// Create necessary matrices
	final double[][] C = new double[len][len];
	final double[][] D = new double[len][len];
	for (int i = 0; i < len; i++) {
		for (int j = 0; j < len; j++) {
			if (i == j) {
				C[i][j] = 1 + 2 * theta * kappa;
				D[i][j] = 1 - 2 * (1 - theta) * kappa;
			} else if ((i == j - 1) || (i == j + 1)) {
				C[i][j] = - theta * kappa;
				D[i][j] = (1 - theta) * kappa;
			} else {
				C[i][j] = 0;
				D[i][j] = 0;
			}
		}
	}

	final RealMatrix CMatrix = new Array2DRowRealMatrix(C);
	final RealMatrix DMatrix = new Array2DRowRealMatrix(D);
	final DecompositionSolver solver = new LUDecomposition(CMatrix).getSolver();

	// Create spatial boundary vector
	final double[] b = new double[len];
	Arrays.fill(b, 0);

	// Initialize U
	double[] U = new double[len];
	for (int i = 0; i < U.length; i++) {
		U[i] = u_0(x[i]);
	}
	RealMatrix UVector = MatrixUtils.createColumnRealMatrix(U);

	// Solve system
	for (int m = 0; m < numTimesteps; m++) {
		b[0] = (u_neg_inf(numberOfPointsNegative * dx, tau[m]) * (1 - theta) * kappa)
				+ (u_neg_inf(numberOfPointsNegative * dx, tau[m + 1]) * theta * kappa);
		b[len-1] = (u_pos_inf(numberOfPointsPositive * dx, tau[m]) * (1 - theta) * kappa)
				+ (u_pos_inf(numberOfPointsPositive * dx, tau[m + 1]) * theta * kappa);

		final RealMatrix bVector = MatrixUtils.createColumnRealMatrix(b);
		final RealMatrix constantsMatrix = (DMatrix.multiply(UVector)).add(bVector);
		UVector = solver.solve(constantsMatrix);
	}
	U = UVector.getColumn(0);

	// Transform x to stockPrice and U to optionPrice
	final double[] optionPrice = new double[len];
	final double[] stockPrice = new double[len];
	for (int i = 0; i < len; i++ ){
		optionPrice[i] = U[i] * optionStrike *
				Math.exp(alpha * x[i] + beta * tau[numTimesteps]);
		stockPrice[i] = f_s(x[i]);
	}

	final double[][] stockAndOptionPrice = new double[2][len];
	stockAndOptionPrice[0] = stockPrice;
	stockAndOptionPrice[1] = optionPrice;
	return stockAndOptionPrice;
}
 
Example 19
Source File: LinearRegression.java    From rapidminer-studio with GNU Affero General Public License v3.0 4 votes vote down vote up
/** Calculates the coefficients of linear ridge regression. */
public static double[] performRegression(Matrix a, Matrix b, double ridge) {
	RealMatrix x = MatrixUtils.createRealMatrix(a.getArray());
	RealMatrix y = MatrixUtils.createRealMatrix(b.getArray());
	int numberOfColumns = x.getColumnDimension();
	double[] coefficients = new double[numberOfColumns];
	RealMatrix xTransposed = x.transpose();
	Matrix result;
	boolean finished = false;
	while (!finished) {
		RealMatrix xTx = xTransposed.multiply(x);

		for (int i = 0; i < numberOfColumns; i++) {
			xTx.addToEntry(i, i, ridge);
		}

		RealMatrix xTy = xTransposed.multiply(y);
		coefficients = xTy.getColumn(0);

		try {
			// do not use Apache LUDecomposition for solve instead because it creates different
			// results
			result = new Matrix(xTx.getData()).solve(new Matrix(coefficients, coefficients.length));
			for (int i = 0; i < numberOfColumns; i++) {
				coefficients[i] = result.get(i, 0);
			}
			finished = true;
		} catch (Exception ex) {
			double ridgeOld = ridge;
			if (ridge > 0) {
				ridge *= 10;
			} else {
				ridge = 0.0000001;
			}
			finished = false;
			logger.warning("Error during calculation: " + ex.getMessage() + ": Increasing ridge factor from " + ridgeOld
					+ " to " + ridge);
		}
	}
	return coefficients;
}
 
Example 20
Source File: BlackScholesTheta.java    From finmath-lib with Apache License 2.0 4 votes vote down vote up
public double[][] solve() {
	// Create interior spatial vector for heat equation
	final int len = numberOfPointsPositive - numberOfPointsNegative - 1;
	final double[] x = new double[len];
	for (int i = 0; i < len; i++) {
		x[i] = (numberOfPointsNegative + 1) * dx + dx * i;
	}

	// Create time vector for heat equation
	final double[] tau = new double[numTimesteps + 1];
	for (int i = 0; i < numTimesteps + 1; i++) {
		tau[i] = i * dtau;
	}

	// Create necessary matrices
	final double[][] C = new double[len][len];
	final double[][] D = new double[len][len];
	for (int i = 0; i < len; i++) {
		for (int j = 0; j < len; j++) {
			if (i == j) {
				C[i][j] = 1 + 2 * theta * kappa;
				D[i][j] = 1 - 2 * (1 - theta) * kappa;
			} else if ((i == j - 1) || (i == j + 1)) {
				C[i][j] = - theta * kappa;
				D[i][j] = (1 - theta) * kappa;
			} else {
				C[i][j] = 0;
				D[i][j] = 0;
			}
		}
	}

	final RealMatrix CMatrix = new Array2DRowRealMatrix(C);
	final RealMatrix DMatrix = new Array2DRowRealMatrix(D);
	final DecompositionSolver solver = new LUDecomposition(CMatrix).getSolver();

	// Create spatial boundary vector
	final double[] b = new double[len];
	Arrays.fill(b, 0);

	// Initialize U
	double[] U = new double[len];
	for (int i = 0; i < U.length; i++) {
		U[i] = u_0(x[i]);
	}
	RealMatrix UVector = MatrixUtils.createColumnRealMatrix(U);

	// Solve system
	for (int m = 0; m < numTimesteps; m++) {
		b[0] = (u_neg_inf(numberOfPointsNegative * dx, tau[m]) * (1 - theta) * kappa)
				+ (u_neg_inf(numberOfPointsNegative * dx, tau[m + 1]) * theta * kappa);
		b[len-1] = (u_pos_inf(numberOfPointsPositive * dx, tau[m]) * (1 - theta) * kappa)
				+ (u_pos_inf(numberOfPointsPositive * dx, tau[m + 1]) * theta * kappa);

		final RealMatrix bVector = MatrixUtils.createColumnRealMatrix(b);
		final RealMatrix constantsMatrix = (DMatrix.multiply(UVector)).add(bVector);
		UVector = solver.solve(constantsMatrix);
	}
	U = UVector.getColumn(0);

	// Transform x to stockPrice and U to optionPrice
	final double[] optionPrice = new double[len];
	final double[] stockPrice = new double[len];
	for (int i = 0; i < len; i++ ){
		optionPrice[i] = U[i] * optionStrike *
				Math.exp(alpha * x[i] + beta * tau[numTimesteps]);
		stockPrice[i] = f_s(x[i]);
	}

	final double[][] stockAndOptionPrice = new double[2][len];
	stockAndOptionPrice[0] = stockPrice;
	stockAndOptionPrice[1] = optionPrice;
	return stockAndOptionPrice;
}