List of usage examples for org.apache.commons.math3.linear FieldMatrix getRowDimension
int getRowDimension();
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 ww. ja v a2 s . co 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: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 w w w.ja v a 2s.com return true; }
From source file:controller.VisLP.java
/** * Dictionary form assumes all x-values >= 0. For a geometric * representation we need these constraints explicitly stated * in order to draw the feasible region. * // w w w . ja v a 2 s. c o m * This method adds the constraints x >= 0 (-x <= 0) * and y >= 0 (-y <= 0) unless more bounding constraints * on the x and y-values already exists. * * It also always adds a line with a negative slope with * a <<high enough>> positive x- and y-intercept needed * to color unbounded feasible regions. * * @param cons * A constraints-matrix * @return * A constraints matrix guaranteed to have lower bounds. */ static FieldMatrix<BigFraction> checkForBounds(FieldMatrix<BigFraction> cons) { boolean lowerx = false; boolean lowery = false; BigFraction valsum = BigFraction.ZERO; /* Does lower bounds already exist? */ for (int i = 0; i < cons.getRowDimension(); i++) { BigFraction x = cons.getEntry(i, 0); BigFraction y = cons.getEntry(i, 1); if (x.compareTo(BigFraction.ZERO) < 0 && y.equals(BigFraction.ZERO)) { lowerx = true; } else if (x.equals(BigFraction.ZERO) && y.compareTo(BigFraction.ZERO) < 0) { lowery = true; } valsum = valsum.add(cons.getEntry(i, 2).abs()); } FieldMatrix<BigFraction> ncons = cons.copy(); BigFraction[] cxdata = new BigFraction[] { BigFraction.MINUS_ONE, BigFraction.ZERO, BigFraction.ZERO }; BigFraction[] cydata = new BigFraction[] { BigFraction.ZERO, BigFraction.MINUS_ONE, BigFraction.ZERO }; /* Add lower bounds if they do not exist */ if (!lowerx) { FieldMatrix<BigFraction> c = new Array2DRowFieldMatrix<BigFraction>(cxdata).transpose(); ncons = LP.addBlock(ncons, c, LP.UNDER); } if (!lowery) { FieldMatrix<BigFraction> c = new Array2DRowFieldMatrix<BigFraction>(cydata).transpose(); ncons = LP.addBlock(ncons, c, LP.UNDER); } valsum = valsum.add(BigFraction.TWO).multiply(valsum); BigFraction[] uc = new BigFraction[] { BigFraction.ONE, BigFraction.ONE, valsum }; FieldMatrix<BigFraction> c = new Array2DRowFieldMatrix<BigFraction>(uc).transpose(); ncons = LP.addBlock(ncons, c, LP.UNDER); return ncons; }
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 www .j a va 2 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
/** * Return a newly created {@code Matrix} with a new block * {@code Matrix} added either horizontally or vertically * next to the original {@code Matrix}.//w w w . j a v a2 s .c o 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: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//from w w w . j a v a 2 s.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
/** * Initializes a linear program./*from w w w . j av a2s .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
/** * Find a leaving variable index that is the most * bounding on the given entering variable index. * * @param entering/*from ww w .j a v a2 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:model.LP.java
/** * Do one iteration of the simplex method. * * @param entering/*from w ww . j a va 2 s. c o 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:org.briljantframework.array.Matrices.java
/** * Convert the field matrix to an array. * //from w ww.jav a 2s .com * @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; }