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

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

Introduction

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

Prototype

public abstract int getDimension();

Source Link

Document

Returns the size of the vector.

Usage

From source file:com.cloudera.oryx.kmeans.computation.pmml.ClusteringModelBuilder.java

private static Cluster toCluster(RealVector point, int pointId) {
    Cluster cluster = new Cluster();
    cluster.setId(String.valueOf(pointId));
    Array array = new Array(toString(point), Array.Type.REAL);
    array.setN(point.getDimension());
    cluster.setArray(array);/*from w  w w .  ja  v a2  s .  c om*/
    return cluster;
}

From source file:edu.oregonstate.eecs.mcplan.util.Csv.java

public static void write(final PrintStream out, final RealVector v) {
    final Writer writer = new Writer(out);
    for (int i = 0; i < v.getDimension(); ++i) {
        writer.cell(v.getEntry(i));/*from w  w  w  .ja  v a  2  s  .  co m*/
    }
    writer.newline();
}

From source file:net.sf.dsp4j.octave_3_2_4.m.polynomial.Roots.java

public static Complex[] roots(RealVector v) {

    if (v.isInfinite() || v.isNaN()) {
        throw new RuntimeException("roots: inputs must not contain Inf or NaN");
    }//  w  ww .  j a va 2s. c  o m

    int n = v.getDimension();

    // ## If v = [ 0 ... 0 v(k+1) ... v(k+l) 0 ... 0 ], we can remove the
    // ## leading k zeros and n - k - l roots of the polynomial are zero.

    int[] f = new int[v.getDimension()];
    if (v.getDimension() > 0) {
        int fI = 0;
        double max = v.getMaxValue();
        double min = FastMath.abs(v.getMinValue());
        if (min > max) {
            max = min;
        }
        RealVector v1 = v.mapDivide(max);
        f = OctaveBuildIn.find(v1);
    }

    Complex[] r = new Complex[0];
    if (f.length > 0 && n > 1) {
        v = v.getSubVector(f[0], f[f.length - 1] - f[0] + 1);
        if (v.getDimension() > 1) {
            double[] ones = new double[v.getDimension() - 2];
            Arrays.fill(ones, 1);
            RealMatrix A = OctaveBuildIn.diag(ones, -1);
            for (int i = 0; i < A.getRowDimension(); i++) {
                A.setEntry(i, 0, -v.getEntry(i + 1) / v.getEntry(0));
            }
            try {
                r = Eig.eig(A);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (f[f.length - 1] < n) {
                int diffLength = n - 1 - f[f.length - 1];
                if (diffLength > 0) {
                    int rl = r.length;
                    r = Arrays.copyOf(r, r.length + diffLength);
                    Arrays.fill(r, rl, r.length, Complex.ZERO);
                }
            }
        } else {
            r = new Complex[n - f[f.length - 1]];
            Arrays.fill(r, Complex.ZERO);
        }
    } else {
        r = new Complex[0];
    }
    return r;

}

From source file:edu.stanford.cfuller.imageanalysistools.filter.LocalBackgroundEstimationFilter.java

/**
 * Finds the kth item sorted by increasing value in a possibly unsorted vector.
 * <p>//from ww w. ja v  a2  s  . c  o m
 * This will likely not completely sort the vector, but will almost certainly
 * change the order of the items in the vector in place.
 * 
 * @param k         The index of the item (in the sorted vector) to find.
 * @param toFind   The RealVector in which to find the kth item.
 * @return         The value of the kth item (in the sorted vector).
 */
public static double quickFindKth(int k, RealVector toFind) {

    int n = toFind.getDimension();

    int l = 0;

    int ir = n - 1;

    while (true) {

        if (ir <= l + 1) {
            if (ir == l + 1 && toFind.getEntry(ir) < toFind.getEntry(l)) {
                swap(ir, l, toFind);
            }

            return toFind.getEntry(k);
        } else {
            int mid = (l + ir) >> 1;

            swap(mid, l + 1, toFind);

            if (toFind.getEntry(l) > toFind.getEntry(ir))
                swap(l, ir, toFind);
            if (toFind.getEntry(l + 1) > toFind.getEntry(ir))
                swap(l + 1, ir, toFind);
            if (toFind.getEntry(l) > toFind.getEntry(l + 1))
                swap(l, l + 1, toFind);

            int i = l + 1;
            int j = ir;

            double a = toFind.getEntry(l + 1);

            while (true) {
                do {
                    i++;
                } while (toFind.getEntry(i) < a);

                do {
                    j--;
                } while (toFind.getEntry(j) > a);

                if (j < i)
                    break;

                swap(i, j, toFind);
            }

            toFind.setEntry(l + 1, toFind.getEntry(j));
            toFind.setEntry(j, a);

            if (j >= k)
                ir = j - 1;
            if (j <= k)
                l = i;

        }

    }

}

From source file:hivemall.utils.math.StatsUtils.java

/**
 * pdf(x, x_hat) = exp(-0.5 * (x-x_hat) * inv() * (x-x_hat)T) / ( 2^0.5d * det()^0.5)
 * /*  ww w  .  j a  v a2s. co  m*/
 * @return value of probabilistic density function
 * @link https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Density_function
 */
public static double pdf(@Nonnull final RealVector x, @Nonnull final RealVector x_hat,
        @Nonnull final RealMatrix sigma) {
    final int dim = x.getDimension();
    Preconditions.checkArgument(x_hat.getDimension() == dim,
            "|x| != |x_hat|, |x|=" + dim + ", |x_hat|=" + x_hat.getDimension());
    Preconditions.checkArgument(sigma.getRowDimension() == dim,
            "|x| != |sigma|, |x|=" + dim + ", |sigma|=" + sigma.getRowDimension());
    Preconditions.checkArgument(sigma.isSquare(), "Sigma is not square matrix");

    LUDecomposition LU = new LUDecomposition(sigma);
    final double detSigma = LU.getDeterminant();
    double denominator = Math.pow(2.d * Math.PI, 0.5d * dim) * Math.pow(detSigma, 0.5d);
    if (denominator == 0.d) { // avoid divide by zero
        return 0.d;
    }

    final RealMatrix invSigma;
    DecompositionSolver solver = LU.getSolver();
    if (solver.isNonSingular() == false) {
        SingularValueDecomposition svd = new SingularValueDecomposition(sigma);
        invSigma = svd.getSolver().getInverse(); // least square solution
    } else {
        invSigma = solver.getInverse();
    }
    //EigenDecomposition eigen = new EigenDecomposition(sigma);
    //double detSigma = eigen.getDeterminant();
    //RealMatrix invSigma = eigen.getSolver().getInverse();

    RealVector diff = x.subtract(x_hat);
    RealVector premultiplied = invSigma.preMultiply(diff);
    double sum = premultiplied.dotProduct(diff);
    double numerator = Math.exp(-0.5d * sum);

    return numerator / denominator;
}

From source file:edu.utexas.cs.tactex.utils.BrokerUtils.java

/**
 * Rotates a weekly record to start from the next timeslot
 * and append the last day to continue until the end of the day
 * /*from   w  ww  .j  av  a2  s  . co  m*/
 * @param energy
 * @param currentTimeslot
 * @return
 */
public static ArrayRealVector rotateWeeklyRecordAndAppendTillEndOfDay(RealVector record, int currentTimeslot) {
    // sanity check
    if (record.getDimension() != 7 * 24) {
        log.error("record dimension is not 7*24, not sure if code robust to that?");
    }
    int predictionStartWeeklyHour = (currentTimeslot + 1) % (record.getDimension());
    ArrayRealVector copy = new ArrayRealVector(record.getDimension());
    // rotate to start from current moment
    RealVector slice1 = record.getSubVector(predictionStartWeeklyHour,
            record.getDimension() - predictionStartWeeklyHour);
    RealVector slice2 = record.getSubVector(0, predictionStartWeeklyHour);
    copy.setSubVector(0, slice1);
    copy.setSubVector(slice1.getDimension(), slice2);
    return copy;
}

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

/**
 * Adds a dummy label and converts to an Instance
 * @param headers/*w w w.  jav  a2 s . c om*/
 * @param x
 * @return
 */
public static Instance labeledInstanceFromUnlabeledFeatures(final Instances headers, final RealVector x) {
    assert (x.getDimension() == headers.numAttributes() - 1);
    final double[] labeled = new double[x.getDimension() + 1];
    for (int i = 0; i < x.getDimension(); ++i) {
        labeled[i] = x.getEntry(i);
    }
    labeled[labeled.length - 1] = Double.NaN;
    final DenseInstance inst = new DenseInstance(1.0, labeled);
    return inst;
}

From source file:lirmm.inria.fr.math.TestUtils.java

/**
 * Asserts that all entries of the specified vectors are equal to within a
 * positive {@code delta}./*from w w  w .j  av  a  2  s . co  m*/
 *
 * @param message the identifying message for the assertion error (can be
 * {@code null})
 * @param expected expected value
 * @param actual actual value
 * @param delta the maximum difference between the entries of the expected
 * and actual vectors for which both entries are still considered equal
 */
public static void assertEquals(final String message, final double[] expected, final RealVector actual,
        final double delta) {
    final String msgAndSep = message.equals("") ? "" : message + ", ";
    Assert.assertEquals(msgAndSep + "dimension", expected.length, actual.getDimension());
    for (int i = 0; i < expected.length; i++) {
        Assert.assertEquals(msgAndSep + "entry #" + i, expected[i], actual.getEntry(i), delta);
    }
}

From source file:lirmm.inria.fr.math.TestUtils.java

/**
 * Asserts that all entries of the specified vectors are equal to within a
 * positive {@code delta}.//from  w w w  . j  a v a2s  .  c om
 *
 * @param message the identifying message for the assertion error (can be
 * {@code null})
 * @param expected expected value
 * @param actual actual value
 * @param delta the maximum difference between the entries of the expected
 * and actual vectors for which both entries are still considered equal
 */
public static void assertEquals(final String message, final RealVector expected, final RealVector actual,
        final double delta) {
    final String msgAndSep = message.equals("") ? "" : message + ", ";
    Assert.assertEquals(msgAndSep + "dimension", expected.getDimension(), actual.getDimension());
    final int dim = expected.getDimension();
    for (int i = 0; i < dim; i++) {
        Assert.assertEquals(msgAndSep + "entry #" + i, expected.getEntry(i), actual.getEntry(i), delta);
    }
}

From source file:gamlss.utilities.MatrixFunctions.java

/**
 * Write vector values to CSV file.//www .j av  a 2s . c  om
 * @param cmd - path to the file
 * @param v - vector to write
 */
public static void vectorWriteCSV(final String cmd, final RealVector v, boolean append) {
    try {
        // Create file 
        FileWriter fstream = new FileWriter(cmd, append);
        BufferedWriter out = new BufferedWriter(fstream);

        for (int j = 0; j < v.getDimension(); j++) {
            out.write(Double.toString(v.getEntry(j)));
            out.newLine();
        }
        out.close();
    } catch (Exception e) { //Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}