List of usage examples for org.apache.commons.math3.linear RealVector setEntry
public abstract void setEntry(int index, double value) throws OutOfRangeException;
From source file:edu.stanford.cfuller.imageanalysistools.fitting.NelderMeadMinimizer.java
/** * Constructs the initial simplex that is the starting point of the optimization given an initial guess at the minimum and a size scale for each parameter. * @param initialPoint The initial guess at the minimum, one component per parameter. * @param componentScales A size scale for each parameter that is used to set how large the initial simplex is. * @return A matrix containing p + 1 rows, each of which is one set of p parameters, which specify the simplex. *//*from ww w .ja va 2 s . co m*/ public RealMatrix generateInitialSimplex(RealVector initialPoint, RealVector componentScales) { RealMatrix initialSimplex = new Array2DRowRealMatrix(initialPoint.getDimension() + 1, initialPoint.getDimension()); initialSimplex.setRowVector(0, initialPoint); for (int i = 1; i < initialSimplex.getRowDimension(); i++) { RealVector newVector = initialPoint.copy(); newVector.setEntry(i - 1, newVector.getEntry(i - 1) + componentScales.getEntry(i - 1)); initialSimplex.setRowVector(i, newVector); } return initialSimplex; }
From source file:com.joptimizer.functions.SOCPLogarithmicBarrier.java
/** * Create the barrier function for the Phase I. * It is an instance of this class for the constraints: * <br>||Ai.x+bi|| < ci.x+di+t, i=1,...,m * @see "S.Boyd and L.Vandenberghe, Convex Optimization, 11.6.2" *//* ww w . j a v a2 s . c o m*/ public BarrierFunction createPhase1BarrierFunction() { final int dimPh1 = dim + 1; List<SOCPConstraintParameters> socpConstraintParametersPh1List = new ArrayList<SOCPConstraintParameters>(); SOCPLogarithmicBarrier bfPh1 = new SOCPLogarithmicBarrier(socpConstraintParametersPh1List, dimPh1); for (int i = 0; i < socpConstraintParametersList.size(); i++) { SOCPConstraintParameters param = socpConstraintParametersList.get(i); RealMatrix A = param.getA(); RealVector b = param.getB(); RealVector c = param.getC(); double d = param.getD(); RealMatrix APh1 = MatrixUtils.createRealMatrix(A.getRowDimension(), dimPh1); APh1.setSubMatrix(A.getData(), 0, 0); RealVector bPh1 = b; RealVector cPh1 = new ArrayRealVector(c.getDimension() + 1); cPh1.setSubVector(0, c); cPh1.setEntry(c.getDimension(), 1); double dPh1 = d; SOCPConstraintParameters paramsPh1 = new SOCPConstraintParameters(APh1.getData(), bPh1.toArray(), cPh1.toArray(), dPh1); socpConstraintParametersPh1List.add(socpConstraintParametersPh1List.size(), paramsPh1); } return bfPh1; }
From source file:game.plugins.algorithms.RealFeaturesTree.java
private RealVector getProbabilities(Dataset dataset) { Map<String, Double> prob = new HashMap<>(); Iterator<Instance> it = dataset.iterator(); double sum = 0; while (it.hasNext()) { Instance i = it.next();//from w w w . jav a 2s. c o m String key = i.getTarget().get().get(String.class); if (!prob.containsKey(key)) prob.put(key, 0.0); prob.put(key, prob.get(key) + 1.0); sum++; } List<String> labels = dataset.getTemplate().targetTemplate.getSingleton().getContent("labels"); RealVector ret = new ArrayRealVector(labels.size()); for (String key : prob.keySet()) { ret.setEntry(labels.indexOf(key), prob.get(key) / sum); } return ret; }
From source file:edu.washington.gs.skyline.model.quantification.LinearModel.java
public List<LinearFitResult> fit(double[] observations) { if (observations.length != designMatrix.getRowDimension()) { throw new IllegalArgumentException("Wrong number of rows"); }/*from w w w.jav a2 s. c o m*/ RealVector coefficients = qrDecomposition.getSolver().solve(new ArrayRealVector(observations)); RealVector fittedValues = new ArrayRealVector(observations.length); RealVector residuals = new ArrayRealVector(observations.length); for (int iRow = 0; iRow < observations.length; iRow++) { RealVector designRow = designMatrix.getRowVector(iRow); fittedValues.setEntry(iRow, designRow.dotProduct(coefficients)); residuals.setEntry(iRow, observations[iRow] - fittedValues.getEntry(iRow)); } double rss = residuals.dotProduct(residuals); int degreesOfFreedom = observations.length - qrDecomposition.getR().getColumnDimension(); double resVar = rss / degreesOfFreedom; double sigma = Math.sqrt(resVar); RealMatrix covarianceUnscaled = matrixCrossproductInverse; RealMatrix scaledCovariance = covarianceUnscaled.scalarMultiply(sigma * sigma); List<LinearFitResult> results = new ArrayList<>(); for (int iContrastRow = 0; iContrastRow < contrastValues.getRowDimension(); iContrastRow++) { RealVector contrastRow = contrastValues.getRowVector(iContrastRow); double standardError = 0; for (int iRow = 0; iRow < independentColumnIndices.length; iRow++) { for (int iCol = 0; iCol < independentColumnIndices.length; iCol++) { standardError = contrastRow.getEntry(independentColumnIndices[iRow]) * scaledCovariance.getEntry(iRow, iCol) * contrastRow.getEntry(independentColumnIndices[iCol]); } } standardError = Math.sqrt(standardError); double foldChange = coefficients.dotProduct(contrastRow); LinearFitResult linearFitResult = new LinearFitResult(foldChange); double tValue = foldChange / standardError; linearFitResult.setTValue(tValue); linearFitResult.setStandardError(standardError); linearFitResult.setDegreesOfFreedom(degreesOfFreedom); if (0 == degreesOfFreedom) { linearFitResult.setPValue(1.0); } else { TDistribution tDistribution = new TDistribution(degreesOfFreedom); double pValue = (1 - tDistribution.cumulativeProbability(Math.abs(tValue))) * 2; linearFitResult.setPValue(pValue); } results.add(linearFitResult); } return results; }
From source file:ellipsoidFit.FitPoints.java
/** * Find the radii of the ellipsoid in ascending order. * @param evals the eigenvalues of the ellipsoid. * @return the radii of the ellipsoid.//from w w w . ja v a 2 s .co m */ private RealVector findRadii(double[] evals) { RealVector radii = new ArrayRealVector(evals.length); // radii[i] = sqrt(1/eval[i]); for (int i = 0; i < evals.length; i++) { radii.setEntry(i, Math.sqrt(1 / evals[i])); } return radii; }
From source file:com.joptimizer.util.MPSParserNetlibTest.java
/** * Tests the parsing of a netlib problem. *//* ww w .ja v a2s .co m*/ public void xxxtestSingleNetlib() throws Exception { log.debug("testSingleNetlib"); //String problemName = "afiro"; //String problemName = "afiroPresolved"; //String problemName = "adlittle"; //String problemName = "kb2"; //String problemName = "sc50a"; //String problemName = "sc50b"; //String problemName = "blend"; //String problemName = "scorpion"; //String problemName = "recipe"; //String problemName = "recipePresolved"; //String problemName = "sctap1"; //String problemName = "fit1d"; //String problemName = "israel"; //String problemName = "grow15"; //String problemName = "etamacro"; //String problemName = "pilot"; //String problemName = "pilot4"; //String problemName = "osa-14"; //String problemName = "brandyPresolved"; String problemName = "maros"; File f = Utils.getClasspathResourceAsFile("lp" + File.separator + "netlib" + File.separator + problemName + File.separator + problemName + ".mps"); MPSParser mpsParser = new MPSParser(); mpsParser.parse(f); Properties expectedSolProps = null; try { //this is the solution of the mps problem given by Mathematica expectedSolProps = load(Utils.getClasspathResourceAsFile( "lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "sol.txt")); } catch (Exception e) { } log.debug("name: " + mpsParser.getName()); log.debug("n : " + mpsParser.getN()); log.debug("meq : " + mpsParser.getMeq()); log.debug("mieq: " + mpsParser.getMieq()); log.debug("meq+mieq: " + (mpsParser.getMeq() + mpsParser.getMieq())); List<String> variablesNames = mpsParser.getVariablesNames(); log.debug("x: " + ArrayUtils.toString(variablesNames)); // log.debug("c: " + ArrayUtils.toString(p.getC())); // log.debug("G: " + ArrayUtils.toString(p.getG())); // log.debug("h: " + ArrayUtils.toString(p.getH())); // log.debug("A: " + ArrayUtils.toString(p.getA())); // log.debug("b: " + ArrayUtils.toString(p.getB())); // log.debug("lb:" + ArrayUtils.toString(p.getLb())); // log.debug("ub:" + ArrayUtils.toString(p.getUb())); //check consistency: if the problem was correctly parsed, the expectedSol must be its solution double delta = 1.e-7; if (expectedSolProps != null) { //key = variable name //value = sol value assertEquals(expectedSolProps.size(), variablesNames.size()); RealVector expectedSol = new ArrayRealVector(variablesNames.size()); for (int i = 0; i < variablesNames.size(); i++) { expectedSol.setEntry(i, Double.parseDouble(expectedSolProps.getProperty(variablesNames.get(i)))); } log.debug("expectedSol: " + ArrayUtils.toString(expectedSol.toArray())); //check objective function value Map<String, LPNetlibProblem> problemsMap = LPNetlibProblem.loadAllProblems(); LPNetlibProblem problem = problemsMap.get(problemName); RealVector c = new ArrayRealVector(mpsParser.getC().toArray()); double value = c.dotProduct(expectedSol); log.debug("optimalValue: " + problem.optimalValue); log.debug("value : " + value); assertEquals(problem.optimalValue, value, delta); //check G.x < h if (mpsParser.getG() != null) { RealMatrix G = new Array2DRowRealMatrix(mpsParser.getG().toArray()); RealVector h = new ArrayRealVector(mpsParser.getH().toArray()); RealVector Gxh = G.operate(expectedSol).subtract(h); double maxGxh = -Double.MAX_VALUE; for (int i = 0; i < Gxh.getDimension(); i++) { //log.debug(i); maxGxh = Math.max(maxGxh, Gxh.getEntry(i)); assertTrue(Gxh.getEntry(i) <= 0); } log.debug("max(G.x - h): " + maxGxh); } //check A.x = b if (mpsParser.getA() != null) { RealMatrix A = new Array2DRowRealMatrix(mpsParser.getA().toArray()); RealVector b = new ArrayRealVector(mpsParser.getB().toArray()); RealVector Axb = A.operate(expectedSol).subtract(b); double norm = Axb.getNorm(); log.debug("||A.x -b||: " + norm); assertEquals(0., norm, delta * mpsParser.getN());//some more tolerance } //check upper and lower bounds for (int i = 0; i < mpsParser.getLb().size(); i++) { double di = Double.isNaN(mpsParser.getLb().getQuick(i)) ? -Double.MAX_VALUE : mpsParser.getLb().getQuick(i); assertTrue(di <= expectedSol.getEntry(i)); } for (int i = 0; i < mpsParser.getUb().size(); i++) { double di = Double.isNaN(mpsParser.getUb().getQuick(i)) ? Double.MAX_VALUE : mpsParser.getUb().getQuick(i); assertTrue(di >= expectedSol.getEntry(i)); } } Utils.writeDoubleArrayToFile(mpsParser.getC().toArray(), "target" + File.separator + "c.txt"); Utils.writeDoubleMatrixToFile(mpsParser.getG().toArray(), "target" + File.separator + "G.csv"); Utils.writeDoubleArrayToFile(mpsParser.getH().toArray(), "target" + File.separator + "h.txt"); Utils.writeDoubleMatrixToFile(mpsParser.getA().toArray(), "target" + File.separator + "A.csv"); Utils.writeDoubleArrayToFile(mpsParser.getB().toArray(), "target" + File.separator + "b.txt"); Utils.writeDoubleArrayToFile(mpsParser.getLb().toArray(), "target" + File.separator + "lb.txt"); Utils.writeDoubleArrayToFile(mpsParser.getUb().toArray(), "target" + File.separator + "ub.txt"); }
From source file:com.datumbox.framework.machinelearning.regression.MatrixLinearRegression.java
@Override protected void predictDataset(Dataset newData) { //read model params ModelParameters modelParameters = knowledgeBase.getModelParameters(); int d = modelParameters.getD(); Map<Object, Double> thitas = modelParameters.getThitas(); Map<Object, Integer> featureIds = modelParameters.getFeatureIds(); RealVector coefficients = new ArrayRealVector(d); for (Map.Entry<Object, Double> entry : thitas.entrySet()) { Integer featureId = featureIds.get(entry.getKey()); coefficients.setEntry(featureId, entry.getValue()); }/*from w ww. j a va 2 s. c om*/ MatrixDataset matrixDataset = MatrixDataset.parseDataset(newData, featureIds); RealMatrix X = matrixDataset.getX(); RealVector Y = X.operate(coefficients); for (Record r : newData) { r.setYPredicted(Y.getEntry(r.getId())); } matrixDataset = null; }
From source file:com.datumbox.framework.core.machinelearning.regression.MatrixLinearRegression.java
/** {@inheritDoc} */ @Override//w w w . j a v a2s . c o m protected void _predict(Dataframe newData) { //read model params ModelParameters modelParameters = knowledgeBase.getModelParameters(); Map<Object, Double> thitas = modelParameters.getThitas(); Map<Object, Integer> featureIds = modelParameters.getFeatureIds(); int d = thitas.size(); RealVector coefficients = new OpenMapRealVector(d); for (Map.Entry<Object, Double> entry : thitas.entrySet()) { Integer featureId = featureIds.get(entry.getKey()); coefficients.setEntry(featureId, entry.getValue()); } Map<Integer, Integer> recordIdsReference = new HashMap<>(); //use a mapping between recordIds and rowIds in Matrix DataframeMatrix matrixDataset = DataframeMatrix.parseDataset(newData, recordIdsReference, featureIds); RealMatrix X = matrixDataset.getX(); RealVector Y = X.operate(coefficients); for (Map.Entry<Integer, Record> e : newData.entries()) { Integer rId = e.getKey(); Record r = e.getValue(); int rowId = recordIdsReference.get(rId); newData._unsafe_set(rId, new Record(r.getX(), r.getY(), Y.getEntry(rowId), r.getYPredictedProbabilities())); } //recordIdsReference = null; //matrixDataset = null; }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.DifferentialEvolutionMinimizer.java
/** * Updates the function values for each parameter set in the population only if that parameter set has changed. * @param f The function being minimized * @param population The current population of parameters, one parameter set per row. * @param values The vector of the last computed values for each entry in the population; entries that have changed will be overwritten. * @param valuesChanged An array indicating whether each entry in the population has changed and requires computation of the value. *///ww w . j av a 2 s . c o m private void computeValues(ObjectiveFunction f, RealMatrix population, RealVector values, boolean[] valuesChanged) { for (int i = 0; i < population.getRowDimension(); i++) { if (valuesChanged[i]) { values.setEntry(i, f.evaluate(population.getRowVector(i))); } } }
From source file:com.joptimizer.solvers.DiagonalKKTSolver.java
/** * Returns two vectors v and w./*from w ww .j av a 2 s . com*/ */ @Override public double[][] solve() throws Exception { RealVector v = null; RealVector w = null; if (Log.isLoggable(MainActivity.JOPTIMIZER_LOGTAG, Log.DEBUG)) { Log.d(MainActivity.JOPTIMIZER_LOGTAG, "H: " + ArrayUtils.toString(H.getData())); Log.d(MainActivity.JOPTIMIZER_LOGTAG, "g: " + ArrayUtils.toString(g.toArray())); } v = new ArrayRealVector(g.getDimension()); for (int i = 0; i < v.getDimension(); i++) { v.setEntry(i, -g.getEntry(i) / H.getEntry(i, i)); } // solution checking if (this.checkKKTSolutionAccuracy && !this.checkKKTSolutionAccuracy(v, w)) { Log.e(MainActivity.JOPTIMIZER_LOGTAG, "KKT solution failed"); throw new Exception("KKT solution failed"); } double[][] ret = new double[2][]; ret[0] = v.toArray(); ret[1] = (w != null) ? w.toArray() : null; return ret; }