Example usage for org.apache.commons.math3.linear RealVector toArray

List of usage examples for org.apache.commons.math3.linear RealVector toArray

Introduction

In this page you can find the example usage for org.apache.commons.math3.linear RealVector toArray.

Prototype

public double[] toArray() 

Source Link

Document

Convert the vector to an array of double s.

Usage

From source file:edu.washington.gs.skyline.model.quantification.WeightedRegression.java

public static double[] weighted(double[][] x, double[] y, double[] weights, boolean intercept) {
    RealMatrix predictor;/*from   w  ww . j a  va  2  s. c  om*/
    if (intercept) {
        int nRows = x.length;
        int nCols = x[0].length + 1;
        predictor = MatrixUtils.createRealMatrix(nRows, nCols);
        for (int iRow = 0; iRow < nRows; iRow++) {
            predictor.setEntry(iRow, 0, 1.0);
            for (int iCol = 1; iCol < nCols; iCol++) {
                predictor.setEntry(iRow, iCol, x[iRow][iCol - 1]);
            }
        }
    } else {
        predictor = MatrixUtils.createRealMatrix(x);
    }
    RealVector responseVector = MatrixUtils.createRealVector(y);
    RealMatrix weightsMatrix = MatrixUtils.createRealDiagonalMatrix(weights);
    RealMatrix predictorTransposed = predictor.transpose();
    RealMatrix predictorTransposedTimesWeights = predictorTransposed
            .multiply(weightsMatrix.multiply(predictor));
    CholeskyDecomposition choleskyDecomposition = new CholeskyDecomposition(predictorTransposedTimesWeights);
    RealVector vectorToSolve = predictorTransposed.operate(weightsMatrix.operate(responseVector));
    RealVector result = choleskyDecomposition.getSolver().solve(vectorToSolve);
    return result.toArray();
}

From source file:edu.stanford.cfuller.imageanalysistools.fitting.GaussianFitter3D.java

/**
 * Calculates the fit residual between a set of parameters and a value at a supplied point.
 * @param value         The observed value at the point.
 * @param x             The x-coordinate of the point (in absolute original image coordinates)
 * @param y             The y-coordinate of the point (in absolute original image coordinates)
 * @param z             The z-coordinate of the point (in absolute original image coordinates.
 * @param parameters    The gaussian parameters in the same order as would be required for or returned from {@link #fit}
 * @return              The fit residual at the specified point.
 *///  w  w  w . ja v  a  2  s. co  m
public static double fitResidual(double value, double x, double y, double z, RealVector parameters) {

    return value - gaussian(x, y, z, parameters.toArray());
}

From source file:com.analog.lyric.math.MoreMatrixUtils.java

/**
 * Returns vector as a an array.//from w w  w  .j  ava  2s  .  c  o  m
 * <p>
 * If {@code vector} is a {@link ArrayRealVector}, this returns its underlying array,
 * otherwise returns a newly allocated array.
 * @since 0.08
 */
public static double[] vectorGetDataRef(RealVector vector) {
    if (vector instanceof ArrayRealVector) {
        return ((ArrayRealVector) vector).getDataRef();
    }

    return vector.toArray();
}

From source file:com.opengamma.strata.math.impl.util.CommonsMathWrapper.java

/**
 * Unwraps a vector./*from   w ww.j  av a2s  . c  o m*/
 * 
 * @param x  a Commons vector
 * @return an OG 1-D matrix of doubles
 */
public static DoubleArray unwrap(RealVector x) {
    ArgChecker.notNull(x, "x");
    return DoubleArray.ofUnsafe(x.toArray());
}

From source file:eagle.security.userprofile.model.UserProfileEigenModelEntity.java

public static MLModelAPIEntity serializeModel(UserProfileEigenModel model) throws IOException {
    if (model == null)
        return null;
    if (model.user() == null)
        throw new IllegalArgumentException("user is null");

    MLModelAPIEntity entity = new MLModelAPIEntity();
    UserProfileEigenModelEntity content = new UserProfileEigenModelEntity();
    entity.setVersion(model.version());//from  w  ww.j av a 2s .  c  o m
    if (model.uMatrix() != null)
        content.setUMatrix(model.uMatrix().getData());
    if (model.diagonalMatrix() != null)
        content.setDiagonalMatrix(model.diagonalMatrix().getData());
    content.setDimension(model.dimension());
    if (model.minVector() != null)
        content.setMinVector(model.minVector().toArray());
    if (model.maxVector() != null)
        content.setMaxVector(model.maxVector().toArray());

    RealVector[] pcsInVector = model.principalComponents();
    if (pcsInVector != null) {
        List<double[]> prcsInDouleArrayList = new ArrayList<>(pcsInVector.length);
        for (RealVector vector : pcsInVector)
            prcsInDouleArrayList.add(vector.toArray());
        content.setPrincipalComponents(prcsInDouleArrayList);
    }
    if (model.maximumL2Norm() != null)
        content.setMaximumL2Norm(model.maximumL2Norm().toArray());
    if (model.minimumL2Norm() != null)
        content.setMinimumL2Norm(model.minimumL2Norm().toArray());
    if (model.statistics() != null) {
        List<Map<String, Object>> statisticsMaps = new ArrayList<>(model.statistics().length);
        for (UserCommandStatistics userCommandStatistics : model.statistics())
            statisticsMaps.add(userCommandStatistics.toMap());
        content.setStatistics(statisticsMaps);
    }

    entity.setContent(TaggedLogAPIEntity.buildObjectMapper().writeValueAsString(content));
    Map<String, String> tags = new HashMap<>();
    tags.put(UserProfileConstants.SITE_TAG, model.site());
    tags.put(UserProfileConstants.USER_TAG, model.user());
    tags.put(UserProfileConstants.ALGORITHM_TAG, model.algorithm());

    entity.setTags(tags);
    return entity;
}

From source file:com.vsthost.rnd.commons.math.ext.linear.EMatrixUtils.java

/**
 * Converts a real vector to a JSON string.
 *
 * @param vector The vector to be represented by a JSON string.
 * @return A JSON representation of the matrix.
 *//*w  w w . ja  va  2s. c om*/
public static String toJson(RealVector vector) {
    return new Gson().toJson(vector.toArray());
}

From source file:edu.byu.nlp.math.RealVectors.java

/**
 * Computes the log of the sum of the exponentiated elements of a vector. For any index j:
 * //from  w w w . jav a2 s . c o  m
 * <pre>
 * log(e^{x_1} + e^{x_2} + ...) = log(e^{x_j} * sum\_{i \neq j} e^{x_i - x_j} + 1)
  *                              = x_j + log(sum\_{i \neq j} e^{x_i - x_j} + 1)
  * </pre>
  * 
  * This method ignores elements that are twenty orders of magnitude different than x_j.
  * 
  * @throws NullPointerException if vector is null
  */
public static double logSumSloppy(RealVector x) {
    Preconditions.checkNotNull(x);

    // TODO(rah67): consider just using the first element
    // use max as j
    int argMax = x.getMaxIndex();
    double max = x.getEntry(argMax);

    if (max == Double.NEGATIVE_INFINITY)
        return Double.NEGATIVE_INFINITY;

    return DoubleArrays.logSum(x.toArray());
}

From source file:hits.HitTools.java

private static PointWithPropertiesIfc rotateAndClonePointWithProperties(PointWithPropertiesIfc inputPoint,
        ResultsFromEvaluateCost result) {

    RealVector coordsVector = new ArrayRealVector(
            MathTools.convertToDoubleArray(inputPoint.getCoords().getCoords()));
    RealVector newPointCoords = PairingTools.alignPointFromShape2toShape1(result, coordsVector);
    PointWithPropertiesIfc newPoint = new PointWithProperties();
    newPoint.setCoords(new Point(MathTools.convertToFloatArray(newPointCoords.toArray())));
    newPoint.setStrikingProperties(inputPoint.getStrikingProperties());
    return newPoint;
}

From source file:hits.HitTools.java

public static Float computeRmsdBackboneAtomBetweenHitPeptideAndQueryLigandDefinigQuery(
        ShapeContainerIfc targetShape, ResultsFromEvaluateCost result, ShapeContainerIfc queryShape,
        AlgoParameters algoParameters) {

    boolean isQueryShapeContainerHasPeptideIfc = queryShape instanceof HasPeptideIfc;
    boolean isHitShapeContainerHasPeptideIfc = targetShape instanceof HasPeptideIfc;

    boolean canBeComputed = isQueryShapeContainerHasPeptideIfc && isHitShapeContainerHasPeptideIfc;
    if (!canBeComputed) {
        return null;
    }//from www. j  a v a  2 s. c o  m

    HasPeptideIfc queryShapeWithPeptide = (HasPeptideIfc) queryShape;
    MyChainIfc peptideUsedToBuiltTheQuery = queryShapeWithPeptide.getPeptide();

    HasPeptideIfc currentBestHitWithPeptide = (HasPeptideIfc) targetShape;
    MyChainIfc peptideCurrentBestHit = currentBestHitWithPeptide.getPeptide();

    if (peptideUsedToBuiltTheQuery != null) {

        List<MyAtomIfc> backboneAtomPeptideQuery = extractBackBoneAtoms(peptideUsedToBuiltTheQuery,
                algoParameters);
        List<MyAtomIfc> backboneAtomPeptideHit = extractBackBoneAtoms(peptideCurrentBestHit, algoParameters);
        // put hit in ref frame of query
        List<double[]> coordinatesHit = new ArrayList<>();
        for (MyAtomIfc atomHit : backboneAtomPeptideHit) {
            RealVector newPointCoords = PairingTools.alignPointFromShape2toShape1(result,
                    new ArrayRealVector(MathTools.convertToDoubleArray(atomHit.getCoords())));
            coordinatesHit.add(newPointCoords.toArray());
        }
        List<double[]> coordinatesQuery = new ArrayList<>();
        for (MyAtomIfc atomQuery : backboneAtomPeptideQuery) {
            coordinatesQuery.add(MathTools.convertToDoubleArray(atomQuery.getCoords()));
        }

        List<double[]> smallestChainCoords = coordinatesHit;
        List<double[]> longestChainCoords = coordinatesQuery;
        List<MyAtomIfc> smallestChain = backboneAtomPeptideHit;
        List<MyAtomIfc> longestChain = backboneAtomPeptideQuery;

        if (backboneAtomPeptideHit.size() > backboneAtomPeptideQuery.size()) {
            smallestChain = backboneAtomPeptideQuery;
            longestChain = backboneAtomPeptideHit;
            smallestChainCoords = coordinatesQuery;
            longestChainCoords = coordinatesHit;
        }
        // 10
        // 6
        // pos 0 to pos 4 as start

        List<Integer> posibleStart = new ArrayList<>();

        int countPossibleOverlays = longestChain.size() - smallestChain.size() + 1;
        A: for (int j = 0; j <= countPossibleOverlays; j++) {

            for (int k = 0; k < smallestChain.size(); k++) {
                MyAtomIfc currentAtomLongestchain = longestChain.get(k + j);
                // if any mismatch in atom name I skip the current comparaison
                //System.out.println(String.valueOf(smallestChain.get(k).getAtomName()) + " compared to " + String.valueOf(currentAtomLongestchain.getAtomName()));
                if (!String.valueOf(smallestChain.get(k).getAtomName())
                        .equals(String.valueOf(currentAtomLongestchain.getAtomName()))) {
                    continue A;
                }
            }
            posibleStart.add(j);
        }
        //System.out.println("posibleStart : " + posibleStart);

        // for each possible start I compute the rmsd
        float minRmsd = Float.MAX_VALUE;
        for (int j = 0; j < posibleStart.size(); j++) {

            double rmsd = 0.0;
            for (int k = 0; k < smallestChain.size(); k++) {
                double[] currentAtomSmallestchain = smallestChainCoords.get(k);
                double[] currentAtomLongestchain = longestChainCoords.get(k + posibleStart.get(j));
                double contribRmsd = MathTools.computeDistance(currentAtomSmallestchain,
                        currentAtomLongestchain);
                rmsd += contribRmsd * contribRmsd;
            }
            rmsd = rmsd / smallestChain.size();
            float finalRmsd = (float) Math.sqrt(rmsd);
            if (finalRmsd < minRmsd) {
                minRmsd = finalRmsd;
            }
        }

        return minRmsd;
    }
    return null;
}

From source file:de.termininistic.serein.examples.benchmarks.functions.multimodal.LevyFunction.java

@Override
public double map(RealVector v) {
    double[] x = v.toArray();
    double sum = Math.pow(Math.sin(Math.PI * w(x[0])), 2);
    for (int i = 0; i < x.length - 1; i++) {
        sum += Math.pow((w(x[i]) - 1), 2) * (1 + 10 * Math.pow(Math.sin(2 * Math.PI * w(x[0]) + 1), 2)
                + Math.pow(w(x[x.length - 1]) - 1, 2)
                        * (1 + Math.pow(Math.sin(2 * Math.PI * w(x[x.length - 1]) + 1), 2)));
    }/*from   w ww .  jav  a2s.c o  m*/
    return sum;
}