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

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

Introduction

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

Prototype

T getEntry(int index) throws OutOfRangeException;

Source Link

Document

Returns the entry in the specified index.

Usage

From source file:controller.VisLP.java

/**
 * Draw the linear constraints of an {@code LP} and color
 * it's feasible region in a given {@code CCSystem}.
 * //from  ww w .  j ava2 s . c  o m
 * @param cs
 *        a {@code CCSystem}.
 * @param lp
 *        a {@code LP}.
 */
static void drawLP(CCSystem cs, LP lp) {
    cs.clear();

    /* Don't draw the LP if it is not in two variables */
    if (lp == null || lp.getNoBasic() != 2) {
        cs.setVisibleAxes(false);
        return;
    }
    cs.setVisibleAxes(true);

    CCSLine line;
    FieldMatrix<BigFraction> cons = lp.getConstraints();
    cons = checkForBounds(cons);

    /* Draw all constraints as lines, except hidden bounded constraint */
    for (int i = 0; i < cons.getRowDimension() - 1; i++) {
        line = new CCSLine(cons.getEntry(i, 0).doubleValue(), cons.getEntry(i, 1).doubleValue(),
                cons.getEntry(i, 2).doubleValue(), Color.gray);
        cs.addLine(line);
    }

    Point2D[] fpoints = getFeasibleIntersections(cons);

    /* 
     * Move the center of the coordinate system
     * to the center of the feasible region.
     */
    if (readScope) {
        scopeArea(cs, fpoints, true);
        readScope = false;
    }
    if (feasScope && lp.feasible(false)) {
        scopeArea(cs, fpoints, false);
        feasScope = false;
    }

    /* If there is no feasible region there is no need to try to color it */
    if (fpoints.length == 0)
        return;

    /* Draw all feasible solutions as points */
    Point2D[] pconv = convex(fpoints);
    for (Point2D p2d : pconv) {
        CCSPoint ccsp = new CCSPoint(p2d.getX(), p2d.getY());
        if (!unb.contains(p2d))
            cs.addPoint(ccsp);
    }

    /* Color the region depending on whether it is unbounded or not. */
    if (unb.size() == 0) {
        cs.addPolygon(new CCSPolygon(pconv, Color.pink, true));
    } else if (unb.size() == 1) {
        GradientPaint gp = new GradientPaint(pconv[0], Color.pink, unb.get(0), cs.getBackground());
        cs.addPolygon(new CCSPolygon(pconv, gp, true));
    } else {
        Point2D p1 = unb.get(0);
        Point2D p2 = unb.get(1);
        double xavg = (p1.getX() + p2.getX()) / 2.0;
        double yavg = (p1.getY() + p2.getY()) / 2.0;
        /* 
         * Move the end point of the gradient further away from the
         * polygon edge to make the end of the gradient look less sudden.
         */
        xavg *= 0.9;
        yavg *= 0.9;

        Point2D pavg = new Point2D.Double(xavg, yavg);

        /* Fade into the background color */
        GradientPaint gp = new GradientPaint(pconv[0], Color.pink, pavg, cs.getBackground());

        cs.addPolygon(new CCSPolygon(pconv, gp, true));
    }

    /* Draw the current objective function */
    FieldVector<BigFraction> obj = lp.getObjFunction();
    line = new CCSLine(obj.getEntry(0).doubleValue(), obj.getEntry(1).doubleValue(), lp.objVal().doubleValue(),
            Color.red);
    cs.addLine(line);

    /* Draw the current basic solution as a point. */
    BigFraction[] point = lp.point();
    cs.addPoint(new CCSPoint(point[0].doubleValue(), point[1].doubleValue(), Color.red, true));
}

From source file:model.LP.java

public static BigFraction getMinValue(FieldVector<BigFraction> bf) {
    BigFraction min = bf.getEntry(0);

    for (int i = 1; i < bf.getDimension(); i++) {
        BigFraction val = bf.getEntry(i);
        if (val.compareTo(min) < 0) {
            min = val;
        }/*ww  w  .  java2  s  .  c o m*/
    }
    return min;
}

From source file:controller.VisLP.java

private static boolean feasible(Point2D p2d, FieldMatrix<BigFraction> N, FieldVector<BigFraction> b) {
    double x = p2d.getX();
    double y = p2d.getY();

    for (int j = 0; j < N.getRowDimension(); j++) {
        float nx = N.getEntry(j, 0).floatValue();
        float ny = N.getEntry(j, 1).floatValue();
        float val = (float) (nx * x + ny * y);
        if (val > b.getEntry(j).floatValue())
            return false;
    }/*from  www.j  a va  2  s  .  c om*/

    return true;
}

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   ww  w. j a  v  a 2 s .  c  om
                    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:model.LP.java

/**
 * Find an entering variable index according
 * to the largest coefficients rule.//from w ww  .j a  va2s .c  o  m
 *
 * @param  dual
 *         If true, find an entering variable index for the dual dictionary.
 *         Otherwise, find one for the primal dictionary.
 * @return
 *         An entering variable index.
 */
private int entering(boolean dual) {
    String e = "Incumbent basic solution is optimal.";
    String e2 = String.format("Incumbent basic solution is %s infeasible", dual ? "dually" : "primal");

    if (optimal(dual))
        throw new RuntimeException(e);
    if (!feasible(dual))
        throw new RuntimeException(e2);

    FieldVector<BigFraction> check = dual ? b_ : c_;

    BigFraction min = BigFraction.ZERO;
    int index = -1;

    for (int i = 0; i < check.getDimension(); i++) {
        BigFraction val = check.getEntry(i);
        if (val.compareTo(min) < 0) {
            min = val;
            index = i;
        }
    }
    return index;
}

From source file:model.LP.java

/**
 * Do one iteration of the simplex method.
 *
 * @param  entering//ww  w  .j  a  va 2 s .  co m
 *         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

public LP reinstate() {
    FieldVector<BigFraction> nc_ = new ArrayFieldVector<BigFraction>(c_.getDimension(), BigFraction.ZERO);
    FieldMatrix<BigFraction> bin = new FieldLUDecomposition<BigFraction>(B_).getSolver().getInverse()
            .multiply(N_);//from  w ww. j a va 2  s  .  c om

    for (int i = 0; i < Bi.length; i++) {
        int k = Bi[i];
        if (k < Ni.length) {
            for (int j = 0; j < Ni.length; j++) {
                BigFraction bf = c.getEntry(k).multiply(bin.getEntry(i, j));
                nc_.setEntry(j, nc_.getEntry(j).add(bf));
            }
        }
    }

    for (int i = 0; i < Ni.length; i++) {
        int k = Ni[i];
        if (k < Ni.length) {
            nc_.setEntry(i, nc_.getEntry(i).subtract(c.getEntry(i)));
        }
    }

    return new LP(B, N, b, c, B_, N_, b_, nc_, x, Bi, Ni);
}

From source file:model.LP.java

/**
 * Find a leaving variable index that is the most
 * bounding on the given entering variable index.
 *
 * @param  entering//from   www.  java  2s  . c o  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.rhwlab.BHCnotused.GaussianGIWPrior.java

private void vectorAsString(FieldVector v, StringBuilder builder) {
    boolean first = true;
    builder.append("(");
    for (int i = 0; i < v.getDimension(); ++i) {
        if (!first) {
            builder.append(String.format(",%d", ((Dfp) v.getEntry(i)).intValue()));
        } else {/*  www  . j a  v a 2 s  .  c  om*/
            builder.append(String.format("%d", ((Dfp) v.getEntry(i)).intValue()));
        }
        first = false;
    }
    builder.append(")");
}