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

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

Introduction

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

Prototype

public abstract double getEntry(int index) throws OutOfRangeException;

Source Link

Document

Return the entry at the specified index.

Usage

From source file:edu.byu.nlp.math.RealVectors.java

/**
 * Computes the log of the sum of the exponentiated elements of a vector. For any index j:
 * //from   w ww .j  a v a2 s  .c  om
 * <pre>
 * log(e^{x_1} + e^{x_2} + ...) = log(e^{x_j} * sum\_{i \neq j} e^{x_i - x_j} + 1)
  *                              = x_j + log(sum\_{i \neq j} e^{x_i - x_j} + 1)
  * </pre>
  * 
  * This method ignores elements that are twenty orders of magnitude different than x_j.
  * 
  * @throws NullPointerException if vector is null
  */
public static double logSumSloppy(RealVector x) {
    Preconditions.checkNotNull(x);

    // TODO(rah67): consider just using the first element
    // use max as j
    int argMax = x.getMaxIndex();
    double max = x.getEntry(argMax);

    if (max == Double.NEGATIVE_INFINITY)
        return Double.NEGATIVE_INFINITY;

    return DoubleArrays.logSum(x.toArray());
}

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.j av  a2  s  . c  o  m
    writer.newline();
}

From source file:IO.java

public static void display(RealVector vec, String name) {
    int len = vec.getDimension();
    System.out.println(name + ":" + len);
    for (int i = 0; i < len; i++) {
        System.out.print(vec.getEntry(i) + ",");
    }//from   w  w w.j av  a2s  . c o m
    System.out.println();
}

From source file:com.idylwood.utils.OptimizationUtils.java

/**
 * Solves for Markowitz optimal portfolio by means of lagrange multiplier.
 * Returns null if it does not exist (the matrix is singular)
 * Otherwise it attempts to find the lowest variance portfolio for
 * the given <code>portfolio_return</code>
 * @param covariance Precalculated covariance matrix
 * @param returns Precalculated vector of returns
 * @param portfolio_return Return to optimize risk for
 * @author Harry C Kim// www  .  j  ava 2  s  . co m
 * @return
 */
static final double[] MarkowitzSolve(final double[][] covariance, final double[] returns,
        final double portfolio_return) {
    if (covariance.length != covariance[0].length)
        throw new IllegalArgumentException("Covariance needs to be square matrix");
    if (returns.length != covariance.length)
        throw new IllegalArgumentException("Returns must be same length as covariance");

    /*
    for (int i = 0; i < covariance.length; i++)
       MathUtils.printArray(covariance[i]);
    System.out.println();
    MathUtils.printArray(returns);
    System.out.println();
    */

    final int timePoints = covariance.length;
    final double[][] lagrangeMatrix = new double[timePoints + 2][timePoints + 2];
    //b as in Ax = b
    final double[] b = new double[timePoints + 2];
    for (int i = 0; i < timePoints; i++) {
        for (int j = 0; j < timePoints; j++) {
            lagrangeMatrix[i][j] = 2 * covariance[i][j];
            b[i] = 0;
            // this is like riskTolerance*returns[i]; but since
            // returns[i]*weights[i] = portfolio_return it will go away in the derivative
        }
    }

    for (int j = 0; j < timePoints; j++) {
        lagrangeMatrix[timePoints][j] = returns[j];
        lagrangeMatrix[timePoints + 1][j] = 1;
        lagrangeMatrix[j][timePoints] = returns[j];
        lagrangeMatrix[j][timePoints + 1] = 1;
    }
    b[timePoints] = portfolio_return; //**** what is the constraint on total expected return?
    b[timePoints + 1] = 1;

    /*
    // Print out lagrangeMatrix augmented with b vector
    for(int i=0; i<timePoints+2; i++)
    {
       for(int j=0; j<timePoints+2;j++)
       {
    System.out.print(lagrangeMatrix[i][j] + " ");
       }
       System.out.println(b[i]);
    }
    */
    // TODO use Gaussian elimination solver, may be faster
    // TODO maybe refactor to use idylblas
    RealMatrix lagrangeReal = MatrixUtils.createRealMatrix(lagrangeMatrix);
    RealVector bReal = MatrixUtils.createRealVector(b);
    SingularValueDecomposition svd = new SingularValueDecomposition(lagrangeReal);

    if (!svd.getSolver().isNonSingular())
        return null;

    RealVector solution = svd.getSolver().solve(bReal);

    final double weights[] = new double[timePoints];

    // last two elements of solution are just lagrange multipliers
    for (int i = 0; i < weights.length; i++)
        weights[i] = solution.getEntry(i);

    // put these in some test class
    if (!MathUtils.fuzzyEquals(1, MathUtils.sum(weights)))
        throw new RuntimeException();
    if (!MathUtils.fuzzyEquals(portfolio_return, MathUtils.linearCombination(returns, weights)))
        throw new RuntimeException();
    //The following calculates the risk(variance) for the weights found
    // final double risk = MathUtils.linearCombination(MathUtils.matrixMultiply(covariance, weights),weights);
    return weights;
}

From source file:com.cloudera.oryx.kmeans.computation.VectorConvert.java

public static MLVector fromVector(RealVector input) {
    final List<Double> values = Lists.newArrayList();
    MLVector.Builder vb = MLVector.newBuilder().setSize(input.getDimension()).setValues(values);
    if (input instanceof ArrayRealVector) {
        vb.setIndices(ImmutableList.<Integer>of());
        for (int i = 0; i < input.getDimension(); i++) {
            values.add(input.getEntry(i));
        }// w ww  . j  a  va2  s  .  c o  m
    } else {
        final List<Integer> indices = Lists.newArrayList();
        vb.setIndices(indices);
        input.walkInDefaultOrder(new AbstractRealVectorPreservingVisitor() {
            @Override
            public void visit(int index, double value) {
                indices.add(index);
                values.add(value);
            }
        });
    }
    if (input instanceof NamedRealVector) {
        vb.setId(((NamedRealVector) input).getName());
    } else {
        vb.setId("");
    }
    return vb.build();
}

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  w  w  w. ja  v  a  2 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:edu.stanford.cfuller.imageanalysistools.clustering.DEGaussianMixtureModelClustering.java

/**
 * Performs Gaussian mixture model clustering on the given inputs using a differential evolution algorithm for maximization of the likelihood of having observed the data.
 * @param singleCluster     An Image mask with each object to be clustered labeled with a unique greylevel value.  (Note that the name stems from this method's original use to recursively divide existing single clusters; this need not actually correspond to a single cluster).
 * @param clusterObjects    A Vector containing an initialized ClusterObject for each object present in the Image passed as singleCluster.
 * @param clusters          A Vector containing an initialized Cluster (guess) for each of the k clusters that will be determined.
 * @param k                 The number of clusters to end up with.
 * @param n                 The number of cluster objects.
 * @return                  The negative log likelihood of observing the objects at their locations, given the maximally likely clustering scheme found.  On return, clusterObjects and clusters will have been updated to reflect this maximally likely scheme.
 *///  w w  w  . ja va  2  s  . c o m
public static double go(Image singleCluster, java.util.Vector<ClusterObject> clusterObjects,
        java.util.Vector<Cluster> clusters, int k, int n) {

    final int numParametersEach = 5;

    int numParameters = k * numParametersEach;

    int populationSize = numParameters;

    double tol = 1.0e-3;
    double scaleFactor = 0.9;
    double crFrq = 0.05;
    int maxIterations = 10;

    RealVector parameterLowerBounds = new ArrayRealVector(numParameters);
    RealVector parameterUpperBounds = new ArrayRealVector(numParameters);

    for (int i = 0; i < k; i++) {

        parameterLowerBounds.setEntry(numParametersEach * i,
                -0.1 * singleCluster.getDimensionSizes().get(ImageCoordinate.X));
        parameterLowerBounds.setEntry(numParametersEach * i + 1,
                -0.1 * singleCluster.getDimensionSizes().get(ImageCoordinate.Y));
        parameterLowerBounds.setEntry(numParametersEach * i + 2, tol);
        parameterLowerBounds.setEntry(numParametersEach * i + 3, -1);
        parameterLowerBounds.setEntry(numParametersEach * i + 4, tol);

        parameterUpperBounds.setEntry(numParametersEach * i,
                1.1 * singleCluster.getDimensionSizes().get(ImageCoordinate.X));
        parameterUpperBounds.setEntry(numParametersEach * i + 1,
                1.1 * singleCluster.getDimensionSizes().get(ImageCoordinate.Y));
        parameterUpperBounds.setEntry(numParametersEach * i + 2,
                Math.pow(0.05 * singleCluster.getDimensionSizes().get(ImageCoordinate.X), 2));
        parameterUpperBounds.setEntry(numParametersEach * i + 3, 1);
        parameterUpperBounds.setEntry(numParametersEach * i + 4,
                Math.pow(0.05 * singleCluster.getDimensionSizes().get(ImageCoordinate.Y), 2));

    }

    ObjectiveFunction f = new GaussianLikelihoodObjectiveFunction(clusterObjects);

    DifferentialEvolutionMinimizer dem = new DifferentialEvolutionMinimizer();

    RealVector output = null;

    double L = Double.MAX_VALUE;

    while (L == Double.MAX_VALUE || output == null) {
        output = dem.minimize(f, parameterLowerBounds, parameterUpperBounds, populationSize, scaleFactor,
                maxIterations, crFrq, tol);
        L = f.evaluate(output);
    }

    //set up new clusters

    for (int i = 0; i < k; i++) {
        clusters.get(i).setCentroidComponents(output.getEntry(numParametersEach * i),
                output.getEntry(numParametersEach * i + 1), 0);
        clusters.get(i).setID(i + 1);
        clusters.get(i).getObjectSet().clear();
    }

    //assign objects to clusters

    for (ClusterObject c : clusterObjects) {
        c.setCurrentCluster(clusters.get(c.getMostProbableCluster()));
        c.getCurrentCluster().getObjectSet().add(c);
    }

    return L;

}

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

/**
 * Adds a dummy label and converts to an Instance
 * @param headers/*from  w w w .  j  a v  a  2  s  .  co  m*/
 * @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:edu.oregonstate.eecs.mcplan.domains.blackjack.AbstractionDiscovery.java

private static void writeClustering(final MetricConstrainedKMeans kmeans, final File root, final int iter,
        final BlackjackParameters params, final String[][] hard_actions, final String[][] soft_actions)
        throws FileNotFoundException {
    Csv.write(new PrintStream(new File(root, "M" + iter + ".csv")), kmeans.metric);
    {//from   w  w w  .  j  a  va2 s  .c  o m
        final Csv.Writer writer = new Csv.Writer(new PrintStream(new File(root, "mu" + iter + ".csv")));
        for (int i = 0; i < kmeans.d; ++i) {
            for (int j = 0; j < kmeans.k; ++j) {
                writer.cell(kmeans.mu()[j].getEntry(i));
            }
            writer.newline();
        }
    }
    // Lt.operate( x ) maps x to the space defined by the metric
    final RealMatrix Lt = new CholeskyDecomposition(kmeans.metric).getLT();
    {
        final Csv.Writer writer = new Csv.Writer(new PrintStream(new File(root, "X" + iter + ".csv")));
        writer.cell("cluster").cell("label").cell("x1").cell("x2").cell("x3").cell("Ax1").cell("Ax2")
                .cell("Ax3").newline();
        for (int cluster = 0; cluster < kmeans.k; ++cluster) {
            for (int i = 0; i < kmeans.N; ++i) {
                if (kmeans.assignments()[i] == cluster) {
                    writer.cell(cluster);
                    final RealVector phi = kmeans.X_.get(i); //Phi.get( i );
                    final int pv = (int) phi.getEntry(0);
                    final int paces = (int) phi.getEntry(1);
                    final int dv = (int) phi.getEntry(2);
                    if (paces > 0) {
                        writer.cell(soft_actions[pv - params.soft_hand_min][dv - params.dealer_showing_min]);
                    } else {
                        writer.cell(hard_actions[pv - params.hard_hand_min][dv - params.dealer_showing_min]);
                    }
                    for (int j = 0; j < phi.getDimension(); ++j) {
                        writer.cell(phi.getEntry(j));
                    }
                    final RealVector trans = Lt.operate(phi);
                    for (int j = 0; j < trans.getDimension(); ++j) {
                        writer.cell(trans.getEntry(j));
                    }
                    writer.newline();
                }
            }
        }
    }
}

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

@Nonnull
static RealVector unitL2norm(@Nonnull final RealVector x) {
    double x0 = x.getEntry(0);
    double sign = MathUtils.sign(x0);
    x.setEntry(0, x0 + sign * x.getNorm());
    return x.unitVector();
}