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

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

Introduction

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

Prototype

public ArrayRealVector(ArrayRealVector v) throws NullArgumentException 

Source Link

Document

Construct a vector from another vector, using a deep copy.

Usage

From source file:com.bolatu.gezkoncsvlogger.GyroOrientation.RotationKalmanFilter.java

/**
 * Creates a new Kalman filter with the given process and measurement
 * models./*from  w w w.  java2  s.c om*/
 *
 * @param process
 *            the model defining the underlying process dynamics
 * @param measurement
 *            the model defining the given measurement characteristics
 * @throws NullArgumentException
 *             if any of the given inputs is null (except for the control
 *             matrix)
 * @throws NonSquareMatrixException
 *             if the transition matrix is non square
 * @throws DimensionMismatchException
 *             if the column dimension of the transition matrix does not
 *             match the dimension of the initial state estimation vector
 * @throws MatrixDimensionMismatchException
 *             if the matrix dimensions do not fit together
 */
public RotationKalmanFilter(final ProcessModel process, final MeasurementModel measurement)
        throws NullArgumentException, NonSquareMatrixException, DimensionMismatchException,
        MatrixDimensionMismatchException {

    MathUtils.checkNotNull(process);
    MathUtils.checkNotNull(measurement);

    this.processModel = process;
    this.measurementModel = measurement;

    transitionMatrix = processModel.getStateTransitionMatrix();
    MathUtils.checkNotNull(transitionMatrix);
    transitionMatrixT = transitionMatrix.transpose();

    // create an empty matrix if no control matrix was given
    if (processModel.getControlMatrix() == null) {
        controlMatrix = new Array2DRowRealMatrix();
    } else {
        controlMatrix = processModel.getControlMatrix();
    }

    measurementMatrix = measurementModel.getMeasurementMatrix();
    MathUtils.checkNotNull(measurementMatrix);
    measurementMatrixT = measurementMatrix.transpose();

    // check that the process and measurement noise matrices are not null
    // they will be directly accessed from the model as they may change
    // over time
    RealMatrix processNoise = processModel.getProcessNoise();
    MathUtils.checkNotNull(processNoise);
    RealMatrix measNoise = measurementModel.getMeasurementNoise();
    MathUtils.checkNotNull(measNoise);

    // set the initial state estimate to a zero vector if it is not
    // available from the process model
    if (processModel.getInitialStateEstimate() == null) {
        stateEstimation = new ArrayRealVector(transitionMatrix.getColumnDimension());
    } else {
        stateEstimation = processModel.getInitialStateEstimate();
    }

    if (transitionMatrix.getColumnDimension() != stateEstimation.getDimension()) {
        throw new DimensionMismatchException(transitionMatrix.getColumnDimension(),
                stateEstimation.getDimension());
    }

    // initialize the error covariance to the process noise if it is not
    // available from the process model
    if (processModel.getInitialErrorCovariance() == null) {
        errorCovariance = processNoise.copy();
    } else {
        errorCovariance = processModel.getInitialErrorCovariance();
    }

    // sanity checks, the control matrix B may be null

    // A must be a square matrix
    if (!transitionMatrix.isSquare()) {
        throw new NonSquareMatrixException(transitionMatrix.getRowDimension(),
                transitionMatrix.getColumnDimension());
    }

    // row dimension of B must be equal to A
    // if no control matrix is available, the row and column dimension will
    // be 0
    if (controlMatrix != null && controlMatrix.getRowDimension() > 0 && controlMatrix.getColumnDimension() > 0
            && controlMatrix.getRowDimension() != transitionMatrix.getRowDimension()) {
        throw new MatrixDimensionMismatchException(controlMatrix.getRowDimension(),
                controlMatrix.getColumnDimension(), transitionMatrix.getRowDimension(),
                controlMatrix.getColumnDimension());
    }

    // Q must be equal to A
    MatrixUtils.checkAdditionCompatible(transitionMatrix, processNoise);

    // column dimension of H must be equal to row dimension of A
    if (measurementMatrix.getColumnDimension() != transitionMatrix.getRowDimension()) {
        throw new MatrixDimensionMismatchException(measurementMatrix.getRowDimension(),
                measurementMatrix.getColumnDimension(), measurementMatrix.getRowDimension(),
                transitionMatrix.getRowDimension());
    }

    // row dimension of R must be equal to row dimension of H
    if (measNoise.getRowDimension() != measurementMatrix.getRowDimension()) {
        throw new MatrixDimensionMismatchException(measNoise.getRowDimension(), measNoise.getColumnDimension(),
                measurementMatrix.getRowDimension(), measNoise.getColumnDimension());
    }
}

From source file:edu.oregonstate.eecs.mcplan.abstraction.EvaluateSimilarityFunction.java

public static ClusterContingencyTable evaluateClustering(final MetricSimilarityFunction f,
        final Instances single, final int max_branching) {
    final StreamingClusterer clusterer = new StreamingClusterer(f, max_branching);
    final Map<Integer, Set<RealVector>> Umap = new TreeMap<Integer, Set<RealVector>>();
    final Map<Integer, Set<RealVector>> Vmap = new TreeMap<Integer, Set<RealVector>>();

    for (final Instance i : single) {
        final double[] phi = WekaUtil.unlabeledFeatures(i);

        final int cluster = clusterer.clusterState(phi);
        Set<RealVector> u = Umap.get(cluster);
        if (u == null) {
            u = new HashSet<RealVector>();
            Umap.put(cluster, u);/*from   w  ww. j  a va2  s.  c  o  m*/
        }
        u.add(new ArrayRealVector(phi));

        final int true_label = (int) i.classValue();
        Set<RealVector> v = Vmap.get(true_label);
        if (v == null) {
            v = new HashSet<RealVector>();
            Vmap.put(true_label, v);
        }
        v.add(new ArrayRealVector(phi));
    }

    final ArrayList<Set<RealVector>> U = new ArrayList<Set<RealVector>>();
    for (final Map.Entry<Integer, Set<RealVector>> e : Umap.entrySet()) {
        U.add(e.getValue());
    }

    final ArrayList<Set<RealVector>> V = new ArrayList<Set<RealVector>>();
    for (final Map.Entry<Integer, Set<RealVector>> e : Vmap.entrySet()) {
        V.add(e.getValue());
    }

    return new ClusterContingencyTable(U, V);
}

From source file:gamlss.distributions.GT.java

/** Calculate and set initial value of nu.
 * @param y - vector of values of response variable
 * @return vector of initial values of nu
 *//*from w w  w . j  a v  a 2  s.c om*/
private ArrayRealVector setNuInitial(final ArrayRealVector y) {
    //nu.initial = expression(nu <- rep(5, length(y))),
    tempV = new ArrayRealVector(y.getDimension());
    tempV.set(5.0);
    return tempV;
}

From source file:edu.utexas.cs.tactex.tariffoptimization.TariffOptimizierTOUFixedMargin.java

private ArrayRealVector computeEnergyUnitCosts(CostCurvesPredictor costCurvesPredictor,
        ArrayRealVector predictedMyCustomersEnergy, ArrayRealVector predictedCompetitorsEnergy,
        int currentTimeslot) {
    ArrayRealVector energyUnitCosts = new ArrayRealVector(predictedMyCustomersEnergy.getDimension());
    for (int i = 0; i < energyUnitCosts.getDimension(); ++i) {
        int futureTimeslot = currentTimeslot + i + 1; // +1 since energy record starts next timeslot
        energyUnitCosts.setEntry(i,/*w w w.  j  a v a 2s  .  c om*/
                costCurvesPredictor.predictUnitCostKwh(currentTimeslot, futureTimeslot,
                        predictedMyCustomersEnergy.getEntry(i), predictedCompetitorsEnergy.getEntry(i))
                        + costCurvesPredictor.getFudgeFactorKwh(currentTimeslot));
    }
    //log.debug("energyUnitCosts =" + energyUnitCosts.toString());
    return energyUnitCosts;
}

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

@Test
public void testwls9() {

    for (int i = 0; i < this.x.getDimension(); i++) {
        this.x.setEntry(i, i);
        this.w.setEntry(i, i);
    }/*w w w.  j  a  va2s  .  c  o  m*/

    double[] testY = { 5, 17, 8, 2, 1 };

    this.y = new ArrayRealVector(testY);

    this.expected.setEntry(0, 0.83);
    this.expected.setEntry(1, 0);

    this.bslf.disableIntercept();

    this.result = this.bslf.wlsFit(x, y, w);

    this.success &= (this.result.subtract(this.expected).getNorm() < this.eps);

    assertTrue(success);

}

From source file:gamlss.distributions.NO.java

/** Second cross derivative of likelihood function in
 *  respect to mu and sigma (d2ldmdd = d2l/dmu*dsigma).
 * @param y - vector of values of response variable
 * @return  a vector of Second cross derivative
 *///from   ww  w . j  av  a  2  s.  c o  m
private ArrayRealVector d2ldmdd(final ArrayRealVector y) {
    //d2ldmdd = function(y) rep(0,length(y) 
    return new ArrayRealVector(y.getDimension());
    // all elemnts are 0's);
}

From source file:gamlss.distributions.ST1.java

/** Calculate and set initial value of sigma.
 * @param y - vector of values of response variable
 * @return vector of initial values of sigma
 *///from www.j ava 2s  .  co m
private ArrayRealVector setSigmaInitial(final ArrayRealVector y) {
    //sigma.initial = expression(sigma <- rep(sd(y)/4, length(y))),
    tempV = new ArrayRealVector(y.getDimension());
    final double out = new StandardDeviation().evaluate(y.getDataRef());
    tempV.set(out / 4);
    return tempV;
}

From source file:gamlss.distributions.GT.java

/** Calculates initial value of tau.
 * @param y - vector of values of response variable
 * @return vector of initial values of tau
 *///www. j  a  v a2s .  c  om
private ArrayRealVector setTauInitial(final ArrayRealVector y) {
    //tau.initial = expression(tau <-rep(2, length(y)))
    tempV = new ArrayRealVector(y.getDimension());
    tempV.set(2.0);
    return tempV;
}

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());
    }/* ww w.ja  v  a  2s .com*/

    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:com.joptimizer.algebra.CholeskySparseFactorizationTest.java

/**
 * Tests vector and matrix solve method.
 *//*w w  w .  j av  a2s  . c  om*/
public void testFromFile3() throws Exception {
    log.debug("testFromFile3");
    String matrixId = "3";
    double[][] G = Utils
            .loadDoubleMatrixFromFile("factorization" + File.separator + "matrix" + matrixId + ".csv");
    RealMatrix Q = MatrixUtils.createRealMatrix(G);
    int dim = Q.getRowDimension();

    CholeskySparseFactorization myc = new CholeskySparseFactorization(new SparseDoubleMatrix2D(G));
    myc.factorize();

    //solve for a vector
    RealVector b = new ArrayRealVector(Utils.randomValuesVector(dim, -0.5, 0.5, new Long(dim)).toArray());
    RealVector x = new ArrayRealVector(myc.solve(F1.make(b.toArray())).toArray());

    //b - Q.x
    double n1 = b.subtract(Q.operate(x)).getNorm();
    double sr1 = Utils.calculateScaledResidual(G, x.toArray(), b.toArray());
    log.debug("||b - Q.x||: " + n1);
    log.debug("scaled res : " + sr1);
    assertTrue(n1 < 1.E-8);
    assertTrue(sr1 < Utils.getDoubleMachineEpsilon());

    //solve for a matrix
    RealMatrix B = new Array2DRowRealMatrix(
            Utils.randomValuesMatrix(dim, 10, -0.5, 0.5, new Long(dim)).toArray());
    RealMatrix X = new Array2DRowRealMatrix(myc.solve(F2.make(B.getData())).toArray());

    //B - Q.X
    double n2 = B.subtract(Q.multiply(X)).getNorm();
    double sr2 = Utils.calculateScaledResidual(G, X.getData(), B.getData());
    log.debug("||B - Q.X||: " + n2);
    log.debug("scaled res : " + sr2);
    assertTrue(n2 < 1.E-8);
    assertTrue(sr2 < Utils.getDoubleMachineEpsilon());
}