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.mycompany.myfirstindoorsapp.PagedActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.pointMode:
        item.setChecked(true);/*from www  . ja  v a 2  s  .c  o  m*/
        mesureMode = POINTMODE;
        createdOverlays = refreshOverlay(createdOverlays);
        twoPoints[0] = null;
        twoPoints[1] = null;
        singlePoint = null;
        return true;
    case R.id.lineMode:
        item.setChecked(true);
        mesureMode = LINEMODE;
        createdOverlays = refreshOverlay(createdOverlays);
        twoPoints[0] = null;
        twoPoints[1] = null;
        singlePoint = null;
        return true;
    case R.id.menu_startMesurement:
        // begin mesurement
        if ((currentPosition == null) || ((singlePoint == null) && (twoPoints[0] == null))) {
            Toast.makeText(this, "Set pts", Toast.LENGTH_SHORT).show();
        } else {

            double[] coord = new double[4];
            coord[0] = currentPosition.x;
            coord[1] = currentPosition.y;
            coord[2] = 0;
            coord[3] = 0;
            RealVector x = new ArrayRealVector(coord);
            kalman = new Kalman(accelNoise, measurementNoise, x);
            accel.start(mesureMode);
            if ((mesureMode == POINTMODE) && (singlePoint != null)) {
                data = new Data(singlePoint);
                Toast.makeText(this, "new Data (singlePoint)", Toast.LENGTH_SHORT).show();
            }
            if ((mesureMode == LINEMODE) && (twoPoints[0] != null) && (twoPoints[1] != null)) {
                data = new Data(twoPoints[0], twoPoints[1], SystemClock.uptimeMillis());
                Toast.makeText(this, "new Data (twoPoints)", Toast.LENGTH_SHORT).show();
            }
            if ((twoPoints[0] != null) && (twoPoints[1] != null) && (singlePoint != null)) {
                Toast.makeText(this, "singlePoint!=!=!null!=!=!twoPoints[0][1]", Toast.LENGTH_SHORT).show();
            }
            if ((twoPoints[0] == null) && (twoPoints[1] == null) && (singlePoint == null)) {
                Toast.makeText(this, "singlePoint==null==twoPoints[0][1]", Toast.LENGTH_SHORT).show();
            }
        }
        return true;
    case R.id.menu_stopMesurement:
        if (null != data) {
            double[] standartDeviations = data.calc(SystemClock.uptimeMillis());
            accel.stop();
            kalman = null;
            fragment.addItem(pagedActivity, indoorsSurfaceFragment, "Deviation for indoors="
                    + standartDeviations[0] + "; and for Kalman=" + standartDeviations[1],
                    new Coordinate(0, 0, 0));

            Toast.makeText(this, "Deviation for indoors=" + standartDeviations[0] + "; and for " + "Kalman="
                    + standartDeviations[1], Toast.LENGTH_LONG).show();
            data = null;
            if (overlayKalman != null) {
                indoorsSurfaceFragment.removeOverlay(overlayKalman);
                indoorsSurfaceFragment.updateSurface();
            }
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.joptimizer.algebra.CholeskySparseFactorizationTest.java

public void testSimple2() throws Exception {
    log.debug("testSimple2");
    double[][] A = new double[][] { { 4, 0, 0, 1 }, { 0, 4, 0, -1 }, { 0, 0, 6, 1 }, { 1, -1, 1, 6 } };

    CholeskySparseFactorization cs = new CholeskySparseFactorization(new SparseDoubleMatrix2D(A));
    cs.factorize();/*from w w w .  j  ava2s.c  o m*/
    DoubleMatrix2D L = cs.getL();
    DoubleMatrix2D LT = cs.getLT();
    log.debug("L : " + ArrayUtils.toString(L.toArray()));
    log.debug("LT: " + ArrayUtils.toString(LT.toArray()));

    //check the norm ||A.x-b||
    double[] b = new double[] { 1, 2, 3, 4 };
    double[] x = cs.solve(F1.make(b)).toArray();
    double norm = new Array2DRowRealMatrix(A).operate(new ArrayRealVector(x)).subtract(new ArrayRealVector(b))
            .getNorm();
    log.debug("norm: " + norm);
    assertEquals(0., norm, 1.e-15);

    //check the scaled residual
    double residual = Utils.calculateScaledResidual(A, x, b);
    log.debug("residual: " + residual);
    assertEquals(0., residual, Utils.getDoubleMachineEpsilon());
}

From source file:de.bund.bfr.math.LeastSquaresOptimization.java

@Override
public Result optimize(int nParameterSpace, int nOptimizations, boolean stopWhenSuccessful,
        Map<String, Double> minStartValues, Map<String, Double> maxStartValues, int maxIterations,
        DoubleConsumer progressListener, ExecutionContext exec) throws CanceledExecutionException {
    if (exec != null) {
        exec.checkCanceled();/*from ww  w.  jav  a  2  s  .  co m*/
    }

    progressListener.accept(0.0);

    List<ParamRange> ranges = MathUtils.getParamRanges(parameters, minStartValues, maxStartValues,
            nParameterSpace);
    RealVector targetVector = new ArrayRealVector(Doubles.toArray(targetValues));
    List<StartValues> startValuesList = MathUtils.createStartValuesList(ranges, nOptimizations,
            values -> targetVector
                    .getDistance(new ArrayRealVector(optimizerFunction.value(Doubles.toArray(values)))),
            progress -> progressListener.accept(0.5 * progress), exec);
    LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
    Result result = new Result();
    AtomicInteger count = new AtomicInteger(0);

    for (StartValues startValues : startValuesList) {
        if (exec != null) {
            exec.checkCanceled();
        }

        progressListener.accept(0.5 * count.get() / startValuesList.size() + 0.5);

        try {
            LeastSquaresBuilder builder = createLeastSquaresBuilder(startValues.getValues(), maxIterations);

            builder.checker((iteration, previous, current) -> {
                double currentProgress = (double) iteration / (double) maxIterations;

                if (exec != null) {
                    try {
                        exec.checkCanceled();
                    } catch (CanceledExecutionException e) {
                        return true;
                    }
                }

                progressListener.accept(0.5 * (count.get() + currentProgress) / startValuesList.size() + 0.5);
                return iteration == maxIterations;
            });

            LeastSquaresOptimizer.Optimum optimizerResults = optimizer.optimize(builder.build());

            if (exec != null) {
                exec.checkCanceled();
            }

            double cost = optimizerResults.getCost();

            if (result.sse == null || cost * cost < result.sse) {
                result = getResults(optimizerResults);

                if (result.sse == 0.0) {
                    break;
                }

                if (result.r2 != null && result.r2 > 0.0 && stopWhenSuccessful) {
                    break;
                }
            }
        } catch (TooManyEvaluationsException | TooManyIterationsException | ConvergenceException e) {
        }

        count.incrementAndGet();
    }

    return result;
}

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

public static ClusterContingencyTable evaluateClassifier(final Classifier classifier, final Instances test) {
    try {/*w ww  .  j a  v  a 2s .co m*/
        final Map<Integer, Set<RealVector>> Umap = new TreeMap<Integer, Set<RealVector>>();
        final Map<Integer, Set<RealVector>> Vmap = new TreeMap<Integer, Set<RealVector>>();

        final Remove rm_filter = new Remove();
        rm_filter.setAttributeIndicesArray(new int[] { test.classIndex() });
        rm_filter.setInputFormat(test);

        for (final Instance i : test) {
            rm_filter.input(i);
            final double[] phi = rm_filter.output().toDoubleArray();
            //            final double[] phi = WekaUtil.unlabeledFeatures( i );

            final int cluster = (int) classifier.classifyInstance(i);
            Set<RealVector> u = Umap.get(cluster);
            if (u == null) {
                u = new HashSet<RealVector>();
                Umap.put(cluster, u);
            }
            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);
    } catch (final RuntimeException ex) {
        throw ex;
    } catch (final Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:gamlss.algorithm.AdditiveFit.java

/**
 * Performs a smoothing process - creates an approximating function
 * that attempts to capture important patterns in the data, while 
 * leaving out noise or other fine-scale structures/rapid phenomena.
 * @param xMat - design matrix// ww  w. ja  v a  2 s.  c om
 * @param y - response variable
 * @param sMat - smoother matrix
 * @param distParameter - distribution parameter
 * @return matrix of smoothed values
 */
public BlockRealMatrix fitSmoother(final ArrayRealVector y, final ArrayRealVector weights,
        final BlockRealMatrix xMat, final BlockRealMatrix sMat, final int distParameter) {

    this.s = sMat.copy();
    this.w = weights;
    this.whichDistParameter = distParameter;

    //residuals <- as.vector(y - s %*% rep(1, ncol(s)))   
    tempV = new ArrayRealVector(s.getColumnDimension());
    tempV.set(1.0);
    tempV = (ArrayRealVector) s.operate(tempV);
    residuals = MatrixFunctions.vecSub(y, tempV);
    tempV = null;

    //fit <- list(fitted.values = 0)
    fittedValues = new ArrayRealVector(residuals.getDimension());

    //rss <- weighted.mean(residuals^2, w)
    //rss = calculateRss(residuals, w);
    //tempArr = null;

    //rssold <- rss * 10
    //rssOld = rss*10;

    //nit <- 0
    nit = 0;

    //df <- rep(NA, length(who))
    //lambda <- rep(NA, length(who))
    //double[] df = new double[s.getColumnDimension()]; 

    //var <- s
    var = s.copy();

    //if(trace) cat("\nADDITIVE   iter   rss/n     term\n")
    if (Controls.BACKFIT_TRACE) {
        System.out.println("ADDITIVE   iter   rss/n     term");
    }

    //ndig <- -log10(tol) + 1
    //double ndig = -FastMath.log10(tol)+1;

    //RATIO <- tol + 1
    ratio = Controls.BACKFIT_TOL + 1;

    //while(RATIO > tol & nit < maxit) 
    while (ratio > Controls.BACKFIT_TOL & nit < Controls.BACKFIT_CYCLES) {

        //rssold <- rss
        //rssOld = rss;

        //nit <- nit + 1
        nit++;

        //z <- residuals + fit$fitted.values         
        z = residuals.add(fittedValues);

        //org.apache.commons.lang3.time.StopWatch watch = new org.apache.commons.lang3.time.StopWatch();
        //watch.start();         

        //fit <- lm.wfit(x, z, w, method="qr", ...)
        wls.setNoIntercept(Controls.NO_INTERCEPT[whichDistParameter - 1]);
        wls.newSampleData(z, xMat.copy(), w.copy());

        wls.setNoIntercept(false);

        //residuals <- fit$residuals
        fittedValues = (ArrayRealVector) wls.calculateFittedValues(Controls.IS_SVD);
        //watch.stop();
        //System.out.println(watch.getNanoTime()/(1e+9));
        //watch.reset();         

        //residuals = z.subtract(fittedValues);
        //residuals = (ArrayRealVector) wls.calculateResiduals();
        residuals = z.subtract(fittedValues);

        //rss <- weighted.mean(residuals^2, w)
        //rss = calculateRss(residuals, w);

        //if(trace) cat(nit, "   ", 
        //format(round(rss, ndig)), "  Parametric -- lm.wfit\n", sep = "")
        if (Controls.BACKFIT_TRACE) {
            //System.out.println(" " + nit + "  " + 
            //rss + " Parametric -- lm.wfit");
        }

        //deltaf <- 0
        deltaf = 0;

        //for(j in seq(names.calls)) 
        for (colNum = 0; colNum < s.getColumnDimension(); colNum++) {

            //old <- s[, j]
            old = (ArrayRealVector) s.getColumnVector(colNum);

            //z <- residuals + s[, j]
            z = residuals.add(old);

            //fit.call <- eval(smooth.calls[[j]])
            //residuals <- as.double(fit.call$residuals)      
            residuals = smoother.solve(this);

            //if(length(residuals) != n)
            //stop(paste(names.calls[j], "returns a vector 
            //of the wrong length"))
            if (residuals.getDimension() != y.getDimension()) {
                System.err.println(colNum + "  column of matrix s has a" + " vector of the wrong length");
            }

            //s[, j] <- z - residual
            s.setColumnVector(colNum, z.subtract(residuals));

            //if (length(fit.call$lambda)>1)
            //{for cases where there are multiple lambdas 
            //ambda[j] <- fit.call$lambda[1] 

            //coefSmo[[j]] <- if(is.null(fit.call$coefSmo))
            //0 else fit.call$coefSmo

            //deltaf <- deltaf + weighted.mean((s[, j] - old)^2, w)
            tempV = MatrixFunctions.vecSub((ArrayRealVector) s.getColumnVector(colNum), old);
            deltaf = deltaf + mean.evaluate(tempV.ebeMultiply(tempV).getDataRef(), w.getDataRef());
            tempV = null;

            //rss <- weighted.mean(residuals^2, w)
            //rss = calculateRss(residuals, w);

            // if(trace)
            if (Controls.BACKFIT_TRACE) {
                //cat(" ", nit, " ", format(round(rss, ndig)), 
                //"  Nonparametric -- ", names.calls[j], "\n", sep = "")
                //System.out.println("   " + nit +"   " + rss + "
                //Nonparametric " + "pb(column "+ i+")");
            }

            //df[j] <- fit.call$nl.df
            //df[i] = pb.getEdf();

            //if(se)
            if (Controls.IS_SE) {
                //var[, j] <- fit.call$var
                var.setColumnVector(colNum, smoother.getVar());
            }
        }

        //RATIO <- sqrt(deltaf/sum(w * apply(s, 1, sum)^2))   
        tempD = 0.0;
        tempM = new BlockRealMatrix(s.getRowDimension(), 1);
        for (int j = 0; j < s.getRowDimension(); j++) {
            for (int k = 0; k < s.getColumnDimension(); k++) {
                tempD = tempD + s.getEntry(j, k);
            }
            tempM.setEntry(j, 0, tempD);
            tempD = 0.0;
        }
        size = tempM.getRowDimension();
        for (int j = 0; j < size; j++) {
            tempD = tempD + tempM.getEntry(j, 0) * tempM.getEntry(j, 0) * w.getEntry(j);
        }
        ratio = FastMath.sqrt(deltaf / tempD);
        tempD = null;
        tempM = null;

        //if(trace)
        //cat("Relative change in functions:", 
        //format(round(RATIO, ndig)), "\n")
        if (Controls.BACKFIT_TRACE) {
            System.out.println("Relative change in functions:  " + ratio);
        }
    }

    //if(nit == maxit && maxit > 1)
    //warning(paste("additive.fit convergence not 
    //obtained in ", maxit, " iterations"))
    if (ratio > Controls.BACKFIT_TOL) {
        System.out.println(
                "AdditiveFit convergence is not obtained in " + Controls.BACKFIT_CYCLES + " iterations");
    }

    //fit$fitted.values <- y - residuals
    fittedValues = y.subtract(residuals);

    //rl <- c(fit, list(smooth = s, nl.df = 
    //sum(df), lambda=lambda, coefSmo=coefSmo))
    return s;
}

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

@Test
public void testwls6() {

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

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

    this.y = new ArrayRealVector(testY);

    this.expected.setEntry(0, -2.3);
    this.expected.setEntry(1, 11.2);

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

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

    assertTrue(success);

}

From source file:com.github.thorbenlindhauer.factor.GaussianFactorTest.java

@Test
public void testInitializationFromConditionalLinearGaussian() {
    GaussianFactor factor = factorBuilder.scope("A", "B").conditional().conditioningScope("B").parameters(
            new ArrayRealVector(new double[] { 4.0d }), // mean of A
            new Array2DRowRealMatrix(new double[] { 2.0d }), // variance for A
            new Array2DRowRealMatrix(new double[] { 5.0d })); // weight of B

    // P(A = 3 | B = 1.5)
    assertThat(factor.getValueForAssignment(new double[] { 10.0d, 1.5d })).isEqualTo(0.160733d,
            TestConstants.DOUBLE_VALUE_TOLERANCE);

}

From source file:gamlss.distributions.JSUo.java

/** Calculate and set initial value of sigma.
    * @param y - vector of values of response variable
    * @return vector of initial values of sigma
    *//*  ww w .  j  ava 2  s .c o  m*/
private ArrayRealVector setSigmaInitial(final ArrayRealVector y) {
    //sigma.initial = expression(sigma<- rep(.1, length(y))),
    tempV = new ArrayRealVector(y.getDimension());
    tempV.set(0.1);
    return tempV;
}

From source file:gamlss.distributions.TF2.java

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

From source file:gamlss.distributions.TF.java

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