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.ucsf.valelab.saim.calculations.SaimParameterValidator.java
/** * Very simple validator that uses lower and upper bounds to restrict * parameter values/* ww w. j a v a 2 s .c om*/ * @param params * @return */ @Override public RealVector validate(RealVector params) { if (params.getDimension() != 3) throw new DimensionMismatchException(params.getDimension(), 3); RealVector n = params.copy(); for (int i = 0; i < 3; i++) { if (n.getEntry(i) < lowerBounds_[i]) n.setEntry(i, lowerBounds_[i]); if (n.getEntry(i) > upperBounds_[i]) n.setEntry(i, upperBounds_[i]); } return n; }
From source file:edu.cuhk.hccl.cmd.CosineDocumentSimilarity.java
private RealVector toRealVector(Map<String, Integer> map) { RealVector vector = new ArrayRealVector(terms.size()); int i = 0;// ww w . j a v a 2 s . co m for (String term : terms) { int value = map.containsKey(term) ? map.get(term) : 0; vector.setEntry(i++, value); } return (RealVector) vector.mapDivide(vector.getL1Norm()); }
From source file:eu.crisis_economics.abm.markets.clearing.heterogeneous.NelderMeadClearingAlgorithm.java
@Override public double applyToNetwork(final MixedClearingNetwork network) { Preconditions.checkNotNull(network); final SimplexOptimizer optimizer = new SimplexOptimizer(relErrorTarget, absErrorTarget); final ResidualCostFunction aggregateCostFunction = super.getResidualScalarCostFunction(network); final RealVector start = new ArrayRealVector(network.getNumberOfEdges()); for (int i = 0; i < network.getNumberOfEdges(); ++i) start.setEntry(i, network.getEdges().get(i).getMaximumRateAdmissibleByBothParties()); start.set(1.);//from w ww.ja va2 s .co m final PointValuePair result = optimizer.optimize(new MaxEval(maximumEvaluations), new ObjectiveFunction(aggregateCostFunction), GoalType.MINIMIZE, new InitialGuess(start.toArray()), new NelderMeadSimplex(network.getNumberOfEdges())); final double residualCost = result.getValue(); System.out.println("Network cleared: residual cost: " + residualCost + "."); return residualCost; }
From source file:edu.stanford.cfuller.colocalization3d.fitting.P3DFitter.java
/** * Fits the distances between the two channels of a set of objects to a p3d distribution. * // w ww .j a va2s . c o m * @param objects the ImageObjects whose distances will be fit * @param diffs a RealVector containing the scalar distances between the channels of the ImageObjects, in the same order. * * @return a RealVector containing the parameters for the distribution fit: first the mean parameter, second the standard deviation parameter */ public RealVector fit(List<ImageObject> objects, RealVector diffs) { P3dObjectiveFunction of = new P3dObjectiveFunction(); of.setR(diffs); final double tol = 1e-12; NelderMeadMinimizer nmm = new NelderMeadMinimizer(tol); double initialMean = diffs.getL1Norm() / diffs.getDimension(); double initialWidth = diffs.mapSubtract(initialMean) .map(new org.apache.commons.math3.analysis.function.Power(2)).getL1Norm() / diffs.getDimension(); initialWidth = Math.sqrt(initialWidth); RealVector startingPoint = new ArrayRealVector(2, 0.0); startingPoint.setEntry(0, initialMean); startingPoint.setEntry(1, initialWidth); RealVector parametersMin = null; if (this.parameters.hasKey(ROBUST_P3D_FIT_PARAM)) { double cutoff = this.parameters.getDoubleValueForKey(ROBUST_P3D_FIT_PARAM); of.setMinProb(cutoff); } return nmm.optimize(of, startingPoint); }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.CentroidImageObject.java
/** * "Fits" this object to a position by finding its intensity-weighted * centroid. Does not compute error estimates, numbers of photons, etc. * //from w ww .ja v a 2 s .co m * @param p The parameters for the current analysis. */ @Override public void fitPosition(ParameterDictionary p) { if (this.sizeInPixels == 0) { this.nullifyImages(); return; } this.fitParametersByChannel = new java.util.ArrayList<FitParameters>(); this.fitR2ByChannel = new java.util.ArrayList<Double>(); this.fitErrorByChannel = new java.util.ArrayList<Double>(); this.nPhotonsByChannel = new java.util.ArrayList<Double>(); int numChannels = 0; if (p.hasKey("num_wavelengths")) { numChannels = p.getIntValueForKey("num_wavelengths"); } else { numChannels = this.parent.getDimensionSizes().get(ImageCoordinate.C); } for (int channelIndex = 0; channelIndex < numChannels; channelIndex++) { this.parentBoxMin.set(ImageCoordinate.C, channelIndex); this.parentBoxMax.set(ImageCoordinate.C, channelIndex + 1); this.boxImages(); java.util.Vector<Double> x = new java.util.Vector<Double>(); java.util.Vector<Double> y = new java.util.Vector<Double>(); java.util.Vector<Double> z = new java.util.Vector<Double>(); java.util.Vector<Float> f = new java.util.Vector<Float>(); for (ImageCoordinate ic : this.parent) { x.add((double) ic.get(ImageCoordinate.X)); y.add((double) ic.get(ImageCoordinate.Y)); z.add((double) ic.get(ImageCoordinate.Z)); if (((int) this.mask.getValue(ic)) == this.label) { f.add(parent.getValue(ic)); } else { f.add(0.0f); } } xValues = new double[x.size()]; yValues = new double[y.size()]; zValues = new double[z.size()]; functionValues = new double[f.size()]; double xCentroid = 0; double yCentroid = 0; double zCentroid = 0; double totalCounts = 0; for (int i = 0; i < x.size(); i++) { xValues[i] = x.get(i); yValues[i] = y.get(i); zValues[i] = z.get(i); functionValues[i] = f.get(i); xCentroid += xValues[i] * functionValues[i]; yCentroid += yValues[i] * functionValues[i]; zCentroid += zValues[i] * functionValues[i]; totalCounts += functionValues[i]; } xCentroid /= totalCounts; yCentroid /= totalCounts; zCentroid /= totalCounts; RealVector position = new ArrayRealVector(3, 0.0); position.setEntry(0, xCentroid); position.setEntry(1, yCentroid); position.setEntry(2, zCentroid); this.positionsByChannel.add(position); } this.hadFittingError = false; this.nullifyImages(); }
From source file:lucene.CosineDocumentSimilarity.java
RealVector toRealVector(Map<String, Integer> map) { RealVector vector = new ArrayRealVector(terms.size()); int i = 0;//from w ww . j a v a 2 s .c o m for (String term : terms) { int value = map.containsKey(term) ? map.get(term) : 0; vector.setEntry(i++, value); } return (RealVector) vector.mapDivide(vector.getL1Norm()); }
From source file:edu.utexas.cs.tactex.tariffoptimization.OptimizerWrapperGradientAscent.java
@Override public TreeMap<Double, TariffSpecification> findOptimum(TariffUtilityEstimate tariffUtilityEstimate, int NUM_RATES, int numEval) { double[] startingVertex = new double[NUM_RATES]; // start from the fixed-rate tariff's offset Arrays.fill(startingVertex, 0.0); // temporary solution - getting fixed rate tariff to determine step size and scaling STEP_SIZE proportionally TariffSpecification bestFixedRateSpec = tariffUtilityEstimate.getCorrespondingSpec(startingVertex); double bestFixedRate = bestFixedRateSpec.getRates().get(0).getValue(); double rateRatio = bestFixedRate / REFERENCE_RATE; // Note: using rateRatio has not been good enough, so trying powers of it (remember it's > 1) //STEP_SIZE = Math.max(REFERENCE_STEP_SIZE, (rateRatio * rateRatio) * REFERENCE_STEP_SIZE); STEP_SIZE = Math.max(REFERENCE_STEP_SIZE, Math.abs(rateRatio) * REFERENCE_STEP_SIZE); log.debug("STEP_SIZE = " + STEP_SIZE + " REFERENCE_STEP_SIZE=" + REFERENCE_STEP_SIZE + " bestFixedRate=" + bestFixedRate + " REFERENCE_RATE=" + REFERENCE_RATE); evaluations = 0;//from w ww . j av a 2 s. com TreeMap<Double, TariffSpecification> eval2TOUTariff = new TreeMap<Double, TariffSpecification>(); // OUTER LOOP //for( STEP_SIZE = 0.005; STEP_SIZE < 0.100; STEP_SIZE += 0.005) { // log.info("STARTING A LOOP: STEP_SIZE=" + STEP_SIZE); // first compute numerical gradient RealVector gradient = new ArrayRealVector(NUM_RATES); for (int i = 0; i < NUM_RATES; ++i) { gradient.setEntry(i, computePartialDerivative(i, tariffUtilityEstimate, NUM_RATES, eval2TOUTariff)); } gradient = gradient.unitVector(); // taking steps in the gradient direction double previousPointValue = -Double.MAX_VALUE; final double alpha = STEP_SIZE; RealVector rateOffsets = new ArrayRealVector(NUM_RATES); // initializes with 0s? double currentPointValue = evaluatePoint(tariffUtilityEstimate, rateOffsets.toArray()); eval2TOUTariff.put(currentPointValue, tariffUtilityEstimate.getCorrespondingSpec(rateOffsets.toArray())); while (!converged(currentPointValue, previousPointValue) && evaluations < MAX_EVALUATIONS) { previousPointValue = currentPointValue; rateOffsets = rateOffsets.add(gradient.mapMultiply(alpha)); currentPointValue = evaluatePoint(tariffUtilityEstimate, rateOffsets.toArray()); eval2TOUTariff.put(currentPointValue, tariffUtilityEstimate.getCorrespondingSpec(rateOffsets.toArray())); } log.info("gradient ascent finished after " + evaluations + " evaluations"); //} // return map return eval2TOUTariff; }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.core.operator.real.AdaptiveMetropolis.java
@Override public Solution[] evolve(Solution[] parents) { int k = parents.length; int n = parents[0].getNumberOfVariables(); RealMatrix x = new Array2DRowRealMatrix(k, n); for (int i = 0; i < k; i++) { x.setRow(i, EncodingUtils.getReal(parents[i])); }/* www .j a v a2s .c o m*/ try { //perform Cholesky factorization and get the upper triangular matrix double jumpRate = Math.pow(jumpRateCoefficient / Math.sqrt(n), 2.0); RealMatrix chol = new CholeskyDecomposition( new Covariance(x.scalarMultiply(jumpRate)).getCovarianceMatrix()).getLT(); //produce the offspring Solution[] offspring = new Solution[numberOfOffspring]; for (int i = 0; i < numberOfOffspring; i++) { Solution child = parents[PRNG.nextInt(parents.length)].copy(); //apply adaptive metropolis step to solution RealVector muC = new ArrayRealVector(EncodingUtils.getReal(child)); RealVector ru = new ArrayRealVector(n); for (int j = 0; j < n; j++) { ru.setEntry(j, PRNG.nextGaussian()); } double[] variables = muC.add(chol.preMultiply(ru)).toArray(); //assign variables back to solution for (int j = 0; j < n; j++) { RealVariable variable = (RealVariable) child.getVariable(j); double value = variables[j]; if (value < variable.getLowerBound()) { value = variable.getLowerBound(); } else if (value > variable.getUpperBound()) { value = variable.getUpperBound(); } variable.setValue(value); } offspring[i] = child; } return offspring; } catch (Exception e) { return new Solution[0]; } }
From source file:ir.project.helper.SVDecomposition.java
public TFIDFBookVector changeQuery(TFIDFBookVector query) { // Perform the necessary opperations to change the vector to the LSA space Matrix q = SparseMatrix.Factory.zeros(query.getVector().getDimension(), 1); for (int i = 0; i < query.getVector().getDimension(); i++) { q.setAsDouble(query.getVector().getEntry(i), i, 0); }/*w w w.j a v a 2s. co m*/ // Now change the query: // new q = S.inv * U.transpose * q Matrix new_q = this.Sk.inv().mtimes(Uk.transpose()).mtimes(q); // Reconstruct the TFIDF Vector RealVector r = new ArrayRealVector(query.getVector().getDimension()); // TODO Make sparse (Might not be neccessary if the vector has barely any zeroes for (int i = 0; i < new_q.getRowCount(); i++) { r.setEntry(i, new_q.getAsDouble(i, 0)); } query.setVector(r); return query; }
From source file:com.joptimizer.functions.SOCPLogarithmicBarrier.java
public double[] gradient(double[] X) { RealVector x = new ArrayRealVector(X); RealVector ret = new ArrayRealVector(dim); for (int i = 0; i < socpConstraintParametersList.size(); i++) { SOCPConstraintParameters param = socpConstraintParametersList.get(i); double t = this.buildT(param, x); RealVector u = this.buildU(param, x); double t2uu = t * t - u.dotProduct(u); RealMatrix Jacob = this.buildJ(param, x); int k = u.getDimension(); RealVector G = new ArrayRealVector(k + 1); G.setSubVector(0, u);/* ww w . ja v a 2 s .c o m*/ G.setEntry(k, -t); RealVector ret_i = Jacob.operate(G).mapMultiply((2. / t2uu)); ret = ret.add(ret_i); } return ret.toArray(); }