Example usage for org.apache.commons.math.linear RealVector getData

List of usage examples for org.apache.commons.math.linear RealVector getData

Introduction

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

Prototype

double[] getData();

Source Link

Document

Returns vector entries as a double array.

Usage

From source file:com.opengamma.analytics.math.util.wrapper.CommonsMathWrapper.java

/**
 * @param x A Commons vector, not null/*  ww  w. ja va2  s  .c o  m*/
 * @return An OG 1-D matrix of doubles
 */
public static DoubleMatrix1D unwrap(final RealVector x) {
    Validate.notNull(x);
    return new DoubleMatrix1D(x.getData());
}

From source file:gda.spring.propertyeditors.RealVectorPropertyEditorTest.java

protected void assertVectorsEqual(double[] expected, RealVector actual) {
    assertEquals("Length does not match", expected.length, actual.getDimension());
    for (int i = 0; i < expected.length; i++) {
        assertEquals("Element " + i + " does not match", expected[i], actual.getData()[i]);
    }//w w  w . j  av a  2s  .co  m
}

From source file:io.seldon.mf.RecentMfRecommender.java

public double[] createAvgProductVector(List<Long> recentitemInteractions, Map<Long, float[]> productFeatures) {
    int numLatentFactors = productFeatures.values().iterator().next().length;
    double[] userFeatures = new double[numLatentFactors];
    for (Long item : recentitemInteractions) {
        float[] productFactors = productFeatures.get(item);
        if (productFactors != null) {
            for (int feature = 0; feature < numLatentFactors; feature++) {
                userFeatures[feature] += productFactors[feature];
            }//from   ww w.  j  av a 2s  . c  o m
        }
    }
    RealVector userFeaturesAsVector = new ArrayRealVector(userFeatures);
    RealVector normalised = userFeaturesAsVector.mapDivide(userFeaturesAsVector.getL1Norm());

    return normalised.getData();
}

From source file:gda.images.camera.SampleMovementServiceBase.java

@Override
 public void moveSampleByMicronsAlongBeamlineAxes(double x, double y, double z) throws DeviceException {
     logger.debug(String.format("move in microns (beamline axes): (x=%.2f, y=%.2f, z=%.2f)", x, y, z));
     double[] currentPos = getPosition();
     RealVector currentPosVector = MatrixUtils.createRealVector(currentPos);
     logger.debug(String.format("current position is %s", currentPosVector));
     RealVector move = MatrixUtils.createRealVector(new double[] { x, y, z });
     RealVector newPosition = currentPosVector.add(move);
     logger.debug(String.format("new position is %s", newPosition));
     setPosition(newPosition.getData());
 }

From source file:de.mpicbg.knime.hcs.base.nodes.preproc.OutlierRemoval.java

@Override
protected BufferedDataTable[] execute(BufferedDataTable[] inData, ExecutionContext exec) throws Exception {

    BufferedDataTable input = inData[0];
    DataTableSpec inputSpec = input.getDataTableSpec();

    // Get the parameter and make sure there all double value columns
    List<Attribute> parameter = new ArrayList<Attribute>();
    for (String item : parameterNames.getIncludeList()) {
        Attribute attribute = new InputTableAttribute(item, input);
        if (attribute.getType().isCompatible(DoubleValue.class)) {
            parameter.add(attribute);/*from ww  w . ja  v  a 2 s.com*/
        } else {
            logger.warn("The parameter '" + attribute.getName()
                    + "' will not be considered for outlier removal, since it is not compatible to double.");
        }
    }

    // Get the groups defined by the nominal column.
    Attribute groupingAttribute = new InputTableAttribute(this.groupingColumn.getStringValue(), input);
    Map<Object, List<DataRow>> subsets = AttributeUtils.splitRowsGeneric(input, groupingAttribute);

    // Initialize
    BufferedDataContainer keepContainer = exec.createDataContainer(inputSpec);
    BufferedDataContainer discartContainer = exec.createDataContainer(inputSpec);
    int S = subsets.size();
    int s = 1;

    // Outlier analysis for each subset
    for (Object key : subsets.keySet()) {

        // Get the subset having all constraints in common
        List<DataRow> rowSubset = subsets.get(key);

        // Get the valid values
        RealMatrix data = extractMatrix(rowSubset, parameter);

        int N = data.getColumnDimension();
        int M = data.getRowDimension();
        if (M == 0) {
            logger.warn("The group '" + key + "' has no valid values and will be removed entirely'");
        } else {

            // Determine upper and lower outlier bounds
            double[] lowerBound = new double[N];
            double[] upperBound = new double[N];
            if (method.getStringValue().equals("Boxplot")) {
                for (int c = 0; c < N; ++c) {
                    RealVector vect = data.getColumnVector(c);
                    DescriptiveStatistics stats = new DescriptiveStatistics();
                    for (double value : vect.getData()) {
                        stats.addValue(value);
                    }
                    double lowerQuantile = stats.getPercentile(25);
                    double upperQuantile = stats.getPercentile(85);
                    double whisker = factor.getDoubleValue() * Math.abs(lowerQuantile - upperQuantile);
                    lowerBound[c] = lowerQuantile - whisker;
                    upperBound[c] = upperQuantile + whisker;
                }
            } else {
                for (int c = 0; c < N; ++c) {
                    RealVector vect = data.getColumnVector(c);
                    double mean = StatUtils.mean(vect.getData());
                    double sd = Math.sqrt(StatUtils.variance(vect.getData()));
                    lowerBound[c] = mean - factor.getDoubleValue() * sd;
                    upperBound[c] = mean + factor.getDoubleValue() * sd;
                }
            }

            // Remove The outlier
            if (rule.getBooleanValue()) { // The row is only discarted if the row is an outlier in all parameter.
                for (DataRow row : rowSubset) {
                    int c = 0;
                    for (Attribute column : parameter) {

                        DataCell valueCell = row.getCell(((InputTableAttribute) column).getColumnIndex());

                        // a missing value will be treated as data point inside the bounds
                        if (valueCell.isMissing()) {
                            continue;
                        }

                        Double value = ((DoubleValue) valueCell).getDoubleValue();
                        if ((value != null) && (lowerBound[c] <= value) && (value <= upperBound[c])) {
                            break;
                        } else {
                            c++;
                        }
                    }
                    if (c != N) {
                        keepContainer.addRowToTable(row);
                    } else {
                        discartContainer.addRowToTable(row);
                    }
                }
            } else { // The row is discarted if it has a outlier for at least one parameter.
                for (DataRow row : rowSubset) {
                    int c = 0;
                    for (Attribute column : parameter) {

                        DataCell valueCell = row.getCell(((InputTableAttribute) column).getColumnIndex());

                        // a missing value will be treated as data point inside the bounds
                        if (valueCell.isMissing()) {
                            c++;
                            continue;
                        }

                        Double value = ((DoubleValue) valueCell).getDoubleValue();
                        if ((value != null) && (lowerBound[c] <= value) && (value <= upperBound[c])) {
                            c++;
                        } else {
                            break;
                        }
                    }
                    if (c == N) {
                        keepContainer.addRowToTable(row);
                    } else {
                        discartContainer.addRowToTable(row);
                    }
                }
            }
        }

        BufTableUtils.updateProgress(exec, s++, S);

    }

    keepContainer.close();
    discartContainer.close();
    return new BufferedDataTable[] { keepContainer.getTable(), discartContainer.getTable() };
}

From source file:eu.amidst.core.exponentialfamily.EF_Normal_NormalParents2.java

/**
 * {@inheritDoc}//from   w  ww  . jav a 2s.c  om
 */
@Override
public void updateNaturalFromMomentParameters() {

    /*
     * First step: means and convariances
     */
    CompoundVector globalMomentParam = (CompoundVector) this.momentParameters;
    double mean_X = globalMomentParam.getXYbaseMatrix().getEntry(0);
    RealVector mean_Y = globalMomentParam.getTheta_beta0BetaRV();

    double cov_XX = globalMomentParam.getcovbaseMatrix().getEntry(0, 0) - mean_X * mean_X;
    RealMatrix cov_YY = globalMomentParam.getcovbaseMatrix().getSubMatrix(1, nOfParents, 1, nOfParents)
            .subtract(mean_Y.outerProduct(mean_Y));
    RealVector cov_XY = globalMomentParam.getcovbaseMatrix().getSubMatrix(0, 0, 1, nOfParents).getRowVector(0)
            .subtract(mean_Y.mapMultiply(mean_X));
    //RealVector cov_YX = cov_XY; //outerProduct transposes the vector automatically

    /*
     * Second step: betas and variance
     */
    RealMatrix cov_YYInverse = new LUDecompositionImpl(cov_YY).getSolver().getInverse();
    RealVector beta = cov_YYInverse.preMultiply(cov_XY);

    double beta_0 = mean_X - beta.dotProduct(mean_Y);
    double variance = cov_XX - beta.dotProduct(cov_XY);

    /*
     * Third step: natural parameters (5 in total)
     */

    /*
     * 1) theta_0
     */
    double theta_0 = beta_0 / variance;
    double[] theta_0array = { theta_0 };

    /*
     * 2) theta_0Theta
     */
    double variance2Inv = 1.0 / (2 * variance);
    RealVector theta_0Theta = beta.mapMultiply(-beta_0 / variance);
    ((CompoundVector) this.naturalParameters)
            .setXYbaseVector(new ArrayRealVector(theta_0array, theta_0Theta.getData()));

    /*
     * 3) theta_Minus1
     */
    double theta_Minus1 = -variance2Inv;

    /*
     * 4) theta_beta
     */
    RealVector theta_beta = beta.mapMultiply(variance2Inv);

    /*
     * 5) theta_betaBeta
     */
    RealMatrix theta_betaBeta = beta.outerProduct(beta).scalarMultiply(-variance2Inv * 2);

    /*
     * Store natural parameters
     */
    RealMatrix natural_XY = new Array2DRowRealMatrix(nOfParents + 1, nOfParents + 1);
    double[] theta_Minus1array = { theta_Minus1 };
    RealVector covXY = new ArrayRealVector(theta_Minus1array, theta_beta.getData());
    natural_XY.setColumnVector(0, covXY);
    natural_XY.setRowVector(0, covXY);
    natural_XY.setSubMatrix(theta_betaBeta.getData(), 1, 1);
    ((CompoundVector) this.naturalParameters).setcovbaseVector(natural_XY);

}

From source file:org.deegree.geometry.linearization.CurveLinearizer.java

private double[] solveLinearEquation(double[][] matrixA, double[] vectorb) {

    RealMatrix coefficients = new Array2DRowRealMatrix(matrixA, false);

    // LU-decomposition
    DecompositionSolver solver = new LUDecompositionImpl(coefficients).getSolver();

    RealVector constants = new ArrayRealVector(vectorb, false);
    RealVector solution = null;
    try {/*from   w  ww.j  av  a2s  .  c  om*/
        solution = solver.solve(constants);
    } catch (SingularMatrixException e) {
        LOG.error(e.getLocalizedMessage());
        e.printStackTrace();
    }
    return solution.getData();
}

From source file:org.plista.kornakapi.core.recommender.FoldingFactorization.java

public double[] foldInAnonymousUser(long[] itemIDs) throws NoSuchItemException {

    double[] userFeatures = new double[factorization.numFeatures()];
    for (long itemID : itemIDs) {
        try {//from   ww w .  ja v  a  2s . co  m
            int itemIndex = factorization.itemIndex(itemID);
            for (int feature = 0; feature < factorization.numFeatures(); feature++) {
                userFeatures[feature] += factorization.allItemFeatures()[itemIndex][feature];
            }
        } catch (NoSuchItemException e) {
            if (log.isDebugEnabled()) {
                log.debug("Item unknown: {}", itemID);
                if (itemIDs.length == 1) {
                    throw new NoSuchItemException("At least one item must be known");
                }
            }
        }
    }
    RealVector userFeaturesAsVector = new ArrayRealVector(userFeatures);
    RealVector normalised = userFeaturesAsVector.mapDivide(userFeaturesAsVector.getL1Norm());

    return normalised.getData();
}