List of usage examples for org.apache.commons.math3.linear ArrayRealVector ArrayRealVector
public ArrayRealVector(ArrayRealVector v) throws NullArgumentException
From source file:edu.oregonstate.eecs.mcplan.ml.LinearDiscriminantAnalysis.java
/** * @param data The elements of 'data' will be modified. * @param label/*from w ww . jav a 2 s . c om*/ * @param Nclasses * @param shrinkage_intensity */ public LinearDiscriminantAnalysis(final ArrayList<double[]> data, final int[] label, final int Nclasses, final double shrinkage) { assert (data.size() == label.length); final int Ndata = data.size(); final int Ndim = data.get(0).length; // Partition data by class final ArrayList<ArrayList<double[]>> classes = new ArrayList<ArrayList<double[]>>(Nclasses); for (int i = 0; i < Nclasses; ++i) { classes.add(new ArrayList<double[]>()); } for (int i = 0; i < data.size(); ++i) { classes.get(label[i]).add(data.get(i)); } // Mean center the data final VectorMeanVarianceAccumulator mv = new VectorMeanVarianceAccumulator(Ndim); for (int i = 0; i < Ndata; ++i) { mv.add(data.get(i)); } mean = mv.mean(); // Subtract global mean for (final double[] x : data) { Fn.vminus_inplace(x, mean); } // Calculate class means and covariances final double[][] class_mean = new double[Nclasses][Ndim]; final RealMatrix[] class_cov = new RealMatrix[Nclasses]; for (int i = 0; i < Nclasses; ++i) { final ArrayList<double[]> Xc = classes.get(i); final VectorMeanVarianceAccumulator mv_i = new VectorMeanVarianceAccumulator(Ndim); final StorelessCovariance cov = new StorelessCovariance(Ndim); for (int j = 0; j < Xc.size(); ++j) { final double[] x = Xc.get(j); mv_i.add(x); cov.increment(x); } class_mean[i] = mv_i.mean(); class_cov[i] = cov.getCovarianceMatrix(); } // Between-class scatter. // Note that 'data' is mean-centered, so the global mean is 0. RealMatrix Sb_builder = new Array2DRowRealMatrix(Ndim, Ndim); for (int i = 0; i < Nclasses; ++i) { final RealVector mu_i = new ArrayRealVector(class_mean[i]); final RealMatrix xxt = mu_i.outerProduct(mu_i); Sb_builder = Sb_builder.add(xxt.scalarMultiply(classes.get(i).size() / ((double) Ndata - 1))); } this.Sb = Sb_builder; Sb_builder = null; // Within-class scatter with shrinkage estimate: // Sw = (1.0 - shrinkage) * \sum Sigma_i + shrinkage * I RealMatrix Sw_builder = new Array2DRowRealMatrix(Ndim, Ndim); for (int i = 0; i < Nclasses; ++i) { final RealMatrix Sigma_i = class_cov[i]; final RealMatrix scaled = Sigma_i.scalarMultiply((1.0 - shrinkage) * (classes.get(i).size() - 1)); Sw_builder = Sw_builder.add(scaled); } for (int i = 0; i < Ndim; ++i) { Sw_builder.setEntry(i, i, Sw_builder.getEntry(i, i) + shrinkage); } this.Sw = Sw_builder; Sw_builder = null; // Invert Sw System.out.println("[LDA] Sw inverse"); final RealMatrix Sw_inv = new LUDecomposition(Sw).getSolver().getInverse(); final RealMatrix F = Sw_inv.multiply(Sb); System.out.println("[LDA] Eigendecomposition"); eigenvalues = new double[Nclasses - 1]; eigenvectors = new ArrayList<RealVector>(Nclasses - 1); final EigenDecomposition evd = new EigenDecomposition(F); for (int j = 0; j < Nclasses - 1; ++j) { final double eigenvalue = evd.getRealEigenvalue(j); eigenvalues[j] = eigenvalue; // final double scale = 1.0 / Math.sqrt( eigenvalue ); // eigenvectors.add( evd.getEigenvector( j ).mapMultiply( scale ) ); eigenvectors.add(evd.getEigenvector(j)); } }
From source file:com.datumbox.framework.common.dataobjects.MatrixDataframe.java
/** * Parses a testing dataset and converts it to MatrixDataframe by using an already existing mapping between feature names and column ids. Typically used * to parse the testing or validation dataset. * /*ww w . ja v a 2 s . c o m*/ * @param newData * @param recordIdsReference * @param featureIdsReference * @return */ public static MatrixDataframe parseDataset(Dataframe newData, Map<Integer, Integer> recordIdsReference, Map<Object, Integer> featureIdsReference) { if (featureIdsReference.isEmpty()) { throw new IllegalArgumentException("The featureIdsReference map should not be empty."); } int n = newData.size(); int d = featureIdsReference.size(); MatrixDataframe m = new MatrixDataframe(new OpenMapRealMatrix(n, d), new ArrayRealVector(n)); if (newData.isEmpty()) { return m; } boolean extractY = (newData.getYDataType() == TypeInference.DataType.NUMERICAL); boolean addConstantColumn = featureIdsReference.containsKey(Dataframe.COLUMN_NAME_CONSTANT); int rowId = 0; for (Map.Entry<Integer, Record> e : newData.entries()) { Integer rId = e.getKey(); Record r = e.getValue(); if (recordIdsReference != null) { recordIdsReference.put(rId, rowId); } if (extractY) { m.Y.setEntry(rowId, TypeInference.toDouble(r.getY())); } if (addConstantColumn) { m.X.setEntry(rowId, 0, 1.0); //add the constant column } for (Map.Entry<Object, Object> entry : r.getX().entrySet()) { Object feature = entry.getKey(); Double value = TypeInference.toDouble(entry.getValue()); if (value != null) { Integer featureId = featureIdsReference.get(feature); if (featureId != null) {//if the feature exists in our database m.X.setEntry(rowId, featureId, value); } } //else the X matrix maintains the 0.0 default value } ++rowId; } return m; }
From source file:fi.smaa.jsmaa.model.MultivariateGaussianCriterionMeasurementTest.java
@Test public void testModifyAlternatives() { m.setCovarianceMatrix(new Array2DRowRealMatrix( new double[][] { { 2.0, 0.5, 0.0 }, { 0.5, 2.0, 0.0 }, { 0.0, 0.0, 2.0 } })); m.setMeanVector(new ArrayRealVector(new double[] { 25.3, 2.1, -3 })); Alternative alt = new Alternative("Slackware"); m.addAlternative(alt);//w w w . j a v a 2s. co m RealMatrix sigma = new Array2DRowRealMatrix(new double[][] { { 2.0, 0.5, 0.0, 0.0 }, { 0.5, 2.0, 0.0, 0.0 }, { 0.0, 0.0, 2.0, 0.0 }, { 0.0, 0.0, 0.0, 1.0 } }); RealVector mu = new ArrayRealVector(new double[] { 25.3, 2.1, -3, 0.0 }); alternatives.add(alt); assertEquals(alternatives, m.getAlternatives()); assertEquals(mu, m.getMeanVector()); assertEquals(sigma, m.getCovarianceMatrix()); Alternative del = alternatives.get(1); alternatives.remove(del); m.deleteAlternative(del); assertEquals(alternatives, m.getAlternatives()); sigma = new Array2DRowRealMatrix( new double[][] { { 2.0, 0.0, 0.0 }, { 0.0, 2.0, 0.0 }, { 0.0, 0.0, 1.0 } }); mu = new ArrayRealVector(new double[] { 25.3, -3, 0.0 }); assertEquals(mu, m.getMeanVector()); assertEquals(sigma, m.getCovarianceMatrix()); List<Alternative> reordered = Arrays.asList(alternatives.get(1), alternatives.get(2), alternatives.get(0)); m.setCovarianceMatrix(new Array2DRowRealMatrix( new double[][] { { 2.0, 0.5, 0.0 }, { 0.5, 2.0, -0.2 }, { 0.0, -0.2, 1.0 } })); m.reorderAlternatives(reordered); assertEquals(reordered, m.getAlternatives()); sigma = new Array2DRowRealMatrix( new double[][] { { 2.0, -0.2, 0.5 }, { -0.2, 1.0, 0.0 }, { 0.5, 0.0, 2.0 } }); mu = new ArrayRealVector(new double[] { -3, 0.0, 25.3 }); assertEquals(mu, m.getMeanVector()); assertEquals(sigma, m.getCovarianceMatrix()); // FIXME: define what events should be fired and when. }
From source file:com.github.kingtim1.jmdp.discounted.MatrixInversePolicyEvaluation.java
/** * Returns a vector containing the expected reinforcement with respect to * the policy at each state.//w ww.j a v a 2 s .c o m * * @param states * a list of states (this determines the order of the * reinforcements in the returned vector) * @return a vector containing the immediate expected reinforcement at each * state */ private RealVector rPi(StationaryPolicy<S, A> policy, List<S> states) { int n = _smdp.numberOfStates(); double[] rp = new double[n]; // Fill the vector for (int i = 0; i < n; i++) { rp[i] = rPi(policy, states, i); } return new ArrayRealVector(rp); }
From source file:edu.oregonstate.eecs.mcplan.ml.InformationTheoreticMetricLearner.java
/** * Execute the algorithm./*from w w w .java2s. c o m*/ * @see java.lang.Runnable#run() */ @Override public void run() { System.out.println("\tITML run()"); final RealMatrix A = A0_.copy(); final int[] idx = Fn.range(0, Nc_); int iter_count = 0; final int logging_interval = 1; double cumulative_update = 0.0; while (iter_count++ < iteration_limit_) { if (iter_count % logging_interval == 0) { System.out.println("\tIteration " + iter_count); } Fn.shuffle(rng_, idx); double update_magnitude = 0.0; for (int c = 0; c < Nc_; ++c) { final int[] constraint; final RealVector xdiff; final int delta; if (c < S_.size()) { // constraint = S_.get( c ); xdiff = new ArrayRealVector(S_.get(c)); delta = 1; } else { // constraint = D_.get( c - S_.size() ); xdiff = new ArrayRealVector(D_.get(c - S_.size())); delta = -1; } // final int i = constraint[0]; // final int j = constraint[1]; // final RealVector xdiff = X_.get( i ).subtract( X_.get( j ) ); // final double p = xdiff.dotProduct( A.operate( xdiff ) ); // if( p == 0.0 ) { // System.out.println( "! p == 0.0" ); // } // if( xi_[c] == 0.0 ) { // System.out.println( "! xi_[c] == 0.0" ); // } final double p = HilbertSpace.inner_prod(xdiff, A, xdiff); final double alpha; if (p == 0.0) { alpha = lambda_[c]; } else { alpha = Math.min(lambda_[c], (delta / 2.0) * ((1.0 / p) - (gamma_ / xi_[c]))); } final double beta = (delta * alpha) / (1 - delta * alpha * p); xi_[c] = (gamma_ * xi_[c]) / (gamma_ + delta * alpha * xi_[c]); lambda_[c] -= alpha; // This implements: A += beta * A xdiff xdiff^T A final RealVector Ax = A.operate(xdiff); // final RealMatrix outer_prod = Ax.outerProduct( Ax ); for (int row = 0; row < A.getRowDimension(); ++row) { final double axi = Ax.getEntry(row); for (int col = 0; col < A.getColumnDimension(); ++col) { final double a = axi * Ax.getEntry(col); A.addToEntry(row, col, a * beta); } } // final RealMatrix outer_prod = xdiff.outerProduct( xdiff ); // final RealMatrix update = A.multiply( outer_prod ).multiply( A ).scalarMultiply( beta ); // A = A.add( update ); update_magnitude += alpha * alpha; //update.getFrobeniusNorm(); } cumulative_update += update_magnitude; if (iter_count % logging_interval == 0) { System.out.println("\tupdate = " + (cumulative_update / logging_interval)); cumulative_update = 0.0; } // Declare convergence if all updates were small. if (Math.sqrt(update_magnitude) < convergence_tolerance_) { break; } } A_ = A; // A_ = MatrixAlgorithms.makePositiveDefinite( A, 1e-4 ); // System.out.println( "Metric:" ); // for( int i = 0; i < A_.getRowDimension(); ++i ) { // System.out.println( A_.getRowVector( i ) ); // } // Check for positive-definiteness // final EigenDecomposition eig = new EigenDecomposition( A_ ); // final double det = eig.getDeterminant(); // assert( det > 0.0 ); }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.DifferentialEvolutionMinimizer.java
/** * Performs a minimization of a function starting with a given population. * //from www . ja v a 2 s . c o m * @param population The population of parameters to start from, one population entry per row, one parameter per column. * @param f The function to be minimized. * @param parameterLowerBounds The lower bounds of each parameter. This must have the same size as the column dimension of the population. Generated parameter values less than these values will be discarded. * @param parameterUpperBounds The upper bounds of each paraemter. This must have the same size as the column dimension of the population. Generated parameter values greater than these values will be discarded. * @param populationSize The size of the population of parameters sets. This must be equal to the row dimension of the population. * @param scaleFactor Factor controlling the scale of crossed over entries during crossover events. * @param maxIterations The maximum number of iterations to allow before returning a result. * @param crossoverFrequency The frequency of crossover from 0 to 1. At any given parameter, this is the probability of initiating a crossover as well as the probability of ending one after it has started. * @param tol Relative function value tolerance controlling termination; if the maximal and minimal population values differ by less than this factor times the maximal value, optimization will terminate. * @return The parameter values at the minimal function value found. */ public RealVector minimizeWithPopulation(RealMatrix population, ObjectiveFunction f, RealVector parameterLowerBounds, RealVector parameterUpperBounds, int populationSize, double scaleFactor, int maxIterations, double crossoverFrequency, double tol) { int numberOfParameters = parameterLowerBounds.getDimension(); double currMinValue = Double.MAX_VALUE; double currMaxValue = -1.0 * Double.MAX_VALUE; int iterationCounter = maxIterations; double mutationProb = 0.01; // int totalIterations =0; RealVector values = new ArrayRealVector(populationSize); boolean[] valuesChanged = new boolean[populationSize]; java.util.Arrays.fill(valuesChanged, true); computeValues(f, population, values, valuesChanged); RealVector newVec = new ArrayRealVector(numberOfParameters); RealMatrix newPopulation = new Array2DRowRealMatrix(populationSize, numberOfParameters); while (iterationCounter > 0) { for (int i = 0; i < populationSize; i++) { int i1 = RandomGenerator.getGenerator().randInt(populationSize); int i2 = RandomGenerator.getGenerator().randInt(populationSize); int i3 = RandomGenerator.getGenerator().randInt(populationSize); newVec.mapMultiplyToSelf(0.0); boolean inBounds = true; boolean isCrossingOver = false; for (int j = 0; j < numberOfParameters; j++) { if ((RandomGenerator.rand() < crossoverFrequency) ^ isCrossingOver) { if (!isCrossingOver) { isCrossingOver = true; } newVec.setEntry(j, scaleFactor * (population.getEntry(i2, j) - population.getEntry(i1, j)) + population.getEntry(i3, j)); } else { if (isCrossingOver) { isCrossingOver = false; } newVec.setEntry(j, population.getEntry(i, j)); } //random 10% range +/- mutation if ((RandomGenerator.rand() < mutationProb)) { double magnitude = 0.2 * (parameterUpperBounds.getEntry(j) - parameterLowerBounds.getEntry(j)); newVec.setEntry(j, newVec.getEntry(j) + (RandomGenerator.rand() - 0.5) * magnitude); } if (newVec.getEntry(j) < parameterLowerBounds.getEntry(j) || newVec.getEntry(j) > parameterUpperBounds.getEntry(j)) { inBounds = false; } } double functionValue = Double.MAX_VALUE; if (inBounds) functionValue = f.evaluate(newVec); //if (inBounds) System.out.printf("in bounds candidate value: %1.2f old value: %1.2f \n", functionValue, values.getEntry(i)); if (functionValue < values.getEntry(i)) { newPopulation.setRowVector(i, newVec); valuesChanged[i] = true; values.setEntry(i, functionValue); } else { newPopulation.setRowVector(i, population.getRowVector(i)); valuesChanged[i] = false; } } population = newPopulation; double tempMinValue = Double.MAX_VALUE; double tempMaxValue = -1.0 * Double.MAX_VALUE; // double averageValue = 0; for (int i = 0; i < values.getDimension(); i++) { double value = values.getEntry(i); // averageValue += value; if (value < tempMinValue) { tempMinValue = value; } if (value > tempMaxValue) { tempMaxValue = value; } } // averageValue /= values.getDimension(); currMinValue = tempMinValue; currMaxValue = tempMaxValue; //LoggingUtilities.getLogger().info("Iteration counter: " + Integer.toString(totalIterations) + " best score: " + currMinValue + " worst score: " + currMaxValue + " average score: " + averageValue); if (Math.abs(currMaxValue - currMinValue) < Math.abs(tol * currMaxValue) + Math.abs(tol * currMinValue)) { iterationCounter--; } else { iterationCounter = 1; } // totalIterations++; } for (int i = 0; i < populationSize; i++) { valuesChanged[i] = true; } computeValues(f, population, values, valuesChanged); double tempMinValue = Double.MAX_VALUE; int tempMinIndex = 0; for (int i = 0; i < populationSize; i++) { if (values.getEntry(i) < tempMinValue) { tempMinValue = values.getEntry(i); tempMinIndex = i; } } RealVector output = new ArrayRealVector(numberOfParameters); for (int i = 0; i < numberOfParameters; i++) { output.setEntry(i, population.getEntry(tempMinIndex, i)); } return output; }
From source file:ellipsoidFit.FitPoints.java
/** * Solve the polynomial expression Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz + * 2Gx + 2Hy + 2Iz from the provided points. * // w w w.ja v a 2 s. c om * @param points * the points that will be fit to the polynomial expression. * @return the solution vector to the polynomial expression. */ private RealVector solveSystem(ArrayList<ThreeSpacePoint> points) { // determine the number of points int numPoints = points.size(); // the design matrix // size: numPoints x 9 RealMatrix d = new Array2DRowRealMatrix(numPoints, 9); // Fit the ellipsoid in the form of // Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz + 2Gx + 2Hy + 2Iz for (int i = 0; i < d.getRowDimension(); i++) { double xx = Math.pow(points.get(i).x, 2); double yy = Math.pow(points.get(i).y, 2); double zz = Math.pow(points.get(i).z, 2); double xy = 2 * (points.get(i).x * points.get(i).y); double xz = 2 * (points.get(i).x * points.get(i).z); double yz = 2 * (points.get(i).y * points.get(i).z); double x = 2 * points.get(i).x; double y = 2 * points.get(i).y; double z = 2 * points.get(i).z; d.setEntry(i, 0, xx); d.setEntry(i, 1, yy); d.setEntry(i, 2, zz); d.setEntry(i, 3, xy); d.setEntry(i, 4, xz); d.setEntry(i, 5, yz); d.setEntry(i, 6, x); d.setEntry(i, 7, y); d.setEntry(i, 8, z); } // solve the normal system of equations // v = (( d' * d )^-1) * ( d' * ones.mapAddToSelf(1)); // Multiply: d' * d RealMatrix dtd = d.transpose().multiply(d); // Create a vector of ones. RealVector ones = new ArrayRealVector(numPoints); ones.mapAddToSelf(1); // Multiply: d' * ones.mapAddToSelf(1) RealVector dtOnes = d.transpose().operate(ones); // Find ( d' * d )^-1 DecompositionSolver solver = new SingularValueDecomposition(dtd).getSolver(); RealMatrix dtdi = solver.getInverse(); // v = (( d' * d )^-1) * ( d' * ones.mapAddToSelf(1)); RealVector v = dtdi.operate(dtOnes); return v; }
From source file:com.joptimizer.optimizers.JOptimizerTest.java
/** * Quadratic objective, no constraints.// w ww . ja v a2s . com */ public void testNewtownUnconstrained() throws Exception { Log.d(MainActivity.JOPTIMIZER_LOGTAG, "testNewtownUnconstrained"); RealMatrix PMatrix = new Array2DRowRealMatrix( new double[][] { { 1.68, 0.34, 0.38 }, { 0.34, 3.09, -1.59 }, { 0.38, -1.59, 1.54 } }); RealVector qVector = new ArrayRealVector(new double[] { 0.018, 0.025, 0.01 }); // Objective function. double theta = 0.01522; RealMatrix P = PMatrix.scalarMultiply(theta); RealVector q = qVector.mapMultiply(-1); PDQuadraticMultivariateRealFunction objectiveFunction = new PDQuadraticMultivariateRealFunction(P.getData(), q.toArray(), 0); OptimizationRequest or = new OptimizationRequest(); or.setF0(objectiveFunction); or.setInitialPoint(new double[] { 0.04, 0.50, 0.46 }); //optimization JOptimizer opt = new JOptimizer(); opt.setOptimizationRequest(or); int returnCode = opt.optimize(); if (returnCode == OptimizationResponse.FAILED) { fail(); } OptimizationResponse response = opt.getOptimizationResponse(); double[] sol = response.getSolution(); Log.d(MainActivity.JOPTIMIZER_LOGTAG, "sol : " + ArrayUtils.toString(sol)); Log.d(MainActivity.JOPTIMIZER_LOGTAG, "value : " + objectiveFunction.value(sol)); // we already know the analytic solution of the problem // sol = -invQ * C RealMatrix QInv = Utils.squareMatrixInverse(P); RealVector benchSol = QInv.operate(q).mapMultiply(-1); Log.d(MainActivity.JOPTIMIZER_LOGTAG, "benchSol : " + ArrayUtils.toString(benchSol.toArray())); Log.d(MainActivity.JOPTIMIZER_LOGTAG, "benchValue : " + objectiveFunction.value(benchSol.toArray())); assertEquals(benchSol.getEntry(0), sol[0], 0.000000000000001); assertEquals(benchSol.getEntry(1), sol[1], 0.000000000000001); assertEquals(benchSol.getEntry(2), sol[2], 0.000000000000001); }
From source file:com.joptimizer.optimizers.LPStandardConverterTest.java
/** * Standardization of a problem on the form: * min(c) s.t.//from w ww .j a v a 2 s. c om * G.x < h * A.x = b * lb <= x <= ub */ public void testCGhAbLbUb1() throws Exception { log.debug("testCGhAbLbUb1"); String problemId = "1"; double[] c = Utils.loadDoubleArrayFromFile( "lp" + File.separator + "standardization" + File.separator + "c" + problemId + ".txt"); double[][] G = Utils.loadDoubleMatrixFromFile( "lp" + File.separator + "standardization" + File.separator + "G" + problemId + ".csv", ",".charAt(0)); double[] h = Utils.loadDoubleArrayFromFile( "lp" + File.separator + "standardization" + File.separator + "h" + problemId + ".txt"); ; double[][] A = Utils.loadDoubleMatrixFromFile( "lp" + File.separator + "standardization" + File.separator + "A" + problemId + ".csv", ",".charAt(0)); double[] b = Utils.loadDoubleArrayFromFile( "lp" + File.separator + "standardization" + File.separator + "b" + problemId + ".txt"); double[] lb = Utils.loadDoubleArrayFromFile( "lp" + File.separator + "standardization" + File.separator + "lb" + problemId + ".txt"); double[] ub = Utils.loadDoubleArrayFromFile( "lp" + File.separator + "standardization" + File.separator + "ub" + problemId + ".txt"); double[] expectedSol = Utils.loadDoubleArrayFromFile( "lp" + File.separator + "standardization" + File.separator + "sol" + problemId + ".txt"); double expectedValue = Utils.loadDoubleArrayFromFile( "lp" + File.separator + "standardization" + File.separator + "value" + problemId + ".txt")[0]; //double expectedTolerance = Utils.loadDoubleArrayFromFile("lp"+File.separator+"standardization"+File.separator+"tolerance"+problemId+".txt")[0]; double expectedTolerance = MatrixUtils.createRealMatrix(A) .operate(MatrixUtils.createRealVector(expectedSol)).subtract(MatrixUtils.createRealVector(b)) .getNorm(); //standard form conversion double unboundedLBValue = Double.NEGATIVE_INFINITY;//this is because in the file the unbounded lb are -Infinity values (not the default value) double unboundedUBValue = Double.POSITIVE_INFINITY;//this is because in the file the unbounded ub are +Infinity values LPStandardConverter lpConverter = new LPStandardConverter(unboundedLBValue, unboundedUBValue); lpConverter.toStandardForm(c, G, h, A, b, lb, ub); int n = lpConverter.getStandardN(); int s = lpConverter.getStandardS(); c = lpConverter.getStandardC().toArray(); A = lpConverter.getStandardA().toArray(); b = lpConverter.getStandardB().toArray(); lb = lpConverter.getStandardLB().toArray(); ub = lpConverter.getStandardUB().toArray(); log.debug("n : " + n); log.debug("s : " + s); log.debug("c : " + ArrayUtils.toString(c)); log.debug("A : " + ArrayUtils.toString(A)); log.debug("b : " + ArrayUtils.toString(b)); log.debug("lb : " + ArrayUtils.toString(lb)); log.debug("ub : " + ArrayUtils.toString(ub)); //check consistency assertEquals(G.length, s); assertEquals(s + lpConverter.getOriginalN(), n); assertEquals(lb.length, n); assertEquals(ub.length, n); //check constraints RealMatrix GOrig = new Array2DRowRealMatrix(G); RealVector hOrig = new ArrayRealVector(h); RealMatrix AStandard = new Array2DRowRealMatrix(A); RealVector bStandard = new ArrayRealVector(b); RealVector expectedSolVector = new ArrayRealVector(expectedSol); RealVector Gxh = GOrig.operate(expectedSolVector).subtract(hOrig);//G.x - h RealVector slackVariables = new ArrayRealVector(s); for (int i = 0; i < s; i++) { slackVariables.setEntry(i, 0. - Gxh.getEntry(i));//the difference from 0 assertTrue(slackVariables.getEntry(i) >= 0.); } RealVector sol = slackVariables.append(expectedSolVector); RealVector Axmb = AStandard.operate(sol).subtract(bStandard); assertEquals(0., Axmb.getNorm(), expectedTolerance); // Utils.writeDoubleArrayToFile(new double[]{s}, "target" + File.separator + "standardS"+problemId+".txt"); // Utils.writeDoubleArrayToFile(c, "target" + File.separator + "standardC"+problemId+".txt"); // Utils.writeDoubleMatrixToFile(A, "target" + File.separator + "standardA"+problemId+".txt"); // Utils.writeDoubleArrayToFile(b, "target" + File.separator + "standardB"+problemId+".txt"); // Utils.writeDoubleArrayToFile(lb, "target" + File.separator + "standardLB"+problemId+".txt"); // Utils.writeDoubleArrayToFile(ub, "target" + File.separator + "standardUB"+problemId+".txt"); }
From source file:com.github.thorbenlindhauer.factor.GaussianFactorTest.java
@Test public void testProbabilityForAssignment() { GaussianFactor oneVariableFactor = factorBuilder.scope("A").momentForm().parameters( new ArrayRealVector(new double[] { 3.0d }), new Array2DRowRealMatrix(new double[] { 2.0d })); assertThat(oneVariableFactor.getValueForAssignment(new double[] { 2.5d })).isEqualTo(0.265004, TestConstants.DOUBLE_VALUE_TOLERANCE); GaussianFactor threeVariableFactor = factorBuilder.scope("A", "B", "C").momentForm() .parameters(new ArrayRealVector(new double[] { 2.0d, 3.0d, 4.0d }), new Array2DRowRealMatrix( new double[][] { { 1.0d, 0.4d, 0.5d }, { 0.4d, 1.0d, 0 }, { 0.5d, 0, 1.0d } })); assertThat(threeVariableFactor.getValueForAssignment(new double[] { 1.0d, 2.0d, 4.0d })) .isEqualTo(0.0369539, TestConstants.DOUBLE_VALUE_TOLERANCE); }