Example usage for org.apache.commons.math3.linear FieldMatrix getColumnDimension

List of usage examples for org.apache.commons.math3.linear FieldMatrix getColumnDimension

Introduction

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

Prototype

int getColumnDimension();

Source Link

Document

Returns the number of columns in the matrix.

Usage

From source file:controller.VisLP.java

private static Point2D[] getFeasibleIntersections(FieldMatrix<BigFraction> cons) {
    FieldMatrix<BigFraction> N = cons.getSubMatrix(0, cons.getRowDimension() - 1, 0,
            cons.getColumnDimension() - 2);
    FieldVector<BigFraction> b = cons.getColumnVector(cons.getColumnDimension() - 1);

    HashSet<Point2D> points = new HashSet<Point2D>();
    unb = new ArrayList<Point2D>();

    /* Find all intersections */
    for (int i = 0; i < N.getRowDimension(); i++) {
        for (int j = 0; j < N.getRowDimension(); j++) {
            if (i == j)
                continue;

            FieldMatrix<BigFraction> line1 = N.getRowMatrix(i);
            FieldMatrix<BigFraction> line2 = N.getRowMatrix(j);

            BigFraction[] bval = new BigFraction[] { b.getEntry(i), b.getEntry(j) };
            FieldVector<BigFraction> bsys = new ArrayFieldVector<BigFraction>(bval);
            FieldMatrix<BigFraction> sys = LP.addBlock(line1, line2, LP.UNDER);

            try {
                FieldVector<BigFraction> point = new FieldLUDecomposition<BigFraction>(sys).getSolver()
                        .getInverse().operate(bsys);
                double x = point.getEntry(0).doubleValue();
                double y = point.getEntry(1).doubleValue();
                Point2D p2d = new Point2D.Double(x, y);

                /* Only add feasible points */
                if (feasible(p2d, N, b)) {
                    if (i >= N.getRowDimension() - 1)
                        unb.add(p2d);/*from w w w.  j  a  v a2s. c  o  m*/
                    points.add(p2d);
                }
            } catch (IllegalArgumentException e) {
                /* 
                 * Two lines that don't intersect forms an invertible
                 * matrix. Skip these points.
                 */
            }
        }
    }
    return points.toArray(new Point2D[0]);
}

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

/** verifies that two matrices are equal */
public static void assertEquals(FieldMatrix<? extends FieldElement<?>> expected,
        FieldMatrix<? extends FieldElement<?>> observed) {

    Assert.assertNotNull("Observed should not be null", observed);

    if (expected.getColumnDimension() != observed.getColumnDimension()
            || expected.getRowDimension() != observed.getRowDimension()) {
        StringBuilder messageBuffer = new StringBuilder();
        messageBuffer.append("Observed has incorrect dimensions.");
        messageBuffer/*w w  w . ja  v  a  2s  .  c  o m*/
                .append("\nobserved is " + observed.getRowDimension() + " x " + observed.getColumnDimension());
        messageBuffer
                .append("\nexpected " + expected.getRowDimension() + " x " + expected.getColumnDimension());
        Assert.fail(messageBuffer.toString());
    }

    for (int i = 0; i < expected.getRowDimension(); ++i) {
        for (int j = 0; j < expected.getColumnDimension(); ++j) {
            FieldElement<?> eij = expected.getEntry(i, j);
            FieldElement<?> oij = observed.getEntry(i, j);
            Assert.assertEquals(eij, oij);
        }
    }
}

From source file:model.LP.java

/**
 * Return a newly created {@code Matrix} with a new block
 * {@code Matrix} added either horizontally or vertically
 * next to the original {@code Matrix}./*from  w w w. j  ava 2s.  co  m*/
 *
 * @param  B
 *         {@code Matrix}to append to the parent {@code Matrix}.
 * @param  modifier
 *         Matrix.HORIZONTAL or Matrix.VERTICAL.
 * @return
 *         The original {@code Matrix}with a new {@code Matrix} block.
 */
public static FieldMatrix<BigFraction> addBlock(FieldMatrix<BigFraction> A, FieldMatrix<BigFraction> B,
        int modifier) {
    int Am = A.getRowDimension();
    int An = A.getColumnDimension();
    int Bm = B.getRowDimension();
    int Bn = B.getColumnDimension();

    String e = String.format(
            "Illegal operation: Cannot add a matrix block" + " of size %d x %d to a matrix of size %d x %d.",
            Am, An, Bm, Bn);

    if ((modifier == RIGHT && Am != Bm || modifier == UNDER && An != Bn)) {
        throw new IllegalArgumentException(e);
    }

    int newm = Am;
    int newn = An;

    int ci = 0;
    int cj = 0;

    switch (modifier) {
    case RIGHT:
        newn += Bn;
        cj = An;
        break;
    case UNDER:
        /* Fall through */
    default:
        newm += Bm;
        ci = Am;
    }

    BigFraction cdata[][] = new BigFraction[newm][newn];

    /* Copy A's data into cdata */
    for (int i = 0; i < Am; i++) {
        for (int j = 0; j < An; j++) {
            cdata[i][j] = A.getEntry(i, j);
        }
    }

    /* Add the new block of data */
    for (int i = 0; i < Bm; i++) {
        for (int j = 0; j < Bn; j++) {
            cdata[i + ci][j + cj] = B.getEntry(i, j);
        }
    }

    return new Array2DRowFieldMatrix<BigFraction>(cdata);
}

From source file:model.LP.java

/**
 * Initializes a linear program./* w  w w .  ja va  2  s. c  o  m*/
 * <p>
 * n being the number of variables and m being the number of constraints,
 * this {@code constructor} does the following:
 * <p><blockquote><pre>
 *     B is set to the identity matrix of dimension m.
 *
 *     The indices of the basic and non-basic variables are set to
 *     0..n-1 and n-1..n+m-1, respectively.
 *
 *     The slack variables are called w1..wm.
 * </pre></blockquote<p>
 *
 * @param N
 *        A {@code Matrix} with the coefficients
 *        of the non-basic variables.
 * @param b
 *        A {@code Matrix} with the upper bounds on
 *        the constraints in the original program.
 * @param c
 *        A {@code Matrix} with the coefficients of the
 *        decision variables in the original program.
 * @param x
 *        A {@code HashMap} mapping the indices of the
 *        basic and non-basic variables to their names.
 */
public LP(FieldMatrix<BigFraction> N, FieldVector<BigFraction> b, FieldVector<BigFraction> c,
        HashMap<Integer, String> x) {
    this(null, N, b, c, null, N.copy(), b.copy(), c.mapMultiply(BigFraction.MINUS_ONE).copy(), x,
            new int[N.getRowDimension()], new int[N.getColumnDimension()]);

    /* Create an identity matrix of BigFraction's */
    int m = N.getRowDimension();
    BigFraction[][] Bd = new BigFraction[m][m];
    for (int i = 0; i < m; i++) {
        Arrays.fill(Bd[i], BigFraction.ZERO);
        Bd[i][i] = BigFraction.ONE;
    }
    FieldMatrix<BigFraction> B = new Array2DRowFieldMatrix<BigFraction>(Bd);

    this.B = B;
    this.B_ = B.copy();

    for (int i = 0; i < Ni.length; i++)
        Ni[i] = i;
    for (int i = 0; i < Bi.length; i++) {
        Bi[i] = i + Ni.length;
        x.put(Bi[i], "w" + (i + 1));
    }
}

From source file:model.LP.java

/**
 * Do one iteration of the simplex method.
 *
 * @param  entering//from  w  w  w  .  j  a  va2 s  .c  om
 *         Index of variable to enter the basis.
 * @param  leaving
 *         Index of variable to leave the basis.
 * @return
 *         A linear program after one iteration.
 */
public LP pivot(int entering, int leaving) {
    FieldMatrix<BigFraction> bin = new FieldLUDecomposition<BigFraction>(B_).getSolver().getInverse()
            .multiply(N_);

    // Step 1: Check for optimpivality
    // Step 2: Select entering variable.
    // Naive method. Does not check for optimality. Assumes feasibility.
    // Entering variable is given.

    // Step 3: Compute primal step direction.
    FieldVector<BigFraction> ej = new ArrayFieldVector<BigFraction>(bin.getColumnDimension(), BigFraction.ZERO);
    ej.setEntry(entering, BigFraction.ONE);
    FieldVector<BigFraction> psd = bin.operate(ej);

    // Step 4: Compute primal step length.
    // Step 5: Select leaving variable.
    // Leaving variable is given.
    BigFraction t = b_.getEntry(leaving).divide(psd.getEntry(leaving));

    // Step 6: Compute dual step direction.
    FieldVector<BigFraction> ei = new ArrayFieldVector<BigFraction>(bin.getRowDimension(), BigFraction.ZERO);
    ei.setEntry(leaving, BigFraction.ONE);
    FieldVector<BigFraction> dsd = bin.transpose().scalarMultiply(BigFraction.MINUS_ONE).operate(ei);

    // Step 7: Compute dual step length.
    BigFraction s = c_.getEntry(entering).divide(dsd.getEntry(entering));

    // Step 8: Update current primal and dual solutions.
    FieldVector<BigFraction> nb_ = b_.subtract(psd.mapMultiply(t));
    nb_.setEntry(leaving, t);

    FieldVector<BigFraction> nc_ = c_.subtract(dsd.mapMultiply(s));
    nc_.setEntry(entering, s);

    // Step 9: Update basis.
    FieldVector<BigFraction> temp = B_.getColumnVector(leaving);
    FieldMatrix<BigFraction> nB_ = B_.copy();
    nB_.setColumn(leaving, N_.getColumn(entering));

    FieldMatrix<BigFraction> nN_ = N_.copy();
    nN_.setColumnVector(entering, temp);

    int[] nBi = Bi.clone();
    int[] nNi = Ni.clone();
    nBi[leaving] = Ni[entering];
    nNi[entering] = Bi[leaving];

    return new LP(B, N, b, c, nB_, nN_, nb_, nc_, x, nBi, nNi);
}

From source file:model.LP.java

/**
 * Find a leaving variable index that is the most
 * bounding on the given entering variable index.
 *
 * @param  entering/*  w ww. ja  va 2  s. co m*/
 *         an entering variable index.
 * @param  dual
 *         If true, find a leaving variable index for the dual dictionary.
 *         Otherwise, find one for the primal dictionary.
 * @return
 *         A leaving variable index.
 */
private int leaving(int entering, boolean dual) {
    FieldVector<BigFraction> check;
    FieldVector<BigFraction> sd;

    FieldMatrix<BigFraction> bin = new FieldLUDecomposition<BigFraction>(B_).getSolver().getInverse()
            .multiply(N_);

    if (dual) {
        check = c_;
        FieldVector<BigFraction> unit = new ArrayFieldVector<BigFraction>(bin.getRowDimension(),
                BigFraction.ZERO);
        unit.setEntry(entering, BigFraction.ONE);
        sd = bin.transpose().scalarMultiply(BigFraction.MINUS_ONE).operate(unit);
    } else {
        check = b_;
        FieldVector<BigFraction> unit = new ArrayFieldVector<BigFraction>(bin.getColumnDimension(),
                BigFraction.ZERO);
        unit.setEntry(entering, BigFraction.ONE);
        sd = bin.operate(unit);
    }

    boolean unbounded = true;
    int index = -1;

    /* Check for unboundedness and find first non-zero element in check */
    for (int i = 0; i < sd.getDimension(); i++) {
        if (!check.getEntry(i).equals(BigFraction.ZERO) && index == -1) {
            index = i;
        }
        if (sd.getEntry(i).compareTo(BigFraction.ZERO) > 0) {
            unbounded = false;
        }
    }
    String e = "Program is unbounded.";
    if (unbounded)
        throw new RuntimeException(e);

    /* Set temporarily max value as ratio of the first divisible pair. */
    BigFraction max = sd.getEntry(index).divide(check.getEntry(index));

    for (int i = 0; i < sd.getDimension(); i++) {
        BigFraction num = sd.getEntry(i);
        BigFraction denom = check.getEntry(i);

        if (!denom.equals(BigFraction.ZERO)) {
            BigFraction val = num.divide(denom);
            if (val.compareTo(max) > 0) {
                max = val;
                index = i;
            }
        } else {
            if (num.compareTo(BigFraction.ZERO) > 0)
                return i;
        }
    }

    return index;
}

From source file:org.briljantframework.array.Matrices.java

/**
 * Convert the field matrix to an array.
 * /*from w  w  w. j ava 2  s  .  co m*/
 * @param matrix the matrix
 * @return a new array
 */
public static ComplexArray toArray(FieldMatrix<Complex> matrix) {
    ComplexArray array = Arrays.complexArray(matrix.getRowDimension(), matrix.getColumnDimension());
    matrix.walkInOptimizedOrder(new DefaultFieldMatrixPreservingVisitor<Complex>(Complex.ZERO) {
        @Override
        public void visit(int row, int column, Complex value) {
            array.set(row, column, value);
        }
    });
    return array;
}

From source file:org.rhwlab.BHCnotused.GaussianGIWPrior.java

public void init() {
    int n = data.size();
    int d = m.getDimension();
    Dfp rP = r.add(n);//  w w  w. java2s.c o  m
    //        System.out.printf("rP=%s\n",rP.toString());
    double nuP = nu + n;
    //        System.out.printf("nuP=%e\n", nuP);
    FieldMatrix C = new Array2DRowFieldMatrix(field, d, d);
    for (int row = 0; row < C.getRowDimension(); ++row) {
        for (int col = 0; col < C.getColumnDimension(); ++col) {
            C.setEntry(row, col, field.getZero());
        }
    }
    FieldVector X = new ArrayFieldVector(field, d); // a vector of zeros

    for (FieldVector v : data) {
        X = X.add(v);
        FieldMatrix v2 = v.outerProduct(v);
        C = C.add(v2);
    }
    FieldVector mP = (m.mapMultiply(r).add(X)).mapDivide(r.add(n));
    FieldMatrix Sp = C.add(S);

    FieldMatrix rmmP = mP.outerProduct(mP).scalarMultiply(rP);
    Sp = Sp.add(rmm).subtract(rmmP);

    FieldLUDecomposition ed = new FieldLUDecomposition(Sp);
    Dfp det = (Dfp) ed.getDeterminant();

    Dfp detSp = det.pow(field.newDfp(nuP / 2.0));

    Dfp gamma = field.getOne();

    Dfp gammaP = field.getOne();

    for (int i = 1; i <= d; ++i) {
        gamma = gamma.multiply(Gamma.gamma((nu + 1 - i) / 2.0));
        gammaP = gammaP.multiply(Gamma.gamma((nuP + 1 - i) / 2.0));
    }

    Dfp t1 = field.getPi().pow(-n * d / 2.0);
    Dfp t2 = r.divide(rP).pow(d / 2.0);
    Dfp t3 = detS.divide(detSp);

    Dfp t4 = gammaP.divide(gamma);
    Dfp t34 = t3.multiply(t4);
    /*        
            System.out.printf("detSp=%s\n", detSp.toString());
            System.out.printf("det=%s\n", det.toString());
            System.out.printf("gamma=%s\n", gamma.toString());
            System.out.printf("gammaP=%s\n", gammaP.toString());        
            System.out.printf("t1=%s\n", t1.toString());  
            System.out.printf("t2=%s\n", t2.toString());
            System.out.printf("t3=%s\n", t3.toString());
            System.out.printf("t4=%s\n", t4.toString());
    */
    likelihood = t2.multiply(t34).multiply(t1);
    double realLike = likelihood.getReal();
    //       System.out.printf("Likelihood=%e\n", realLike);
    int uhfd = 0;
}