/** * Computes the Jacobian matrix. * * @param params Model parameters at which to compute the Jacobian. * @return the weighted Jacobian: W<sup>1/2</sup> J. * @throws DimensionMismatchException if the Jacobian dimension does not * match problem dimension. * @since 3.1 */ protected RealMatrix computeWeightedJacobian(double[] params) { ++jacobianEvaluations; final DerivativeStructure[] dsPoint = new DerivativeStructure[params.length]; final int nC = params.length; for (int i = 0; i < nC; ++i) { dsPoint[i] = new DerivativeStructure(nC, 1, i, params[i]); } final DerivativeStructure[] dsValue = jF.value(dsPoint); final int nR = getTarget().length; if (dsValue.length != nR) { throw new DimensionMismatchException(dsValue.length, nR); } final double[][] jacobianData = new double[nR][nC]; for (int i = 0; i < nR; ++i) { int[] orders = new int[nC]; for (int j = 0; j < nC; ++j) { orders[j] = 1; jacobianData[i][j] = dsValue[i].getPartialDerivative(orders); orders[j] = 0; } } return weightMatrixSqrt.multiply(MatrixUtils.createRealMatrix(jacobianData)); }
/** * truncated SVD as taken from http://stackoverflow.com/questions/19957076/best-way-to-compute-a-truncated-singular-value-decomposition-in-java */ static double[][] getTruncatedSVD(double[][] matrix, final int k) { SingularValueDecomposition svd = new SingularValueDecomposition(MatrixUtils.createRealMatrix(matrix)); double[][] truncatedU = new double[svd.getU().getRowDimension()][k]; svd.getU().copySubMatrix(0, truncatedU.length - 1, 0, k - 1, truncatedU); double[][] truncatedS = new double[k][k]; svd.getS().copySubMatrix(0, k - 1, 0, k - 1, truncatedS); double[][] truncatedVT = new double[k][svd.getVT().getColumnDimension()]; svd.getVT().copySubMatrix(0, k - 1, 0, truncatedVT[0].length - 1, truncatedVT); RealMatrix approximatedSvdMatrix = (MatrixUtils.createRealMatrix(truncatedU)).multiply( MatrixUtils.createRealMatrix(truncatedS)).multiply(MatrixUtils.createRealMatrix(truncatedVT)); return approximatedSvdMatrix.getData(); }
public static RealMatrix concatHorizontally(final RealMatrix left, final RealMatrix right) { if (left.getRowDimension() != right.getRowDimension()) { throw new IllegalArgumentException( "The matrices must have the same row dimension!"); } final double[][] result = new double[left.getRowDimension()][left.getColumnDimension() + right.getColumnDimension()]; final int lc = left.getColumnDimension(); for (int r = 0; r < left.getRowDimension(); r++) { for (int c = 0; c < left.getColumnDimension(); c++) { result[r][c] = left.getEntry(r, c); } for (int c = 0; c < right.getColumnDimension(); c++) { result[r][lc + c] = right.getEntry(r, c); } } return MatrixUtils.createRealMatrix(result); }
public static RealMatrix concatVertically(final RealMatrix top, final RealMatrix bottom) { if (top.getColumnDimension() != bottom.getColumnDimension()) { throw new IllegalArgumentException( "The matrices must have the same column dimension!"); } final double[][] result = new double[top.getRowDimension() + bottom.getRowDimension()][top.getColumnDimension()]; final int tr = top.getRowDimension(); for (int c = 0; c < top.getColumnDimension(); c++) { for (int r = 0; r < top.getRowDimension(); r++) { result[r][c] = top.getEntry(r, c); } for (int r = 0; r < bottom.getRowDimension(); r++) { result[tr + r][c] = bottom.getEntry(r, c); } } return MatrixUtils.createRealMatrix(result); }
private RealMatrix makeDataMatrix(List<double[]> X, double[] meanX) { if (meanX == null) { return makeDataMatrix(X); } final int m = X.size(); final int n = X.get(0).length; RealMatrix M = MatrixUtils.createRealMatrix(n, m); RealVector mean = MatrixUtils.createRealVector(meanX); int i = 0; for (double[] x : X) { RealVector xi = MatrixUtils.createRealVector(x).subtract(mean); M.setColumnVector(i, xi); i++; } return M; }
/** * Create a new instance from an array of m-dimensional samples, e.g. * samples = {{x1,y1}, {x2,y2},...,{xn,yn}} for a vector of n two-dimensional * samples. * @param samples A vector of length n with m-dimensional samples, i.e. * samples[k][i] represents the i-th component of the k-th sample. * @param diagonalIncrement Quantity added to the diagonal values of the * covariance matrix to avoid singularity. */ public MahalanobisDistance(double[][] samples, double diagonalIncrement) { n = samples.length; m = samples[0].length; if (n < 1 || m < 1) { throw new IllegalArgumentException("dimension less than 1"); } if (diagonalIncrement < 0) { throw new IllegalArgumentException("diagonal increment must be positive"); } mean = makeMeanVector(samples); Covariance cov = new Covariance(samples, BIAS_CORRECTION); RealMatrix S = cov.getCovarianceMatrix(); // condition the covariance matrix to avoid singularity: S = conditionCovarianceMatrix(S); Cov = S.getData(); // get the inverse covariance matrix iCov = MatrixUtils.inverse(S).getData(); // not always symmetric? }
public static void main(String[] args) { MihcConfigData conf = new MihcConfigData(); RealMatrix inverse = MatrixUtils.inverse(MatrixUtils.createRealMatrix(conf.filterNewXeon4fake)); printMat(inverse); // Array2DRowRealMatrix AsnInv = (Array2DRowRealMatrix) MatrixUtils.createRealMatrix(conf.inverse); // printMat(AsnInv); // double[] gain = new double[]{1,1,1,1,2,1}; // for (int i=0; i<gain.length; i++) gain[i] = 1d/gain[i]; // RealMatrix GiiInv = MatrixUtils.createRealDiagonalMatrix(gain); // printMat(GiiInv); // Array2DRowRealMatrix AsnInvNorm = (Array2DRowRealMatrix) AsnInv.multiply(GiiInv); // printMat(AsnInvNorm); // double[] out = new double[gain.length]; // // //double[] in = new double[]{0,000,0,0,100,39}; // double[] in = new double[]{0,0,0,1.554,100,36.232}; // -> 0,0,0,0,100,0 // fastMultiply(AsnInvNorm,in,out); // System.out.println(Arrays.toString(out)); }
@Override public void setValues(double[] y, double[] x) { if (x.length != y.length) { throw new IllegalArgumentException(String.format("The numbers of y and x values must be equal (%d != %d)", y.length, x.length)); } double[][] xData = new double[x.length][]; for (int i = 0; i < x.length; i++) { // the implementation determines how to produce a vector of predictors from a single x xData[i] = xVector(x[i]); } if (logY()) { // in some models we are predicting ln y, so we replace each y with ln y y = Arrays.copyOf(y, y.length); // user might not be finished with the array we were given for (int i = 0; i < x.length; i++) { y[i] = Math.log(y[i]); } } final OLSMultipleLinearRegression ols = new OLSMultipleLinearRegression(); ols.setNoIntercept(true); // let the implementation include a constant in xVector if desired ols.newSampleData(y, xData); // provide the data to the model coef = MatrixUtils.createColumnRealMatrix(ols.estimateRegressionParameters()); // get our coefs last_error_rate = ols.estimateErrorVariance(); Log.d(TAG, getClass().getSimpleName() + " Forecast Error rate: errorvar:" + JoH.qs(last_error_rate, 4) + " regssionvar:" + JoH.qs(ols.estimateRegressandVariance(), 4) + " stderror:" + JoH.qs(ols.estimateRegressionStandardError(), 4)); }
public void render(World world, RenderCallback callback) { new BukkitRunnable() { public void run() { long msBegin = System.currentTimeMillis(); renderNode(world, scene, MatrixUtils.createRealIdentityMatrix(4)); long msEnd = System.currentTimeMillis(); System.out.println("Filling calculated (" + (msEnd - msBegin) + "ms)"); if (callback != null) renderer.addCallback(callback); } }.runTaskAsynchronously(plugin); }
public List<RealVector> getVectorVarByName(String name) { String varName = "V_" + name; JsonNode obj = redisService.getValue(spaceIdentifier, varName); int size = obj.get("size").asInt(); int dim = obj.get("dim").asInt(); double initial = obj.get("initial").asDouble(); boolean randomize = obj.get("randomize").asBoolean(); boolean normalize = obj.get("normalize").asBoolean(); List<RealVector> vars = new ArrayList<>(size); for (int i=0; i<size; i++) { RealVector var = MatrixUtils.createRealVector(new double[dim]); initializeVector(var, initial, randomize, normalize); vars.add(var); } String varIdxName = "IDX_V_" + name + "_"; List<String> keys = redisService.keysWithPrefixPattern(spaceIdentifier, varIdxName); List<JsonNode> values = redisService.bulkGet(keys); for (JsonNode one : values) { setValue(vars, one, dim); } return vars; }
final public void ensureVectorVar(String name, int size, int dim, double initial, boolean randomize, boolean normalize) { writeLock.lock(); try { int curSize = vectorVars.get(name).size(); if (curSize < size) { for (int i=curSize; i<size; i++) { RealVector vec = MatrixUtils.createRealVector(new double[dim]); initializeVector(vec, initial, randomize, normalize); vectorVars.get(name).add(vec); } } curSize = readLocks.size(); SpaceUtilities.fillReadWriteLocks(readLocks, writeLocks, curSize, size); } finally { writeLock.unlock(); } }
public List<StochasticOracle> getStochasticOracle(List<LearningInstance> instances) { List<StochasticOracle> oracles = new ArrayList<>(instances.size()); for (LearningInstance inIns : instances) { SVDFeatureInstance ins = (SVDFeatureInstance) inIns; StochasticOracle orc = new StochasticOracle(); RealVector ufactSum = MatrixUtils.createRealVector(new double[factDim]); RealVector ifactSum = MatrixUtils.createRealVector(new double[factDim]); double pred = predict(ins, orc, ufactSum, ifactSum); RealVector leftGrad = ifactSum; RealVector rightGrad = ufactSum; for (int i = 0; i < ins.ufeas.size(); i++) { orc.addVectorOracle(SVDFeatureKey.FACTORS.get(), ins.ufeas.get(i).getIndex(), leftGrad.mapMultiply(ins.ufeas.get(i).getValue())); } for (int i = 0; i < ins.ifeas.size(); i++) { orc.addVectorOracle(SVDFeatureKey.FACTORS.get(), ins.ifeas.get(i).getIndex(), rightGrad.mapMultiply(ins.ifeas.get(i).getValue())); } orc.setValues(pred, ins.label, ins.weight); oracles.add(orc); } return oracles; }
/** * If we rotate the covariance matrix by the angle delta, we should get a diagonal matrix. */ @Test public void testDelta() { assertTrue("Covariance matrix should not be diagonal", covarianceMatrix.getEntry(0, 1) != 0 && covarianceMatrix.getEntry(1, 0) != 0); double delta = poser.calculateDelta(eig); double[][] rot = {{Math.cos(delta), Math.sin(delta)}, {-Math.sin(delta), Math.cos(delta)} }; RealMatrix rotMatrix = MatrixUtils.createRealMatrix(rot); RealMatrix b = (rotMatrix.multiply(covarianceMatrix)).multiply(rotMatrix.transpose()); //check if non diagonal elements are close to zero. assertEquals(b.getEntry(1, 0), 0.0, EPSILON); assertEquals(b.getEntry(0, 1), 0.0, EPSILON); }
public ImagePlus applyStackManifold(ImageStack imStack, ImagePlus manifold){ int dimW = imStack.getWidth(); int dimH = imStack.getHeight(); RealMatrix projMnold = MatrixUtils.createRealMatrix(SME_ENS_Utils.convertFloatMatrixToDoubles(manifold.getProcessor().getFloatArray(),dimW,dimH)).transpose(); for(int j=0;j<dimH;j++){ for(int i=0;i<dimW;i++){ int zIndex = ((int) Math.round(stackSize*(projMnold.getEntry(j,i)/255))); projMnold.setEntry (j,i,imStack.getVoxel(i,j,zIndex-1)); } } float[][] mfoldFlaot = SME_ENS_Utils.convertDoubleMatrixToFloat(projMnold.transpose().getData(),dimW,dimH); ImagePlus smeManifold = new ImagePlus("",((ImageProcessor) new FloatProcessor(mfoldFlaot))); return(smeManifold); }
public static RealMatrix padSymetricMatrix(RealMatrix inMatrix, Boolean transMatr){ RealMatrix padedMatrix = null; RealMatrix templateMatrix = null; //transpose if necessary if(transMatr) { templateMatrix = inMatrix.copy().transpose(); }else{ templateMatrix = inMatrix.copy(); } padedMatrix = MatrixUtils.createRealMatrix(templateMatrix.getRowDimension()+2, templateMatrix.getColumnDimension()); int iPadStart = 1,iPadEnd = padedMatrix.getRowDimension()-1; padedMatrix.setRowVector(0,templateMatrix.getRowVector(0)); padedMatrix.setRowVector(iPadEnd,templateMatrix.getRowVector(templateMatrix.getRowDimension()-1)); // symetrical padding for(int i=iPadStart;i<iPadEnd;i++){ padedMatrix.setRowVector(i,templateMatrix.getRowVector(i-1)); } return(padedMatrix); }
public static ImageStack repmatMatrixVar(RealMatrix inMatrix, ImageStack base){ //varold2=sum((base-repmat(Mold,[1 1 8])).^2,3); final int DIMZ = 8; int nrowsMat = inMatrix.getRowDimension(); int ncolsMat = inMatrix.getColumnDimension(); ImageStack baseMatrix = new ImageStack(ncolsMat,nrowsMat); for(int inz=0;inz<DIMZ;inz++){ RealMatrix currentSlice = MatrixUtils.createRealMatrix( convertFloatMatrixToDoubles(base.getProcessor(inz+1).getFloatArray(), ncolsMat,nrowsMat)); currentSlice = currentSlice.transpose(); RealMatrix tmpSlice = currentSlice.subtract(inMatrix); tmpSlice = realmatrixDoublepow(tmpSlice,2); tmpSlice = tmpSlice.transpose(); baseMatrix.addSlice((ImageProcessor) new FloatProcessor( SME_ENS_Utils.convertDoubleMatrixToFloat( tmpSlice.getData(),ncolsMat,nrowsMat ))); } return(baseMatrix); }
public static RealMatrix elementMultiply(RealMatrix inMatrix1,RealMatrix inMatrix2,Boolean absVal){ int nrows = inMatrix1.getRowDimension(); int ncols = inMatrix1.getColumnDimension(); RealMatrix retuRealMatrix = MatrixUtils.createRealMatrix(nrows,ncols); for(int i=0;i<nrows;i++){ for(int j=0;j<ncols;j++){ if(absVal) { retuRealMatrix.setEntry(i, j, Math.abs(inMatrix1.getEntry(i, j) * inMatrix2.getEntry(i, j))); }else { retuRealMatrix.setEntry(i, j, inMatrix1.getEntry(i, j) * inMatrix2.getEntry(i, j)); } } } return(retuRealMatrix); }
public static RealMatrix getMaxProjectionIndex(ImageStack imageStack){ double[][] maxIndex = new double[imageStack.getProcessor(1).getHeight()] [imageStack.getProcessor(1).getWidth()]; for(int pixIndexI=0;pixIndexI<imageStack.getProcessor(1).getHeight();pixIndexI++){ for(int pixIndexJ=0;pixIndexJ<imageStack.getProcessor(1).getWidth();pixIndexJ++){ double maxZval = Double.MIN_VALUE; for(int pixIndexZ=0;pixIndexZ<imageStack.getSize();pixIndexZ++){ if(imageStack.getVoxel(pixIndexJ,pixIndexI,pixIndexZ)>maxZval){ maxIndex[pixIndexI][pixIndexJ] = pixIndexZ; maxZval = imageStack.getVoxel(pixIndexJ,pixIndexI,pixIndexZ); } } } } return(MatrixUtils.createRealMatrix(maxIndex)); }
public static RealMatrix getMinProjectionIndex(ImageStack imageStack){ int colDim = imageStack.getProcessor(1).getWidth(); int rowDim = imageStack.getProcessor(1).getHeight(); int zDim = imageStack.getSize(); double[][] maxIndex = new double[rowDim][colDim]; for(int pixIndexI=0;pixIndexI<rowDim;pixIndexI++){ for(int pixIndexJ=0;pixIndexJ<colDim;pixIndexJ++){ double minZval = Double.MAX_VALUE; for(int pixIndexZ=0;pixIndexZ<zDim;pixIndexZ++){ if(imageStack.getVoxel(pixIndexJ,pixIndexI,pixIndexZ)<minZval){ maxIndex[pixIndexI][pixIndexJ] = pixIndexZ; minZval = imageStack.getVoxel(pixIndexJ,pixIndexI,pixIndexZ); } } } } return(MatrixUtils.createRealMatrix(maxIndex)); }
public static RealVector realmat2vector(RealMatrix inMatrix, int dimWalk){ RealVector retVector = null; int ncols = inMatrix.getColumnDimension(); int nrows = inMatrix.getRowDimension(); switch (dimWalk){ case 1: { retVector = MatrixUtils.createRealVector(inMatrix.getRow(0)); for(int i=1;i<nrows;i++){ retVector = retVector.append(inMatrix.getRowVector(i)); } } default: { retVector = MatrixUtils.createRealVector(inMatrix.getColumn(0)); for(int i=1;i<ncols;i++){ retVector = retVector.append(inMatrix.getColumnVector(i)); } } } return(retVector); }
public static RealVector realmatSelectVector(RealMatrix inMatrix,RealMatrix selectMatrix, double valueSelect){ RealVector retVector = MatrixUtils.createRealVector(new double[0]); int ncols = inMatrix.getColumnDimension(); int nrows = inMatrix.getRowDimension(); for(int j=0;j<ncols;j++){ for(int i=0;i<nrows;i++){ if(inMatrix.getEntry(i,j)==valueSelect) { retVector = retVector.append(selectMatrix.getEntry(i,j)); } } } return(retVector); }
/** * Apply the SME_ENS_Kmeans_Engine for segmentation * * @param numClust_ : number of clusters * @param result_fft : matrix that contains * the results after applying the FFT_1D = width is equal to the number of stacks in the image * and length of result_fft is equal to the number of pixels of the image */ public void Kmeans_(int numClust_, double[][] result_fft) { int m; int slice_num = sme_pluginGetManifold.getStack().getSize(); int threadcount = 5; final int numClust = numClust_; final double[][] coordClust = result_fft; List<SME_ENS_PixelPoints> clusterInput = new ArrayList<>(result_fft.length); for (int i=0;i<result_fft.length;i++) { clusterInput.add(new SME_ENS_PixelPoints(MatrixUtils.createRealVector(result_fft[i]),i)); } clusterer = new KMeansPlusPlusClusterer<SME_ENS_PixelPoints>(numClust_, 10); clusterResults = clusterer.cluster(clusterInput); getClassDetails(); /* // output the clusters for (int i=0; i<clusterResults.size(); i++) { System.out.println("Cluster " + i); for (SME_ENS_PixelPoints locationWrapper : clusterResults.get(i).getPoints()) System.out.println(locationWrapper.getLocation()); System.out.println(); }*/ //SME_ENS_Kmeans_Engine OBSKmeans_Niki = new SME_ENS_Kmeans_Engine(result_fft, numClust_, false); //OBSKmeans_Niki.calculateClusters(); sme_pluginGetManifold.setKmeanCentroids(classCenters); sme_pluginGetManifold.setKmeansLabels(classLabels); for (m = 0; m < slice_num; m++) { sme_pluginGetManifold.setMean0(sme_pluginGetManifold.getMean0() + (float) sme_pluginGetManifold.getKmeanCentroids()[0][m]); sme_pluginGetManifold.setMean1(sme_pluginGetManifold.getMean1() + (float) sme_pluginGetManifold.getKmeanCentroids()[1][m]); sme_pluginGetManifold.setMean2(sme_pluginGetManifold.getMean2() + (float) sme_pluginGetManifold.getKmeanCentroids()[2][m]); } }
public void getClassDetails(){ // Initialize class centers and class labels to 0 classCenters = MatrixUtils.createRealMatrix(3,((SME_ENS_PixelPoints)(clusterResults.get(0).getPoints().get(0))).getLocation().getDimension()).getData(); classLabels = MatrixUtils.createRealVector(new double[nmbPoints]).toArray(); for(int i=0;i<clusterResults.size();i++){ for (SME_ENS_PixelPoints locationWrapper : clusterResults.get(i).getPoints()) { classCenters[i]=MatrixUtils.createRealVector(classCenters[i]).add(locationWrapper.getLocation()).toArray(); // update pixel label classLabels[locationWrapper.getIndexPixel()] = i; } classCenters[i]=MatrixUtils.createRealVector(classCenters[i]).mapDivideToSelf((double)clusterResults.get(i).getPoints().size()).toArray(); } }
public void initStepEnergyOpt(){ foregroundPixelVal = MatrixUtils.createRealVector(new double[1]); Boolean vecInitialised = Boolean.FALSE; for(int i=0;i<edgeflag2.getRowDimension();i++){ for(int j=0;j<edgeflag2.getColumnDimension();j++){ if(edgeflag2.getEntry(i,j)>0){ if(!vecInitialised){ foregroundPixelVal.setEntry(0,idmax.getEntry(i,j)); vecInitialised = Boolean.TRUE; }else { foregroundPixelVal = foregroundPixelVal.append(idmax.getEntry(i, j)); } } } } KE= foregroundPixelVal.getMaxValue()-foregroundPixelVal.getMinValue()+1; step=KE/100; //step = sme_pluginGetManifold.getStack1().getSize()/(double)stepNumber; }
public void setOutputSME(Boolean showResult){ double norm_factor = sme_pluginGetManifold.getStack1().getSize(); int dimW = sme_pluginGetManifold.getStack1().getWidth(); int dimH = sme_pluginGetManifold.getStack1().getHeight(); ImageStack rawStack = sme_pluginGetManifold.getStack(); RealMatrix projMnold = MatrixUtils.createRealMatrix(dimH,dimW); for(int i=0;i<dimH;i++){ for(int j=0;j<dimW;j++){ int zIndex = ((int) Math.round(idmaxk.getEntry(i,j)))-1; projMnold.setEntry (i,j,rawStack.getVoxel(j,i,zIndex)); } } float[][] mfoldFlaot = SME_ENS_Utils.convertDoubleMatrixToFloat(projMnold.transpose().getData(),dimW,dimH); ImagePlus smeManifold = new ImagePlus("ProjectionSME",((ImageProcessor) new FloatProcessor(mfoldFlaot))); sme_pluginGetManifold.setSmeImage(smeManifold); if(showResult) sme_pluginGetManifold.getSmeImage().show(); }
/** * Get the covariance matrix. * @return covariance matrix */ public RealMatrix getResult() { int dimension = sums.length; RealMatrix result = MatrixUtils.createRealMatrix(dimension, dimension); if (n > 1) { double c = 1.0 / (n * (isBiasCorrected ? (n - 1) : n)); int k = 0; for (int i = 0; i < dimension; ++i) { for (int j = 0; j <= i; ++j) { double e = c * (n * productsSums[k++] - sums[i] * sums[j]); result.setEntry(i, j, e); result.setEntry(j, i, e); } } } return result; }
/** * Translate the algebraic form of the ellipsoid to the center. * * @param center * vector containing the center of the ellipsoid. * @param a * the algebraic form of the polynomial. * @return the center translated form of the algebraic ellipsoid. */ private RealMatrix translateToCenter(RealVector center, RealMatrix a) { // Form the corresponding translation matrix. RealMatrix t = MatrixUtils.createRealIdentityMatrix(4); RealMatrix centerMatrix = new Array2DRowRealMatrix(1, 3); centerMatrix.setRowVector(0, center); t.setSubMatrix(centerMatrix.getData(), 3, 0); // Translate to the center. RealMatrix r = t.multiply(a).multiply(t.transpose()); return r; }
public Transition( final PageRater rater, final int numberOfPages, final Stream<PagesLink> pagesLinkStream) { final int[] degree = new int[numberOfPages]; final int[][] counts = new int[numberOfPages][numberOfPages]; pagesLinkStream.forEach( (pl) -> { final int hostPage = pl.getHostPage(); final int linkReferToPage = pl.getLinkReferToPage(); degree[hostPage]++; counts[hostPage][linkReferToPage]++; } ); matrix = MatrixUtils.createRealMatrix(numberOfPages, numberOfPages); for (int i = 0; i < numberOfPages; i++) { for (int j = 0; j < numberOfPages; j++) { matrix.addToEntry(i, j, rater.calculateRate(counts[i][j], degree[i])); } } }
@Test public void testMath891Matrix() { final double[] xArray = new double[] { Double.NaN, 1.9, 2, 100, 3 }; final double[] yArray = new double[] { 10, 2, 10, Double.NaN, 4 }; RealMatrix matrix = MatrixUtils.createRealMatrix(xArray.length, 2); for (int i = 0; i < xArray.length; i++) { matrix.addToEntry(i, 0, xArray[i]); matrix.addToEntry(i, 1, yArray[i]); } // compute correlation NaturalRanking ranking = new NaturalRanking(NaNStrategy.REMOVED); SpearmansCorrelation spearman = new SpearmansCorrelation(matrix, ranking); Assert.assertEquals(0.5, spearman.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE); }
/** * Verifies that setting X, Y and covariance separately has the same effect as newSample(X,Y,cov). */ @Test public void testNewSample2() { double[] y = new double[] {1, 2, 3, 4}; double[][] x = new double[][] { {19, 22, 33}, {20, 30, 40}, {25, 35, 45}, {27, 37, 47} }; double[][] covariance = MatrixUtils.createRealIdentityMatrix(4).scalarMultiply(2).getData(); GLSMultipleLinearRegression regression = new GLSMultipleLinearRegression(); regression.newSampleData(y, x, covariance); RealMatrix combinedX = regression.getX().copy(); RealVector combinedY = regression.getY().copy(); RealMatrix combinedCovInv = regression.getOmegaInverse(); regression.newXSampleData(x); regression.newYSampleData(y); Assert.assertEquals(combinedX, regression.getX()); Assert.assertEquals(combinedY, regression.getY()); Assert.assertEquals(combinedCovInv, regression.getOmegaInverse()); }
public MultivariateTDistribution(RealVector mean, RealMatrix covarianceMatrix, double degreesOfFreedom) { this.mean = mean; if (mean.getDimension() > 1) { this.precisionMatrix = MatrixUtils.blockInverse(covarianceMatrix, (-1 + covarianceMatrix.getColumnDimension()) / 2); } else { this.precisionMatrix = MatrixUtils.createRealIdentityMatrix(1).scalarMultiply(1. / covarianceMatrix.getEntry(0, 0)); } this.dof = degreesOfFreedom; this.D = mean.getDimension(); double determinant = new LUDecomposition(covarianceMatrix).getDeterminant(); this.multiplier = Math.exp(Gamma.logGamma(0.5 * (D + dof)) - Gamma.logGamma(0.5 * dof)) / Math.pow(Math.PI * dof, 0.5 * D) / Math.pow(determinant, 0.5); }
@Test public void layerpropagateTest() throws Exception { FeedForwardNet net = getNetWith1Weights(); SingleThreadPropagation prop = new SingleThreadPropagationTest(); prop.setNetWork(net); prop.setEta(10); SingleThreadCalculation calc = new SingleThreadCalculation(net); Complex[] in = {new Complex(1),new Complex(1)}; Complex[] tar = {new Complex(1)}; FieldVector<Complex> input = MatrixUtils.createFieldVector(in); FieldVector<Complex> target = MatrixUtils.createFieldVector(tar); FieldVector<Complex> output = calc.calculate(input); FieldVector<Complex> error = target.subtract(output); prop.propagate(error, calc.getLayerResults()); assertEquals(1.161527544, net.getLayers().get(1).getNeurons().get(0).getOutputs().get(0).getWeight().getReal(), 0.00001); assertEquals(1.01925455, net.getLayers().get(0).getNeurons().get(0).getOutputs().get(0).getWeight().getReal(), 0.00001); }
public static RealMatrix createHankelMatrix(RealMatrix data, int windowSize) { int n = data.getRowDimension(); int m = data.getColumnDimension(); int k = n - windowSize + 1; RealMatrix res = MatrixUtils.createRealMatrix(k, m * windowSize); double[] buffer = {}; for (int i = 0; i < n; ++i) { double[] row = data.getRow(i); buffer = ArrayUtils.addAll(buffer, row); if (i >= windowSize - 1) { RealMatrix mat = MatrixUtils.createRowRealMatrix(buffer); res.setRowMatrix(i - windowSize + 1, mat); buffer = ArrayUtils.subarray(buffer, m, buffer.length); } } return res; }
public static RealMatrix averageHankelMatrix(RealMatrix hankelMat, int windowSize) { int k = hankelMat.getRowDimension(); int m = hankelMat.getColumnDimension() / windowSize; int n = k + windowSize - 1; RealMatrix result = MatrixUtils.createRealMatrix(n, m); for (int t = 0; t < n; ++t) { int i = (t < windowSize) ? 0 : (t - windowSize + 1); int j = (t < windowSize) ? t : (windowSize - 1); int counter = 0; for (; i < k && j >= 0; ++i, --j, ++counter) { for (int h = 0; h < m; ++h) { result.addToEntry(t, h, hankelMat.getEntry(i, j * m + h)); } } for (int h = 0; h < m; ++h) { result.setEntry(t, h, result.getEntry(t, h) / counter); } } return result; }
@Test public void testStack() { RealMatrix one = TransformUtil.translationMatrix(1, 0, 0); RealMatrix two = TransformUtil.translationMatrix(0, 1, 0); RealMatrix three = TransformUtil.translationMatrix(0, 0, 1); ms.loadMatrix(one); ms.pushMatrix(); ms.loadMatrix(two); ms.pushMatrix(); ms.loadIdentity(); ms.pushMatrix(); ms.loadMatrix(three); ms.pushMatrix(); ms.loadIdentity(); assertThat(ms.getMatrix()).isEqualTo(MatrixUtils.createRealIdentityMatrix(4)); ms.popMatrix(); assertThat(ms.getMatrix()).isEqualTo(three); ms.popMatrix(); assertThat(ms.getMatrix()).isEqualTo(MatrixUtils.createRealIdentityMatrix(4)); ms.popMatrix(); assertThat(ms.getMatrix()).isEqualTo(two); ms.popMatrix(); assertThat(ms.getMatrix()).isEqualTo(one); }
/** * Calculate inverse matrix * * @param a The matrix * @return Inverse matrix array */ public static Array inv(Array a) { double[][] aa = (double[][]) ArrayUtil.copyToNDJavaArray(a); RealMatrix matrix = new Array2DRowRealMatrix(aa, false); RealMatrix invm = MatrixUtils.inverse(matrix); if (invm == null) { return null; } int m = invm.getRowDimension(); int n = invm.getColumnDimension(); Array r = Array.factory(DataType.DOUBLE, new int[]{m, n}); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { r.setDouble(i * n + j, invm.getEntry(i, j)); } } return r; }