List of usage examples for org.apache.commons.math3.linear RealVector getEntry
public abstract double getEntry(int index) throws OutOfRangeException;
From source file:com.github.thorbenlindhauer.cluster.ep.TruncatedGaussianPotentialResolverTest.java
@Test public void testTwoSidedTruncatedGaussianApproximation() { ContinuousVariable variable = new ContinuousVariable("A"); Scope scope = new Scope(Collections.singleton(variable)); GaussianFactor factor = StandaloneGaussiaFactorBuilder.withVariables(variable).scope("A").momentForm() .parameters(new ArrayRealVector(new double[] { 2.0d }), new Array2DRowRealMatrix(new double[] { 4.0d })); TruncatedGaussianPotentialResolver resolver = new TruncatedGaussianPotentialResolver(variable, 0.5d, 6.0d); FactorSet<GaussianFactor> factorSet = new FactorSet<GaussianFactor>(Collections.singleton(factor)); FactorSet<GaussianFactor> approximation = resolver.project(factorSet, scope); assertThat(approximation.getFactors()).hasSize(1); GaussianFactor approximationFactor = approximation.getFactors().iterator().next(); RealVector meanVector = approximationFactor.getMeanVector(); RealMatrix covarianceMatrix = approximationFactor.getCovarianceMatrix(); assertThat(meanVector.getDimension()).isEqualTo(1); assertThat(meanVector.getEntry(0)).isEqualTo(2.658510664d, TestConstants.DOUBLE_VALUE_TOLERANCE); assertThat(covarianceMatrix.isSquare()); assertThat(covarianceMatrix.getColumnDimension()).isEqualTo(1); assertThat(covarianceMatrix.getEntry(0, 0)).isEqualTo(1.787386921d, TestConstants.DOUBLE_VALUE_TOLERANCE); }
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 www . j ava2 s . c o m 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:interpolacao.Interpolacao.java
public Interpolacao() { UnivariateFunction polinomio = interpolador.interpolate(x, y);//sera excluido int n = (int) Math.abs((StatUtils.max(x) - Math.abs(StatUtils.min(x))) * 10);//numero de elementos double[] xc = new double[n]; double[] yc = new double[n]; double[] yc2 = new double[n]; double xi = StatUtils.min(x);//valor inicial for (int i = 0; i < h.length; i++)//calculo de h {// w w w . j ava 2 s . c o m h[i] = x[i + 1] - x[i]; } for (int i = 0; i < h.length - 1; i++) { //criacao da matriz A para clculo de G (sistema linear for (int j = 1; j < h.length; j++) { // pular primeira e ultima colunas if (i == j) { matrizA[i][j - 1] = h[i]; } else { if (j == i + 1) { matrizA[i][j - 1] = 2 * (h[i] + h[i + 1]); } else { if (j == i + 2) { matrizA[i][j - 1] = h[i + 1]; } else { matrizA[i][j - 1] = 0; } } } System.out.print(matrizA[i][j - 1] + " ");// imprime matrizA criada } System.out.println(""); } //fim criacao matriz A for (int i = 0; i < vetorB.length; i++) { double auxY1 = y[i + 1] - y[i]; double auxY2 = y[i + 2] - y[i + 1]; double auxH1 = ((x[i + 1] - x[i])); double auxH2 = ((x[i + 2] - x[i + 1])); vetorB[i] = 6 * ((auxY2 / auxH2) - (auxY1 / auxH1)); System.out.print(vetorB[i] + " ");// imprime vetorB criada } RealMatrix coefficients = new Array2DRowRealMatrix(matrizA, false); DecompositionSolver solver = new LUDecomposition(coefficients).getSolver(); RealVector constants = new ArrayRealVector(vetorB, false); RealVector solution = solver.solve(constants); g[0] = 0; for (int k = 1; k < g.length - 2; k++) { g[k] = solution.getEntry(k - 1); } g[g.length - 1] = 0; for (int t = 0; t < x.length - 1; t++) { d[t] = y[t]; c[t] = ((y[t + 1] - y[t]) / h[t]) + (((2 * h[t] * g[t + 1]) + (g[t + 0] * h[t])) / 6); b[t] = g[t + 1] / 2; // talvez seja g[t+1] <----- a[t] = (g[t + 1] - g[t + 0]) / (6 * h[t]); } double step = (StatUtils.max(x) - StatUtils.min(x)) / n; int auxPos = 0; double x_val = x[0]; for (int i = 0; i < xc.length; i++) { while (x_val >= x[auxPos + 1]) { FuncaoS(x[auxPos + 1], auxPos); auxPos++; } xc[i] = x_val; yc[i] = FuncaoS(xc[i], auxPos); yc2[i] = polinomio.value(xc[i]); x_val = (step * i) + x[0]; } plot.addLegend("SOUTH"); plot.addScatterPlot("Pontos", x, y); plot.addLinePlot("Spline", xc, yc); JFrame frame = new JFrame("Spline"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600, 500); frame.add(plot, BorderLayout.CENTER); frame.setVisible(true); Plot2DPanel plot2 = new Plot2DPanel(); plot2.addLegend("SOUTH"); plot2.addScatterPlot("Pontos", x, y); plot2.addLinePlot("Spline", xc, yc2); JFrame frame2 = new JFrame("SplineComp"); frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame2.setSize(600, 500); frame2.add(plot2, BorderLayout.CENTER); frame2.setVisible(true); }
From source file:net.sf.dsp4j.octave_3_2_4.m.polynomial.Roots.java
public static Complex[] roots(RealVector v) { if (v.isInfinite() || v.isNaN()) { throw new RuntimeException("roots: inputs must not contain Inf or NaN"); }/*w ww . j a va 2 s. c o m*/ int n = v.getDimension(); // ## If v = [ 0 ... 0 v(k+1) ... v(k+l) 0 ... 0 ], we can remove the // ## leading k zeros and n - k - l roots of the polynomial are zero. int[] f = new int[v.getDimension()]; if (v.getDimension() > 0) { int fI = 0; double max = v.getMaxValue(); double min = FastMath.abs(v.getMinValue()); if (min > max) { max = min; } RealVector v1 = v.mapDivide(max); f = OctaveBuildIn.find(v1); } Complex[] r = new Complex[0]; if (f.length > 0 && n > 1) { v = v.getSubVector(f[0], f[f.length - 1] - f[0] + 1); if (v.getDimension() > 1) { double[] ones = new double[v.getDimension() - 2]; Arrays.fill(ones, 1); RealMatrix A = OctaveBuildIn.diag(ones, -1); for (int i = 0; i < A.getRowDimension(); i++) { A.setEntry(i, 0, -v.getEntry(i + 1) / v.getEntry(0)); } try { r = Eig.eig(A); } catch (Exception e) { throw new RuntimeException(e); } if (f[f.length - 1] < n) { int diffLength = n - 1 - f[f.length - 1]; if (diffLength > 0) { int rl = r.length; r = Arrays.copyOf(r, r.length + diffLength); Arrays.fill(r, rl, r.length, Complex.ZERO); } } } else { r = new Complex[n - f[f.length - 1]]; Arrays.fill(r, Complex.ZERO); } } else { r = new Complex[0]; } return r; }
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. *//* ww w .j ava 2 s. c om*/ 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:game.plugins.metrics.StandardClassificationMetrics.java
private double evaluateWeightedAverage(RealVector row) { double ret = 0; double sum = 0; for (int i = 0; i < row.getDimension() - 1; i++) { double w = truePositives.get(i) + falseNegatives.get(i); ret += row.getEntry(i) * w; sum += w;//w w w. j a v a 2s. c om } ret = sum == 0 ? 0 : ret / sum; return ret; }
From source file:iocomms.subpos.ArrayLocations.java
private Position trilaterate(ArrayLocations locations) { //Trilateration nonlinear weighted least squares //https://github.com/lemmingapex/Trilateration - MIT Licence //http://commons.apache.org/proper/commons-math/download_math.cgi double[][] positions = new double[locations.size()][3]; double[] distances = new double[locations.size()]; int i = 0;//w w w . j a v a2 s.c o m while (i < locations.size()) { //Map projection is treated as Mercator for calcs //Convert lat,lng to meters and then back again //Altitude is in cm positions[i] = new double[] { WebMercator.latitudeToY(locations.get(i).lat), WebMercator.longitudeToX(locations.get(i).lng), locations.get(i).altitude }; distances[i] = locations.get(i).distance; i++; } TrilaterationFunction trilaterationFunction = new TrilaterationFunction(positions, distances); NonLinearLeastSquaresSolver solver = new NonLinearLeastSquaresSolver(trilaterationFunction, new LevenbergMarquardtOptimizer()); LeastSquaresOptimizer.Optimum optimum = solver.solve(); double[] centroid = optimum.getPoint().toArray(); double errorRadius = 0; boolean errorCalc = false; // Error and geometry information try { //Create new array without the altitude. Including altitude causes a //SingularMatrixException as it cannot invert the matrix. double[][] err_positions = new double[locations.size()][2]; i = 0; while (i < locations.size()) { err_positions[i] = new double[] { positions[i][0], positions[i][1] }; i++; } trilaterationFunction = new TrilaterationFunction(err_positions, distances); solver = new NonLinearLeastSquaresSolver(trilaterationFunction, new LevenbergMarquardtOptimizer()); optimum = solver.solve(); RealVector standardDeviation = optimum.getSigma(0); //RealMatrix covarianceMatrix = optimum.getCovariances(0); errorRadius = ((standardDeviation.getEntry(0) + standardDeviation.getEntry(1)) / 2) * 100; errorCalc = true; } catch (Exception ex) { errorRadius = 0; errorCalc = false; } return new Position(WebMercator.yToLatitude(optimum.getPoint().toArray()[0]), WebMercator.xToLongitude(centroid[1]), centroid[2], errorRadius, errorCalc); }
From source file:edu.oregonstate.eecs.mcplan.abstraction.EvaluateSimilarityFunction.java
public static Instances transformInstances(final Instances src, final CoordinateTransform transform) { final ArrayList<Attribute> out_attributes = new ArrayList<Attribute>(); for (int i = 0; i < transform.outDimension(); ++i) { out_attributes.add(new Attribute("x" + i)); }//w w w . ja va2 s. c o m out_attributes.add((Attribute) src.classAttribute().copy()); final Instances out = new Instances(src.relationName() + "_" + transform.name(), out_attributes, 0); for (int i = 0; i < src.size(); ++i) { final Instance inst = src.get(i); final RealVector flat = new ArrayRealVector(WekaUtil.unlabeledFeatures(inst)); final RealVector transformed_vector = transform.encode(flat).x; final double[] transformed = new double[transformed_vector.getDimension() + 1]; for (int j = 0; j < transformed_vector.getDimension(); ++j) { transformed[j] = transformed_vector.getEntry(j); } transformed[transformed.length - 1] = inst.classValue(); final Instance transformed_instance = new DenseInstance(inst.weight(), transformed); out.add(transformed_instance); transformed_instance.setDataset(out); } out.setClassIndex(out.numAttributes() - 1); return out; }
From source file:com.joptimizer.optimizers.NewtonUnconstrainedTest.java
/** * Quadratic objective./*from w ww . ja v a2 s .co m*/ */ public void testOptimize() throws Exception { log.debug("testOptimize"); // START SNIPPET: newtonUnconstrained-1 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 }); or.setTolerance(1.e-8); //optimization NewtonUnconstrained opt = new NewtonUnconstrained(); opt.setOptimizationRequest(or); int returnCode = opt.optimize(); // END SNIPPET: newtonUnconstrained-1 if (returnCode == OptimizationResponse.FAILED) { fail(); } OptimizationResponse response = opt.getOptimizationResponse(); double[] sol = response.getSolution(); log.debug("sol : " + ArrayUtils.toString(sol)); log.debug("value : " + objectiveFunction.value(sol)); // we know the analytic solution of the problem // sol = -PInv * q CholeskyDecomposition cFact = new CholeskyDecomposition(P); RealVector benchSol = cFact.getSolver().solve(q).mapMultiply(-1); log.debug("benchSol : " + ArrayUtils.toString(benchSol.toArray())); log.debug("benchValue : " + objectiveFunction.value(benchSol.toArray())); assertEquals(benchSol.getEntry(0), sol[0], 0.00000000000001); assertEquals(benchSol.getEntry(1), sol[1], 0.00000000000001); assertEquals(benchSol.getEntry(2), sol[2], 0.00000000000001); }
From source file:com.github.kingtim1.jmdp.discounted.MatrixInversePolicyEvaluation.java
@Override public DiscountedVFunction<S> eval(StationaryPolicy<S, A> policy) { int n = _smdp.numberOfStates(); List<S> states = new ArrayList<S>(n); Iterable<S> istates = _smdp.states(); for (S state : istates) { states.add(state);/*from w ww. j a v a 2 s. c o m*/ } // Construct matrix A and vector b RealMatrix id = MatrixUtils.createRealIdentityMatrix(n); RealMatrix gpp = gammaPPi(policy, states); RealMatrix A = id.subtract(gpp); RealVector b = rPi(policy, states); // Solve for V^{\pi} SingularValueDecomposition decomp = new SingularValueDecomposition(A); DecompositionSolver dsolver = decomp.getSolver(); RealVector vpi = dsolver.solve(b); // Construct the value function Map<S, Double> valueMap = new HashMap<S, Double>(); for (int i = 0; i < states.size(); i++) { S state = states.get(i); double val = vpi.getEntry(i); valueMap.put(state, val); } return new MapVFunction<S>(valueMap, 0); }