Example usage for org.apache.commons.math3.linear Array2DRowRealMatrix Array2DRowRealMatrix

List of usage examples for org.apache.commons.math3.linear Array2DRowRealMatrix Array2DRowRealMatrix

Introduction

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

Prototype

public Array2DRowRealMatrix(final double[][] d, final boolean copyArray)
        throws DimensionMismatchException, NoDataException, NullArgumentException 

Source Link

Document

Create a new RealMatrix using the input array as the underlying data array.

Usage

From source file:mase.app.allocation.AllocationProblem.java

@Override
public EvaluationResult[] evaluateSolution(GroupController gc, long seed) {
    AgentController[] acs = gc.getAgentControllers(numAgents);
    RealMatrix distanceMatrix = new Array2DRowRealMatrix(numAgents, types.length);
    for (int i = 0; i < numAgents; i++) {
        AllocationAgent aa = (AllocationAgent) acs[i];
        for (int j = 0; j < types.length; j++) {
            distanceMatrix.setEntry(i, j, DIST.compute(aa.getLocation(), types[j]));
        }//from w w w. ja va 2  s.  c  om
    }

    DescriptiveStatistics pd = pairDistances(distanceMatrix);

    // fitness
    FitnessResult fr = new FitnessResult(1 - pd.getMean() / FastMath.sqrt(dimensions));

    // individual characterisation -- distance to each type
    List<EvaluationResult> vbrs = new ArrayList<>();
    for (double[] dists : distanceMatrix.getData()) {
        vbrs.add(new VectorBehaviourResult(dists));
    }
    CompoundEvaluationResult ser = new CompoundEvaluationResult(vbrs);

    // aux characterisation -- min, mean, max, sd pair distances
    VectorBehaviourResult aux = new VectorBehaviourResult(pd.getMin(), pd.getMean(), pd.getMax(),
            pd.getStandardDeviation());

    return new EvaluationResult[] { fr, aux, ser };
}

From source file:net.myrrix.common.math.MatrixUtils.java

/**
 * @param M tall, skinny matrix//from  w ww.  j a  v a2 s.  c  o  m
 * @return MT * M as a dense matrix
 */
public static RealMatrix transposeTimesSelf(FastByIDMap<float[]> M) {
    if (M == null || M.isEmpty()) {
        return null;
    }
    RealMatrix result = null;
    for (FastByIDMap.MapEntry<float[]> entry : M.entrySet()) {
        float[] vector = entry.getValue();
        int dimension = vector.length;
        if (result == null) {
            result = new Array2DRowRealMatrix(dimension, dimension);
        }
        for (int row = 0; row < dimension; row++) {
            float rowValue = vector[row];
            for (int col = 0; col < dimension; col++) {
                result.addToEntry(row, col, rowValue * vector[col]);
            }
        }
    }
    Preconditions.checkNotNull(result);
    return result;
}

From source file:com.clust4j.data.DataSet.java

public void addColumn(String s, double[] col) {
    VecUtils.checkDims(col);/*from w ww  .j  a v a  2 s .  co m*/

    final int m = col.length;
    if (m != data.getRowDimension())
        throw new DimensionMismatchException(m, data.getRowDimension());

    final int n = data.getColumnDimension();
    s = null == s ? (COL_PREFIX + n) : s;

    String[] newHeaders = new String[n + 1];
    double[][] newData = new double[m][n + 1];
    double[][] oldData = data.getDataRef();

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n + 1; j++) {
            if (i == 0)
                newHeaders[j] = j != n ? headers[j] : s;
            newData[i][j] = j != n ? oldData[i][j] : col[i];
        }
    }

    this.headers = newHeaders;
    this.data = new Array2DRowRealMatrix(newData, false);
}

From source file:gamlss.utilities.WLSMultipleLinearRegression.java

/**
* {@inheritDoc}//from   ww w.j  a v  a  2 s  .c om
* <p>This implementation computes and caches the QR decomposition of the X matrix
* once it is successfully loaded.</p>
*/
protected void newXSampleData(double[][] x, ArrayRealVector w) {
    if (x == null) {
        throw new NullArgumentException();
    }
    if (x.length == 0) {
        throw new NoDataException();
    }
    if (this.isNoIntercept()) {
        this.xMatrix = new Array2DRowRealMatrix(x, true);
    } else { // Augment design matrix with initial unitary column
        final int nVars = x[0].length;
        final double[][] xAug = new double[x.length][nVars + 1];
        for (int i = 0; i < x.length; i++) {
            if (x[i].length != nVars) {
                throw new DimensionMismatchException(x[i].length, nVars);
            }
            xAug[i][0] = w.getEntry(i);
            System.arraycopy(x[i], 0, xAug[i], 1, nVars);
        }
        this.xMatrix = new Array2DRowRealMatrix(xAug, false);
    }
    this.qr = new QRDecomposition(getX());
}

From source file:edu.tum.cs.vis.model.util.algorithm.ACCUM.java

/**
 * Calculate curvature for vertices of triangle
 * //  w w w.  java2s  .  c  o  m
 * @param curvatures
 *            vertex curvature mapping
 * @param tri
 *            triangle to calculate curvature for
 */
static void calculateCurvatureForTriangle(HashMap<Vertex, Curvature> curvatures, Triangle tri) {
    // Edges
    Vector3f e[] = tri.getEdges();

    // N-T-B coordinate system per face
    Vector3f t = new Vector3f(e[0]);
    t.normalize();
    Vector3f n = new Vector3f();
    n.cross(e[0], e[1]);
    Vector3f b = new Vector3f();
    b.cross(n, t);
    b.normalize();

    // Estimate curvature based on variation of normals
    // along edges
    float m[] = { 0, 0, 0 };
    double w[][] = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } };
    for (int j = 0; j < 3; j++) {

        float u = e[j].dot(t);
        float v = e[j].dot(b);
        w[0][0] += u * u;
        w[0][1] += u * v;
        // w[1][1] += v*v + u*u;
        // w[1][2] += u*v;
        w[2][2] += v * v;
        Vector3f dn = new Vector3f(tri.getPosition()[(j + 2) % 3].getNormalVector());
        dn.sub(tri.getPosition()[(j + 1) % 3].getNormalVector());
        float dnu = dn.dot(t);
        float dnv = dn.dot(b);
        m[0] += dnu * u;
        m[1] += dnu * v + dnv * u;
        m[2] += dnv * v;
    }
    w[1][1] = w[0][0] + w[2][2];
    w[1][2] = w[0][1];

    RealMatrix coefficients = new Array2DRowRealMatrix(w, false);
    DecompositionSolver solver = new LUDecomposition(coefficients).getSolver();
    if (!solver.isNonSingular()) {
        return;
    }

    RealVector constants = new ArrayRealVector(new double[] { m[0], m[1], m[2] }, false);
    RealVector solution = solver.solve(constants);

    m[0] = (float) solution.getEntry(0);
    m[1] = (float) solution.getEntry(1);
    m[2] = (float) solution.getEntry(2);

    // Push it back out to the vertices
    for (int j = 0; j < 3; j++) {
        Vertex vj = tri.getPosition()[j];

        float c1, c12, c2;
        float ret[] = proj_curv(t, b, m[0], m[1], m[2], curvatures.get(vj).getPrincipleDirectionMax(),
                curvatures.get(vj).getPrincipleDirectionMin());
        c1 = ret[0];
        c12 = ret[1];
        c2 = ret[2];

        Curvature c = curvatures.get(vj);

        double wt;
        if (j == 0)
            wt = tri.getCornerarea().x / vj.getPointarea();
        else if (j == 1)
            wt = tri.getCornerarea().y / vj.getPointarea();
        else
            wt = tri.getCornerarea().z / vj.getPointarea();

        synchronized (c) {
            c.setCurvatureMax((float) (c.getCurvatureMax() + wt * c1));
            c.setCurvatureMinMax((float) (c.getCurvatureMinMax() + wt * c12));
            c.setCurvatureMin((float) (c.getCurvatureMin() + wt * c2));
        }
    }
}

From source file:com.clust4j.algo.preprocess.PreProcessorTests.java

@Test
public void testMedianCenter() {
    final double[][] data = new double[][] { new double[] { 0.005, 0.182751, 0.1284 },
            new double[] { 3.65816, 0.29518, 2.123316 }, new double[] { 4.1234, 0.27395, 1.8900002 } };

    final Array2DRowRealMatrix d = new Array2DRowRealMatrix(data, false);
    MedianCenterer norm = new MedianCenterer().fit(d);
    RealMatrix scaled = norm.transform(d);
    double[][] operated = scaled.getData();

    assertTrue(Precision.equals(VecUtils.median(MatUtils.getColumn(operated, 0)), 0, Precision.EPSILON));
    assertTrue(Precision.equals(VecUtils.median(MatUtils.getColumn(operated, 1)), 0, Precision.EPSILON));
    assertTrue(Precision.equals(VecUtils.median(MatUtils.getColumn(operated, 2)), 0, Precision.EPSILON));

    // test copy/*w  ww .j  a  v a2 s  .  c  om*/
    operated = norm.copy().transform(data);
    assertTrue(Precision.equals(VecUtils.median(MatUtils.getColumn(operated, 0)), 0, Precision.EPSILON));
    assertTrue(Precision.equals(VecUtils.median(MatUtils.getColumn(operated, 1)), 0, Precision.EPSILON));
    assertTrue(Precision.equals(VecUtils.median(MatUtils.getColumn(operated, 2)), 0, Precision.EPSILON));

    // Test inverse transform.
    assertTrue(MatUtils.equalsWithTolerance(data, norm.inverseTransform(scaled).getData(), 1e-8));

    // copy coverage
    norm.copy();

    // test dim mismatch
    boolean a = false;
    try {
        norm.inverseTransform(TestSuite.getRandom(2, 2));
    } catch (DimensionMismatchException dim) {
        a = true;
    } finally {
        assertTrue(a);
    }

    // test not fit
    a = false;
    try {
        new MedianCenterer().transform(d);
    } catch (ModelNotFitException dim) {
        a = true;
    } finally {
        assertTrue(a);
    }
}

From source file:edu.cudenver.bios.matrix.DesignEssenceMatrix.java

/**
 * Expands the essence matrix into full design matrix for power
 * calculations using the fixed component only
 *
 * Assumes that row meta data indicates the actual number
 * of repetitions of that row in the full design
 *
 * @return design matrix//  w  w w .j av  a  2  s  .com
 * @throws IllegalArgumentException
 */
public RealMatrix getFullDesignMatrixFixed() {
    if (fixedMatrix == null)
        return null;
    // allocate the full design matrix
    // #rows = total of repetitions for each unique row
    // #columns = number of columns in design matrix
    int fullRows = getTotalSampleSize();
    int fullColumns = fixedMatrix.getColumnDimension();
    Array2DRowRealMatrix fullDesignMatrix = new Array2DRowRealMatrix(fullRows, fullColumns);

    // copy in the columns
    // case 1: if predictor in a given column is fixed, the values are copied from
    // the design matrix
    // case 2: if the predictor is random, the values are set to a random value from
    // a normal curve with the mean/variance specified in the column meta data
    int fullDesignColumn = 0;
    for (int col = 0; col < fixedMatrix.getColumnDimension(); col++, fullDesignColumn++) {
        fillFixedColumn(col, fullDesignColumn, fullDesignMatrix);
    }
    return fullDesignMatrix;
}

From source file:com.itemanalysis.psychometrics.mixture.MvNormalMixtureModel.java

public double mStep() {
    RealMatrix[] M = new Array2DRowRealMatrix[groups];
    RealMatrix[] S = new Array2DRowRealMatrix[groups];
    double[] T1 = new double[groups];
    RealMatrix[] T2 = new Array2DRowRealMatrix[groups];
    RealMatrix[] T3 = new Array2DRowRealMatrix[groups];
    double pp = 0.0;
    RealMatrix rowData = null;//  w w w. j  av a 2s  .c  o  m
    RealMatrix temp = null;

    try {
        //estimate new means, covariances, and mixing proportions
        for (int g = 0; g < groups; g++) {
            T2[g] = new Array2DRowRealMatrix(dimensions, 1);
            T3[g] = new Array2DRowRealMatrix(dimensions, dimensions);
            for (int i = 0; i < sampleSize; i++) {
                pp = posteriorProbability(g, i);
                rowData = data.getRowMatrix(i).transpose();
                T1[g] += pp;
                T2[g] = T2[g].add(rowData.scalarMultiply(pp));
                temp = rowData.scalarMultiply(pp).multiply(rowData.transpose());
                T3[g] = T3[g].add(temp);
            }

        }

        for (int g = 0; g < groups; g++) {
            M[g] = T2[g].scalarMultiply(1.0 / T1[g]);
            temp = T2[g].scalarMultiply(1.0 / T1[g]).multiply(T2[g].transpose());
            S[g] = T3[g].subtract(temp).scalarMultiply(1.0 / T1[g]);
        }
    } catch (SingularMatrixException ex) {
        statusMessage = "Singular Matrix";
    }

    //apply constraints
    if (sameVarianceWithin)
        setCommonVarianceWithinClass(S);
    if (sameCovarianceWithin && !localIndependence)
        setCommonCovarianceWithinClass(S);
    if (localIndependence)
        setLocalIndependence(S);
    if (sameCovarianceBetween)
        setCommonCovariance(S);

    piKp1 = computeMixingProportions();

    //set values of new estimates for eStep (i.e. posterior probability) and computation of loglikelihood
    MvNormalComponentDistribution dist = null;
    for (int g = 0; g < groups; g++) {
        dist = (MvNormalComponentDistribution) compDistribution[g];
        dist.setMixingProportion(piKp1[g]);
        dist.setMean(M[g]);
        dist.setCovariance(S[g]);
    }

    double ll = loglikelihood();
    return ll;
}

From source file:com.joptimizer.functions.SOCPLogarithmicBarrier.java

private RealMatrix buildJ(SOCPConstraintParameters param, RealVector X) {
    RealMatrix J = new Array2DRowRealMatrix(dim, param.getA().getRowDimension() + 1);
    J.setSubMatrix(param.getA().transpose().getData(), 0, 0);
    J.setColumnVector(param.getA().getRowDimension(), param.getC());
    return J;/*from w ww . j  ava  2 s  . co m*/
}

From source file:com.clust4j.algo.MeanShiftTests.java

@Test
public void testMeanShiftAutoBwEstimate1() {
    final double[][] x = TestSuite.bigMatrix;
    double bw = MeanShift.autoEstimateBW(new Array2DRowRealMatrix(x, false), 0.3, Distance.EUCLIDEAN,
            new Random(), false);
    new MeanShift(new Array2DRowRealMatrix(x), bw).fit();
}