/**
   * Computes the euclidean centroid, it may not be the formal centroid for different metrics but
   * intuitively the average counts should provide a good cluster representative which is what this
   * method intends to return
   *
   * @param pwmSet - Collection of pwms from which to compute the centroid0
   * @return The euclidean centroid
   * @throws IllegalArgumentException - When not all PWMs have the same dimension.
   */
  public PositionWeightMatrix centroidOf(Collection<PositionWeightMatrix> pwmSet)
      throws IllegalArgumentException {
    Matrix centroidMatrix = null;
    Iterator<PositionWeightMatrix> pwmIt = pwmSet.iterator();
    if (pwmIt.hasNext()) {
      PositionWeightMatrix first = pwmIt.next();
      PositionWeightColumn firstCol = first.get(0);
      centroidMatrix = new Matrix(firstCol.getAlphabetSize(), first.getNumCol());
      addToCentroid(centroidMatrix, first);
    }
    while (pwmIt.hasNext()) {
      PositionWeightMatrix pwm = pwmIt.next();
      if (pwm.getNumCol() != centroidMatrix.getColumnDimension()) {
        throw new IllegalArgumentException(
            "Error computing centroid. All PWMs in set should have the same dimension");
      }
      addToCentroid(centroidMatrix, pwm);
    }

    centroidMatrix.times(1 / (double) pwmSet.size());

    PositionWeightMatrix centroid = new PositionWeightMatrix("centroid");
    for (int j = 0; j < centroidMatrix.getColumnDimension(); j++) {
      centroid.addColumn(centroidMatrix.getColumn(j));
    }
    return centroid;
  }
Esempio n. 2
0
 public static Matrix add1sRow(Matrix m) {
   Matrix a = new Matrix(m.getRowDimension() + 1, m.getColumnDimension());
   for (int i = 0; i < a.getColumnDimension(); i++) {
     a.set(0, i, 1);
   }
   return a;
 }
Esempio n. 3
0
 public static Matrix remove1stColumn(Matrix m) {
   Matrix a = new Matrix(m.getRowDimension(), m.getColumnDimension() - 1);
   for (int i = 0; i < a.getRowDimension(); i++) {
     for (int j = 0; j < a.getColumnDimension(); j++) {
       a.set(i, j, m.get(i, j + 1));
     }
   }
   return a;
 }
Esempio n. 4
0
 public static Matrix add1sColumn(Matrix m) {
   Matrix a = new Matrix(m.getRowDimension(), m.getColumnDimension() + 1);
   for (int i = 0; i < a.getRowDimension(); i++) {
     a.set(i, 0, 1);
     for (int j = 1; j < a.getColumnDimension(); j++) {
       a.set(i, j, m.get(i, j - 1));
     }
   }
   return a;
 }
Esempio n. 5
0
  /**
   * @param m Matrix with 2 rows, one column (2x1)
   * @return Point with same coordinates as in Matrix
   * @throws InvalidParameterException if the Matrix has wrong dimensions
   */
  public static Point2d matrixToPoint(final Matrix m) throws InvalidParameterException {
    if (m.getColumnDimension() != 1)
      throw new InvalidParameterException(
          "Circle.matrixToPoint: wrong number of columns: " + m.getColumnDimension());
    if (m.getRowDimension() != 2)
      throw new InvalidParameterException(
          "Circle.matrixToPoint: wrong number of rows: " + m.getRowDimension());

    Point2d point = new Point2d(m.get(0, 0), m.get(1, 0));

    return point;
  }
Esempio n. 6
0
  /**
   * @param m Matrix with 2 rows, one column (2x1)
   * @return Vector2d with same coordinates as in Matrix
   * @throws InvalidParameterException if the Matrix has wrong dimensions
   */
  public static Vector2d matrixToVector(final Matrix m) throws InvalidParameterException {
    if (m.getColumnDimension() != 1)
      throw new InvalidParameterException(
          "Circle.matrixToPoint: wrong number of columns: " + m.getColumnDimension());
    if (m.getRowDimension() != 2)
      throw new InvalidParameterException(
          "Circle.matrixToPoint: wrong number of rows: " + m.getRowDimension());

    Vector2d vector = new Vector2d(m.get(0, 0), m.get(1, 0));

    return vector;
  }
Esempio n. 7
0
  /**
   * Creation of one muscle.
   *
   * @param moment nb_segment lines, 3 col : On each line, the influence on the given joint as in
   *     moment[i,0]+moment[i,1]*sin(moment[i,2]*angle)
   * @param minL0 minimum size of muscle
   * @param maxL0 maximum size of muscle
   */
  public SimpleMuscle() {
    // Init
    _ln = _minL0.copy();
    _vn = new Matrix(1, _ln.getColumnDimension(), 0);
    _tn = new Matrix(1, _ln.getColumnDimension(), 0);
    _t = new Matrix(1, _ln.getColumnDimension(), 0);
    _cpl = new Matrix(1, _minA.getColumnDimension(), 0);

    // ratio l/l0=k
    // _k = (_maxL0-_minL0) / JamaU.dotP(_mom, _maxA.minus(_minA));
    _k = (_maxL0.minus(_minL0)).arrayRightDivide((_maxA.minus(_minA)).times(_mom.transpose()));
    _k = _k.uminus();
  }
Esempio n. 8
0
  public static Matrix addBotMatrix(Matrix a, Matrix b) {
    Matrix c = new Matrix(a.getRowDimension() + b.getRowDimension(), a.getColumnDimension());
    for (int i = 0; i < a.getRowDimension(); i++) {
      for (int j = 0; j < a.getColumnDimension(); j++) {
        c.set(i, j, a.get(i, j));
      }
    }
    for (int i = 0; i < b.getRowDimension(); i++) {
      for (int j = 0; j < b.getColumnDimension(); j++) {
        c.set(i + a.getRowDimension(), j, b.get(i, j));
      }
    }

    return c;
  }
  private static Matrix rotatedMatrix(Matrix m, Matrix r) {
    Matrix translationMatrix = new Matrix(m.getRowDimension(), m.getColumnDimension());
    for (int c = 0; c < translationMatrix.getColumnDimension(); c++) {
      // T

      // x
      translationMatrix.set(0, c, 2.0);
      // y
      translationMatrix.set(1, c, 3.0);
      // z
      // translationMatrix.set(2, c, 2.0);
    }

    Matrix rotatedMatrix = r.times(m.minus(translationMatrix)).plus(translationMatrix);
    return rotatedMatrix;
  }
Esempio n. 10
0
 public static Matrix inverse(Matrix x) {
   int rows = x.getRowDimension();
   int cols = x.getColumnDimension();
   if (rows < cols) {
     Matrix result = inverse(x.transpose());
     if (result != null) result = result.transpose();
     return result;
   }
   SingularValueDecomposition svdX = new SingularValueDecomposition(x);
   if (svdX.rank() < 1) return null;
   double[] singularValues = svdX.getSingularValues();
   double tol = Math.max(rows, cols) * singularValues[0] * MACHEPS;
   double[] singularValueReciprocals = new double[singularValues.length];
   for (int i = 0; i < singularValues.length; i++)
     if (Math.abs(singularValues[i]) >= tol) singularValueReciprocals[i] = 1.0 / singularValues[i];
   double[][] u = svdX.getU().getArray();
   double[][] v = svdX.getV().getArray();
   int min = Math.min(cols, u[0].length);
   double[][] inverse = new double[cols][rows];
   for (int i = 0; i < cols; i++)
     for (int j = 0; j < u.length; j++)
       for (int k = 0; k < min; k++)
         inverse[i][j] += v[i][k] * singularValueReciprocals[k] * u[j][k];
   return new Matrix(inverse);
 }
 public static double[] row(Matrix m, int i) {
   double[] array = new double[m.getColumnDimension()];
   for (int k = 0; k < array.length; k++) {
     array[k] = m.get(i, k);
   }
   return array;
 }
Esempio n. 12
0
 @Override
 public String toResultString() {
   StringBuilder result =
       new StringBuilder(
           Tools.getLineSeparator() + "Principal Components:" + Tools.getLineSeparator());
   if (manualNumber) {
     result.append("Number of Components: " + numberOfComponents + Tools.getLineSeparator());
   } else {
     result.append("Proportion Threshold: " + proportionThreshold + Tools.getLineSeparator());
   }
   for (int i = 0; i < vMatrix.getColumnDimension(); i++) {
     result.append("PC " + (i + 1) + ": ");
     for (int j = 0; j < attributeNames.length; j++) {
       double value = vMatrix.get(i, j);
       if (value > 0) {
         result.append(" + ");
       } else {
         result.append(" - ");
       }
       result.append(Tools.formatNumber(Math.abs(value)) + " * " + attributeNames[j]);
     }
     result.append(Tools.getLineSeparator());
   }
   return result.toString();
 }
  /**
   * One common task in machine learning is evaluating an algorithm’s accuracy. One way you can use
   * the existing data is to take some portion, say 90%, to train the classifier. Then you’ll take
   * the remaining 10% to test the classifier and see how accurate it is.
   *
   * @return
   * @throws IOException
   */
  public int classifyTest() throws IOException {
    FileHelper fileHelper = new FileHelper(INPUT_FILE_NAME);
    Matrix dataSet = fileHelper.getMatrix();
    Matrix normMat = autoNormalize(dataSet);
    int testSetLength = (int) (normMat.getRowDimension() * TEST_RATIO);
    Matrix trainingSubmatrix =
        normMat.getMatrix(
            testSetLength, normMat.getRowDimension() - 1, 0, normMat.getColumnDimension() - 1);
    List<Integer> classLabels = fileHelper.getClassLabels();
    List<Integer> trainingClassLabels = classLabels.subList(testSetLength, classLabels.size());

    int errorCount = 0;
    for (int i = 0; i < testSetLength; i++) {
      int classifierResult =
          classify(normMat.getArray()[i], trainingSubmatrix, trainingClassLabels, K_NUMBER);
      System.out.println(
          String.format(
              "The classifier came back with: %d, the real answer is: %d",
              classifierResult, classLabels.get(i)));
      if (classifierResult != classLabels.get(i)) {
        errorCount++;
      }
    }
    log.info("The total error rate is: " + errorCount / (float) testSetLength);
    log.info("Error number: " + errorCount);
    return errorCount;
  }
 protected void addToCentroid(Matrix m, PositionWeightMatrix pwm) {
   for (int i = 0; i < m.getColumnDimension(); i++) {
     PositionWeightColumn c = pwm.get(i);
     for (int j = 0; j < m.getRowDimension(); j++) {
       m.set(j, i, m.get(j, i) + c.getWeight(j));
     }
   }
 }
 /**
  * Checks if a matrix contains NaN elements
  *
  * @param m - original matrix
  * @return boolean
  */
 public static boolean matrixHasNanElements(Matrix m) {
   for (int i = 0; i < m.getRowDimension(); i++) {
     for (int j = 0; j < m.getColumnDimension(); j++) {
       if (Double.isNaN(m.get(i, j))) {
         return true;
       }
     }
   }
   return false;
 }
Esempio n. 16
0
  static void writeMat(BufferedWriter s, Matrix M) throws IOException {
    final int r = M.getRowDimension();
    final int c = M.getColumnDimension();

    s.write(r + " " + c + " 0"); // type always 0 for java version as its
    // ignored

    final double[][] Mv = M.getArray();
    for (int rr = 0; rr < r; rr++) for (int cc = 0; cc < c; cc++) s.write(Mv[rr][cc] + " ");
  }
 public static double getSumOfSquares(Matrix m) {
   if (m.getColumnDimension() != 1) {
     System.out.println("SumOFSquares only defined on vectors");
   }
   double sumOfSquares = 0.0;
   double[] elements = m.getColumnPackedCopy();
   for (int i = 0; i < elements.length; i++) {
     sumOfSquares += elements[i] * elements[i];
   }
   return sumOfSquares;
 }
  /**
   * Returns a matrix which contains on the diagonal the original elements, and zeros elsewhere
   * Input must be a nxm matrix with n = m
   *
   * @param m - original matrix
   * @return Matrix - the filtered matrix
   */
  public static Matrix getRectangularDiagonalMatrix(Matrix m) {
    if (m.getRowDimension() != m.getColumnDimension()) {
      return null;
    }

    Matrix diag = new Matrix(m.getRowDimension(), m.getRowDimension());
    for (int i = 0; i < m.getRowDimension(); i++) {
      diag.set(i, i, m.get(i, i));
    }
    return diag;
  }
 /**
  * Returns the product of all elements of a matrix (equivalent to Python's numpy.product(m))
  *
  * @param m - the input matrix
  * @return double - the result
  */
 public static double getMatrixAllElementsProduct(Matrix m) {
   final int rows = m.getRowDimension();
   final int cols = m.getColumnDimension();
   double result = 1.0;
   for (int i = 0; i < rows; i++) {
     for (int j = 0; j < cols; j++) {
       result *= m.get(i, j);
     }
   }
   return result;
 }
  public static RealMatrix getRealMatrixFromJamaMatrix(Matrix m) {
    final int rDim = m.getRowDimension();
    final int cDim = m.getColumnDimension();
    RealMatrix rm = new Array2DRowRealMatrix(rDim, cDim);
    for (int i = 0; i < rDim; i++) {
      for (int j = 0; j < cDim; j++) {
        rm.setEntry(i, j, m.get(i, j));
      }
    }

    return rm;
  }
  /** Gets the max score in a matrix m. */
  private double getMaxScore(final Matrix m) {
    final double blockingValue = (Double) settings.get(KEY_BLOCKING_VALUE);
    double max = Double.NEGATIVE_INFINITY;

    for (int i = 0; i < m.getRowDimension(); i++) {
      for (int j = 0; j < m.getColumnDimension(); j++) {
        if (m.get(i, j) > max && m.get(i, j) < blockingValue) {
          max = m.get(i, j);
        }
      }
    }
    return max;
  }
 public Matrix autoNormalize(Matrix dataSet) {
   double[] minVals = new double[dataSet.getColumnDimension()];
   Arrays.fill(minVals, Double.MAX_VALUE);
   double[] maxVals = new double[dataSet.getColumnDimension()];
   Arrays.fill(maxVals, Double.MIN_VALUE);
   for (int i = 0; i < dataSet.getRowDimension(); i++) {
     for (int j = 0; j < dataSet.getColumnDimension(); j++) {
       double el0 = dataSet.get(i, j);
       if (el0 < minVals[j]) {
         minVals[j] = el0;
       }
       if (el0 > maxVals[j]) {
         maxVals[j] = el0;
       }
     }
   }
   Matrix minMx = arrayToMatrix(minVals, dataSet.getRowDimension());
   Matrix maxMx = arrayToMatrix(maxVals, dataSet.getRowDimension());
   Matrix range = maxMx.minus(minMx);
   Matrix diff = dataSet.minus(minMx);
   return diff.arrayRightDivide(range);
 }
 /**
  * Returns a rows x columns matrix with reciprocal elements
  *
  * @param m - the input matrix
  * @return Matrix - the result matrix
  */
 public static Matrix getReciprocalMatrix(Matrix m) {
   final int rows = m.getRowDimension();
   final int cols = m.getColumnDimension();
   Matrix resultM = new Matrix(rows, cols);
   for (int i = 0; i < rows; i++) {
     for (int j = 0; j < cols; j++) {
       if (m.get(i, j) != 0.0) {
         resultM.set(i, j, 1.0 / m.get(i, j));
       } else {
         resultM.set(i, j, 0.0);
       }
     }
   }
   return resultM;
 }
Esempio n. 24
0
  public void multipleLinearRegression(Matrix datay, Matrix dataX, boolean interceptTerm) {
    b0Term = interceptTerm;
    if (interceptTerm) { // first column of X is filled with 1s if b_0 != 0
      int row = dataX.getRowDimension();
      int col = dataX.getColumnDimension();

      Matrix B = new Matrix(row, col + 1);
      Matrix ones = new Matrix(row, 1);
      for (int i = 0; i < row; i++) ones.set(i, 0, 1.0);
      B.setMatrix(0, row - 1, 0, 0, ones);
      B.setMatrix(0, row - 1, 1, col, dataX);
      multipleLinearRegression(datay, B);
    } else {
      multipleLinearRegression(datay, dataX);
    }
  }
Esempio n. 25
0
  public void multipleLinearRegression(String fileName, boolean interceptTerm) {
    try {
      BufferedReader reader = new BufferedReader(new FileReader(fileName));
      Matrix data = Matrix.read(reader);
      reader.close();
      int rows = data.getRowDimension() - 1;
      int cols = data.getColumnDimension() - 1;

      Matrix indVar =
          data.getMatrix(0, rows, 0, 0); // dataVowels(:,0) -> col 0 is the independent variable
      data = data.getMatrix(0, rows, 1, cols); // dataVowels(:,1:cols) -> dependent variables

      multipleLinearRegression(indVar, data, interceptTerm);

    } catch (Exception e) {
      throw new RuntimeException("Problem reading file " + fileName, e);
    }
  }
Esempio n. 26
0
  /**
   * * multipleLinearRegression providing index numbers for the columns in fileName, index 0
   * correspond to column 1
   *
   * @param fileName
   * @param indVariable column number (index) of the independent variable
   * @param c int[] column numbers array (indices) of dependent variables
   * @param rowIni and rowEnd should be given from 0 - maxData-1
   * @param interceptTerm
   */
  public void multipleLinearRegression(
      String fileName,
      int indVariable,
      int[] c,
      String[] factors,
      boolean interceptTerm,
      int rowIni,
      int rowEnd) {
    try {
      BufferedReader reader = new BufferedReader(new FileReader(fileName));
      Matrix data = Matrix.read(reader);
      reader.close();
      int rows = data.getRowDimension() - 1;
      int cols = data.getColumnDimension() - 1;

      if (rowIni < 0 || rowIni > rows)
        throw new RuntimeException(
            "Problem reading file, rowIni=" + rowIni + "  and number of rows in file=" + rows);
      if (rowEnd < 0 || rowEnd > rows)
        throw new RuntimeException(
            "Problem reading file, rowIni=" + rowIni + "  and number of rows in file=" + rows);
      if (rowIni > rowEnd)
        throw new RuntimeException(
            "Problem reading file, rowIni < rowend" + rowIni + " < " + rowEnd);

      Matrix indVar =
          data.getMatrix(
              rowIni,
              rowEnd,
              indVariable,
              indVariable); // dataVowels(:,0) -> last col is the independent variable
      data =
          data.getMatrix(
              rowIni, rowEnd,
              c); // the dependent variables correspond to the column indices in c
      multipleLinearRegression(indVar, data, interceptTerm);
    } catch (Exception e) {
      throw new RuntimeException("Problem reading file " + fileName, e);
    }
  }
Esempio n. 27
0
 public MyMatrix times(MyMatrix m) {
   if (numCols() != m.numRows()) {
     throw new RuntimeException("Invalid Matrix");
   }
   Matrix res = new Matrix(a.getRowDimension(), m.numCols());
   for (int i = 0; i < res.getRowDimension(); i++) {
     for (int j = 0; j < res.getColumnDimension(); j++) {
       double[] aY = new double[numCols()];
       double[] bX = new double[m.numRows()];
       for (int n = 0; n < aY.length; n++) {
         aY[n] = a.get(i, n);
       }
       for (int n = 0; n < bX.length; n++) {
         bX[n] = m.get(n, j);
       }
       MyVector u = new MyVector(aY);
       MyVector v = new MyVector(bX);
       res.set(i, j, u.dot(v));
     }
   }
   return new MyMatrix(res);
 }
Esempio n. 28
0
  /**
   * Given an activation 'act', joints angles and speed, compute the tension applied on every joint.
   *
   * @param act in [0,1]
   * @param angles (rad)
   * @param angSpeed (rad/s)
   * @return Torque (1xnb_joint) for each joint.
   */
  public Matrix computeTorque(Matrix act, Matrix angles, Matrix angSpeed) {

    // longueur du muscle
    _ln = computeLength(angles);
    // vitesse du muscle
    _vn = computeSpeed(angles, angSpeed);
    // tension (force)
    for (int col = 0; col < _tn.getColumnDimension(); col++) {
      assert act.get(0, col) >= 0.0 : "_act < 0";
      assert act.get(0, col) <= 1.0 : "_act > 1";
      double t =
          funA(act.get(0, col), _ln.get(0, col))
              * (funFl(_ln.get(0, col)) * funFv(_ln.get(0, col), _vn.get(0, col))
                  + funFp(_ln.get(0, col)));
      _tn.set(0, col, t);
    }
    // Real tension
    _t = _tn.arrayTimes(_sec).times(31.8);
    // Torque
    _cpl = _t.times(_mom);

    return _cpl;
  }
  public static void main(String argv[]) {
    Matrix A, B, C, Z, O, I, R, S, X, SUB, M, T, SQ, DEF, SOL;
    // Uncomment this to test IO in a different locale.
    // Locale.setDefault(Locale.GERMAN);
    int errorCount = 0;
    int warningCount = 0;
    double tmp, s;
    double[] columnwise = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.};
    double[] rowwise = {1., 4., 7., 10., 2., 5., 8., 11., 3., 6., 9., 12.};
    double[][] avals = {{1., 4., 7., 10.}, {2., 5., 8., 11.}, {3., 6., 9., 12.}};
    double[][] rankdef = avals;
    double[][] tvals = {{1., 2., 3.}, {4., 5., 6.}, {7., 8., 9.}, {10., 11., 12.}};
    double[][] subavals = {{5., 8., 11.}, {6., 9., 12.}};
    double[][] rvals = {{1., 4., 7.}, {2., 5., 8., 11.}, {3., 6., 9., 12.}};
    double[][] pvals = {{4., 1., 1.}, {1., 2., 3.}, {1., 3., 6.}};
    double[][] ivals = {{1., 0., 0., 0.}, {0., 1., 0., 0.}, {0., 0., 1., 0.}};
    double[][] evals = {
      {0., 1., 0., 0.}, {1., 0., 2.e-7, 0.}, {0., -2.e-7, 0., 1.}, {0., 0., 1., 0.}
    };
    double[][] square = {{166., 188., 210.}, {188., 214., 240.}, {210., 240., 270.}};
    double[][] sqSolution = {{13.}, {15.}};
    double[][] condmat = {{1., 3.}, {7., 9.}};
    double[][] badeigs = {
      {0, 0, 0, 0, 0}, {0, 0, 0, 0, 1}, {0, 0, 0, 1, 0}, {1, 1, 0, 0, 1}, {1, 0, 1, 0, 1}
    };
    int rows = 3, cols = 4;
    int invalidld = 5; /* should trigger bad shape for construction with val */
    int raggedr = 0; /* (raggedr,raggedc) should be out of bounds in ragged array */
    int raggedc = 4;
    int validld = 3; /* leading dimension of intended test Matrices */
    int nonconformld = 4; /* leading dimension which is valid, but nonconforming */
    int ib = 1, ie = 2, jb = 1, je = 3; /* index ranges for sub Matrix */
    int[] rowindexset = {1, 2};
    int[] badrowindexset = {1, 3};
    int[] columnindexset = {1, 2, 3};
    int[] badcolumnindexset = {1, 2, 4};
    double columnsummax = 33.;
    double rowsummax = 30.;
    double sumofdiagonals = 15;
    double sumofsquares = 650;

    /**
     * Constructors and constructor-like methods: double[], int double[][] int, int int, int, double
     * int, int, double[][] constructWithCopy(double[][]) random(int,int) identity(int)
     */
    print("\nTesting constructors and constructor-like methods...\n");
    try {
      /** check that exception is thrown in packed constructor with invalid length * */
      A = new Matrix(columnwise, invalidld);
      errorCount =
          try_failure(
              errorCount,
              "Catch invalid length in packed constructor... ",
              "exception not thrown for invalid input");
    } catch (IllegalArgumentException e) {
      try_success("Catch invalid length in packed constructor... ", e.getMessage());
    }
    try {
      /** check that exception is thrown in default constructor if input array is 'ragged' * */
      A = new Matrix(rvals);
      tmp = A.get(raggedr, raggedc);
    } catch (IllegalArgumentException e) {
      try_success("Catch ragged input to default constructor... ", e.getMessage());
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      errorCount =
          try_failure(
              errorCount,
              "Catch ragged input to constructor... ",
              "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later");
    }
    try {
      /** check that exception is thrown in constructWithCopy if input array is 'ragged' * */
      A = Matrix.constructWithCopy(rvals);
      tmp = A.get(raggedr, raggedc);
    } catch (IllegalArgumentException e) {
      try_success("Catch ragged input to constructWithCopy... ", e.getMessage());
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      errorCount =
          try_failure(
              errorCount,
              "Catch ragged input to constructWithCopy... ",
              "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later");
    }

    A = new Matrix(columnwise, validld);
    B = new Matrix(avals);
    tmp = B.get(0, 0);
    avals[0][0] = 0.0;
    C = B.minus(A);
    avals[0][0] = tmp;
    B = Matrix.constructWithCopy(avals);
    tmp = B.get(0, 0);
    avals[0][0] = 0.0;
    if ((tmp - B.get(0, 0)) != 0.0) {
      /** check that constructWithCopy behaves properly * */
      errorCount =
          try_failure(
              errorCount, "constructWithCopy... ", "copy not effected... data visible outside");
    } else {
      try_success("constructWithCopy... ", "");
    }
    avals[0][0] = columnwise[0];
    I = new Matrix(ivals);
    try {
      check(I, Matrix.identity(3, 4));
      try_success("identity... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(errorCount, "identity... ", "identity Matrix not successfully created");
    }

    /**
     * Access Methods: getColumnDimension() getRowDimension() getArray() getArrayCopy()
     * getColumnPackedCopy() getRowPackedCopy() get(int,int) getMatrix(int,int,int,int)
     * getMatrix(int,int,int[]) getMatrix(int[],int,int) getMatrix(int[],int[]) set(int,int,double)
     * setMatrix(int,int,int,int,Matrix) setMatrix(int,int,int[],Matrix)
     * setMatrix(int[],int,int,Matrix) setMatrix(int[],int[],Matrix)
     */
    print("\nTesting access methods...\n");

    /** Various get methods: */
    B = new Matrix(avals);
    if (B.getRowDimension() != rows) {
      errorCount = try_failure(errorCount, "getRowDimension... ", "");
    } else {
      try_success("getRowDimension... ", "");
    }
    if (B.getColumnDimension() != cols) {
      errorCount = try_failure(errorCount, "getColumnDimension... ", "");
    } else {
      try_success("getColumnDimension... ", "");
    }
    B = new Matrix(avals);
    double[][] barray = B.getArray();
    if (barray != avals) {
      errorCount = try_failure(errorCount, "getArray... ", "");
    } else {
      try_success("getArray... ", "");
    }
    barray = B.getArrayCopy();
    if (barray == avals) {
      errorCount = try_failure(errorCount, "getArrayCopy... ", "data not (deep) copied");
    }
    try {
      check(barray, avals);
      try_success("getArrayCopy... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(errorCount, "getArrayCopy... ", "data not successfully (deep) copied");
    }
    double[] bpacked = B.getColumnPackedCopy();
    try {
      check(bpacked, columnwise);
      try_success("getColumnPackedCopy... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(
              errorCount,
              "getColumnPackedCopy... ",
              "data not successfully (deep) copied by columns");
    }
    bpacked = B.getRowPackedCopy();
    try {
      check(bpacked, rowwise);
      try_success("getRowPackedCopy... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(
              errorCount, "getRowPackedCopy... ", "data not successfully (deep) copied by rows");
    }
    try {
      tmp = B.get(B.getRowDimension(), B.getColumnDimension() - 1);
      errorCount =
          try_failure(
              errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown");
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      try {
        tmp = B.get(B.getRowDimension() - 1, B.getColumnDimension());
        errorCount =
            try_failure(
                errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown");
      } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
        try_success("get(int,int)... OutofBoundsException... ", "");
      }
    } catch (java.lang.IllegalArgumentException e1) {
      errorCount =
          try_failure(
              errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown");
    }
    try {
      if (B.get(B.getRowDimension() - 1, B.getColumnDimension() - 1)
          != avals[B.getRowDimension() - 1][B.getColumnDimension() - 1]) {
        errorCount =
            try_failure(
                errorCount, "get(int,int)... ", "Matrix entry (i,j) not successfully retreived");
      } else {
        try_success("get(int,int)... ", "");
      }
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      errorCount =
          try_failure(errorCount, "get(int,int)... ", "Unexpected ArrayIndexOutOfBoundsException");
    }
    SUB = new Matrix(subavals);
    try {
      M = B.getMatrix(ib, ie + B.getRowDimension() + 1, jb, je);
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int,int,int,int)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      try {
        M = B.getMatrix(ib, ie, jb, je + B.getColumnDimension() + 1);
        errorCount =
            try_failure(
                errorCount,
                "getMatrix(int,int,int,int)... ",
                "ArrayIndexOutOfBoundsException expected but not thrown");
      } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
        try_success("getMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", "");
      }
    } catch (java.lang.IllegalArgumentException e1) {
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int,int,int,int)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    }
    try {
      M = B.getMatrix(ib, ie, jb, je);
      try {
        check(SUB, M);
        try_success("getMatrix(int,int,int,int)... ", "");
      } catch (java.lang.RuntimeException e) {
        errorCount =
            try_failure(
                errorCount,
                "getMatrix(int,int,int,int)... ",
                "submatrix not successfully retreived");
      }
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int,int,int,int)... ",
              "Unexpected ArrayIndexOutOfBoundsException");
    }

    try {
      M = B.getMatrix(ib, ie, badcolumnindexset);
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int,int,int[])... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      try {
        M = B.getMatrix(ib, ie + B.getRowDimension() + 1, columnindexset);
        errorCount =
            try_failure(
                errorCount,
                "getMatrix(int,int,int[])... ",
                "ArrayIndexOutOfBoundsException expected but not thrown");
      } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
        try_success("getMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", "");
      }
    } catch (java.lang.IllegalArgumentException e1) {
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int,int,int[])... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    }
    try {
      M = B.getMatrix(ib, ie, columnindexset);
      try {
        check(SUB, M);
        try_success("getMatrix(int,int,int[])... ", "");
      } catch (java.lang.RuntimeException e) {
        errorCount =
            try_failure(
                errorCount, "getMatrix(int,int,int[])... ", "submatrix not successfully retreived");
      }
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int,int,int[])... ",
              "Unexpected ArrayIndexOutOfBoundsException");
    }
    try {
      M = B.getMatrix(badrowindexset, jb, je);
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int[],int,int)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      try {
        M = B.getMatrix(rowindexset, jb, je + B.getColumnDimension() + 1);
        errorCount =
            try_failure(
                errorCount,
                "getMatrix(int[],int,int)... ",
                "ArrayIndexOutOfBoundsException expected but not thrown");
      } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
        try_success("getMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", "");
      }
    } catch (java.lang.IllegalArgumentException e1) {
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int[],int,int)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    }
    try {
      M = B.getMatrix(rowindexset, jb, je);
      try {
        check(SUB, M);
        try_success("getMatrix(int[],int,int)... ", "");
      } catch (java.lang.RuntimeException e) {
        errorCount =
            try_failure(
                errorCount, "getMatrix(int[],int,int)... ", "submatrix not successfully retreived");
      }
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int[],int,int)... ",
              "Unexpected ArrayIndexOutOfBoundsException");
    }
    try {
      M = B.getMatrix(badrowindexset, columnindexset);
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int[],int[])... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      try {
        M = B.getMatrix(rowindexset, badcolumnindexset);
        errorCount =
            try_failure(
                errorCount,
                "getMatrix(int[],int[])... ",
                "ArrayIndexOutOfBoundsException expected but not thrown");
      } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
        try_success("getMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", "");
      }
    } catch (java.lang.IllegalArgumentException e1) {
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int[],int[])... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    }
    try {
      M = B.getMatrix(rowindexset, columnindexset);
      try {
        check(SUB, M);
        try_success("getMatrix(int[],int[])... ", "");
      } catch (java.lang.RuntimeException e) {
        errorCount =
            try_failure(
                errorCount, "getMatrix(int[],int[])... ", "submatrix not successfully retreived");
      }
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      errorCount =
          try_failure(
              errorCount,
              "getMatrix(int[],int[])... ",
              "Unexpected ArrayIndexOutOfBoundsException");
    }

    /** Various set methods: */
    try {
      B.set(B.getRowDimension(), B.getColumnDimension() - 1, 0.);
      errorCount =
          try_failure(
              errorCount,
              "set(int,int,double)... ",
              "OutOfBoundsException expected but not thrown");
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      try {
        B.set(B.getRowDimension() - 1, B.getColumnDimension(), 0.);
        errorCount =
            try_failure(
                errorCount,
                "set(int,int,double)... ",
                "OutOfBoundsException expected but not thrown");
      } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
        try_success("set(int,int,double)... OutofBoundsException... ", "");
      }
    } catch (java.lang.IllegalArgumentException e1) {
      errorCount =
          try_failure(
              errorCount,
              "set(int,int,double)... ",
              "OutOfBoundsException expected but not thrown");
    }
    try {
      B.set(ib, jb, 0.);
      tmp = B.get(ib, jb);
      try {
        check(tmp, 0.);
        try_success("set(int,int,double)... ", "");
      } catch (java.lang.RuntimeException e) {
        errorCount =
            try_failure(
                errorCount, "set(int,int,double)... ", "Matrix element not successfully set");
      }
    } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
      errorCount =
          try_failure(
              errorCount, "set(int,int,double)... ", "Unexpected ArrayIndexOutOfBoundsException");
    }
    M = new Matrix(2, 3, 0.);
    try {
      B.setMatrix(ib, ie + B.getRowDimension() + 1, jb, je, M);
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int,int,int,int,Matrix)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      try {
        B.setMatrix(ib, ie, jb, je + B.getColumnDimension() + 1, M);
        errorCount =
            try_failure(
                errorCount,
                "setMatrix(int,int,int,int,Matrix)... ",
                "ArrayIndexOutOfBoundsException expected but not thrown");
      } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
        try_success("setMatrix(int,int,int,int,Matrix)... ArrayIndexOutOfBoundsException... ", "");
      }
    } catch (java.lang.IllegalArgumentException e1) {
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int,int,int,int,Matrix)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    }
    try {
      B.setMatrix(ib, ie, jb, je, M);
      try {
        check(M.minus(B.getMatrix(ib, ie, jb, je)), M);
        try_success("setMatrix(int,int,int,int,Matrix)... ", "");
      } catch (java.lang.RuntimeException e) {
        errorCount =
            try_failure(
                errorCount,
                "setMatrix(int,int,int,int,Matrix)... ",
                "submatrix not successfully set");
      }
      B.setMatrix(ib, ie, jb, je, SUB);
    } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int,int,int,int,Matrix)... ",
              "Unexpected ArrayIndexOutOfBoundsException");
    }
    try {
      B.setMatrix(ib, ie + B.getRowDimension() + 1, columnindexset, M);
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int,int,int[],Matrix)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      try {
        B.setMatrix(ib, ie, badcolumnindexset, M);
        errorCount =
            try_failure(
                errorCount,
                "setMatrix(int,int,int[],Matrix)... ",
                "ArrayIndexOutOfBoundsException expected but not thrown");
      } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
        try_success("setMatrix(int,int,int[],Matrix)... ArrayIndexOutOfBoundsException... ", "");
      }
    } catch (java.lang.IllegalArgumentException e1) {
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int,int,int[],Matrix)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    }
    try {
      B.setMatrix(ib, ie, columnindexset, M);
      try {
        check(M.minus(B.getMatrix(ib, ie, columnindexset)), M);
        try_success("setMatrix(int,int,int[],Matrix)... ", "");
      } catch (java.lang.RuntimeException e) {
        errorCount =
            try_failure(
                errorCount,
                "setMatrix(int,int,int[],Matrix)... ",
                "submatrix not successfully set");
      }
      B.setMatrix(ib, ie, jb, je, SUB);
    } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int,int,int[],Matrix)... ",
              "Unexpected ArrayIndexOutOfBoundsException");
    }
    try {
      B.setMatrix(rowindexset, jb, je + B.getColumnDimension() + 1, M);
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int[],int,int,Matrix)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      try {
        B.setMatrix(badrowindexset, jb, je, M);
        errorCount =
            try_failure(
                errorCount,
                "setMatrix(int[],int,int,Matrix)... ",
                "ArrayIndexOutOfBoundsException expected but not thrown");
      } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
        try_success("setMatrix(int[],int,int,Matrix)... ArrayIndexOutOfBoundsException... ", "");
      }
    } catch (java.lang.IllegalArgumentException e1) {
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int[],int,int,Matrix)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    }
    try {
      B.setMatrix(rowindexset, jb, je, M);
      try {
        check(M.minus(B.getMatrix(rowindexset, jb, je)), M);
        try_success("setMatrix(int[],int,int,Matrix)... ", "");
      } catch (java.lang.RuntimeException e) {
        errorCount =
            try_failure(
                errorCount,
                "setMatrix(int[],int,int,Matrix)... ",
                "submatrix not successfully set");
      }
      B.setMatrix(ib, ie, jb, je, SUB);
    } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int[],int,int,Matrix)... ",
              "Unexpected ArrayIndexOutOfBoundsException");
    }
    try {
      B.setMatrix(rowindexset, badcolumnindexset, M);
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int[],int[],Matrix)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      try {
        B.setMatrix(badrowindexset, columnindexset, M);
        errorCount =
            try_failure(
                errorCount,
                "setMatrix(int[],int[],Matrix)... ",
                "ArrayIndexOutOfBoundsException expected but not thrown");
      } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
        try_success("setMatrix(int[],int[],Matrix)... ArrayIndexOutOfBoundsException... ", "");
      }
    } catch (java.lang.IllegalArgumentException e1) {
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int[],int[],Matrix)... ",
              "ArrayIndexOutOfBoundsException expected but not thrown");
    }
    try {
      B.setMatrix(rowindexset, columnindexset, M);
      try {
        check(M.minus(B.getMatrix(rowindexset, columnindexset)), M);
        try_success("setMatrix(int[],int[],Matrix)... ", "");
      } catch (java.lang.RuntimeException e) {
        errorCount =
            try_failure(
                errorCount, "setMatrix(int[],int[],Matrix)... ", "submatrix not successfully set");
      }
    } catch (java.lang.ArrayIndexOutOfBoundsException e1) {
      errorCount =
          try_failure(
              errorCount,
              "setMatrix(int[],int[],Matrix)... ",
              "Unexpected ArrayIndexOutOfBoundsException");
    }

    /**
     * Array-like methods: minus minusEquals plus plusEquals arrayLeftDivide arrayLeftDivideEquals
     * arrayRightDivide arrayRightDivideEquals arrayTimes arrayTimesEquals uminus
     */
    print("\nTesting array-like methods...\n");
    S = new Matrix(columnwise, nonconformld);
    R = Matrix.random(A.getRowDimension(), A.getColumnDimension());
    A = R;
    try {
      S = A.minus(S);
      errorCount =
          try_failure(errorCount, "minus conformance check... ", "nonconformance not raised");
    } catch (IllegalArgumentException e) {
      try_success("minus conformance check... ", "");
    }
    if (A.minus(R).norm1() != 0.) {
      errorCount =
          try_failure(
              errorCount,
              "minus... ",
              "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)");
    } else {
      try_success("minus... ", "");
    }
    A = R.copy();
    A.minusEquals(R);
    Z = new Matrix(A.getRowDimension(), A.getColumnDimension());
    try {
      A.minusEquals(S);
      errorCount =
          try_failure(errorCount, "minusEquals conformance check... ", "nonconformance not raised");
    } catch (IllegalArgumentException e) {
      try_success("minusEquals conformance check... ", "");
    }
    if (A.minus(Z).norm1() != 0.) {
      errorCount =
          try_failure(
              errorCount,
              "minusEquals... ",
              "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)");
    } else {
      try_success("minusEquals... ", "");
    }

    A = R.copy();
    B = Matrix.random(A.getRowDimension(), A.getColumnDimension());
    C = A.minus(B);
    try {
      S = A.plus(S);
      errorCount =
          try_failure(errorCount, "plus conformance check... ", "nonconformance not raised");
    } catch (IllegalArgumentException e) {
      try_success("plus conformance check... ", "");
    }
    try {
      check(C.plus(B), A);
      try_success("plus... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "plus... ", "(C = A - B, but C + B != A)");
    }
    C = A.minus(B);
    C.plusEquals(B);
    try {
      A.plusEquals(S);
      errorCount =
          try_failure(errorCount, "plusEquals conformance check... ", "nonconformance not raised");
    } catch (IllegalArgumentException e) {
      try_success("plusEquals conformance check... ", "");
    }
    try {
      check(C, A);
      try_success("plusEquals... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "plusEquals... ", "(C = A - B, but C = C + B != A)");
    }
    A = R.uminus();
    try {
      check(A.plus(R), Z);
      try_success("uminus... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "uminus... ", "(-A + A != zeros)");
    }
    A = R.copy();
    O = new Matrix(A.getRowDimension(), A.getColumnDimension(), 1.0);
    C = A.arrayLeftDivide(R);
    try {
      S = A.arrayLeftDivide(S);
      errorCount =
          try_failure(
              errorCount, "arrayLeftDivide conformance check... ", "nonconformance not raised");
    } catch (IllegalArgumentException e) {
      try_success("arrayLeftDivide conformance check... ", "");
    }
    try {
      check(C, O);
      try_success("arrayLeftDivide... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "arrayLeftDivide... ", "(M.\\M != ones)");
    }
    try {
      A.arrayLeftDivideEquals(S);
      errorCount =
          try_failure(
              errorCount,
              "arrayLeftDivideEquals conformance check... ",
              "nonconformance not raised");
    } catch (IllegalArgumentException e) {
      try_success("arrayLeftDivideEquals conformance check... ", "");
    }
    A.arrayLeftDivideEquals(R);
    try {
      check(A, O);
      try_success("arrayLeftDivideEquals... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "arrayLeftDivideEquals... ", "(M.\\M != ones)");
    }
    A = R.copy();
    try {
      A.arrayRightDivide(S);
      errorCount =
          try_failure(
              errorCount, "arrayRightDivide conformance check... ", "nonconformance not raised");
    } catch (IllegalArgumentException e) {
      try_success("arrayRightDivide conformance check... ", "");
    }
    C = A.arrayRightDivide(R);
    try {
      check(C, O);
      try_success("arrayRightDivide... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "arrayRightDivide... ", "(M./M != ones)");
    }
    try {
      A.arrayRightDivideEquals(S);
      errorCount =
          try_failure(
              errorCount,
              "arrayRightDivideEquals conformance check... ",
              "nonconformance not raised");
    } catch (IllegalArgumentException e) {
      try_success("arrayRightDivideEquals conformance check... ", "");
    }
    A.arrayRightDivideEquals(R);
    try {
      check(A, O);
      try_success("arrayRightDivideEquals... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "arrayRightDivideEquals... ", "(M./M != ones)");
    }
    A = R.copy();
    B = Matrix.random(A.getRowDimension(), A.getColumnDimension());
    try {
      S = A.arrayTimes(S);
      errorCount =
          try_failure(errorCount, "arrayTimes conformance check... ", "nonconformance not raised");
    } catch (IllegalArgumentException e) {
      try_success("arrayTimes conformance check... ", "");
    }
    C = A.arrayTimes(B);
    try {
      check(C.arrayRightDivideEquals(B), A);
      try_success("arrayTimes... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "arrayTimes... ", "(A = R, C = A.*B, but C./B != A)");
    }
    try {
      A.arrayTimesEquals(S);
      errorCount =
          try_failure(
              errorCount, "arrayTimesEquals conformance check... ", "nonconformance not raised");
    } catch (IllegalArgumentException e) {
      try_success("arrayTimesEquals conformance check... ", "");
    }
    A.arrayTimesEquals(B);
    try {
      check(A.arrayRightDivideEquals(B), R);
      try_success("arrayTimesEquals... ", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(errorCount, "arrayTimesEquals... ", "(A = R, A = A.*B, but A./B != R)");
    }

    /** I/O methods: read print serializable: writeObject readObject */
    print("\nTesting I/O methods...\n");
    try {
      DecimalFormat fmt = new DecimalFormat("0.0000E00");
      fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));

      PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out"));
      A.print(FILE, fmt, 10);
      FILE.close();
      R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out")));
      if (A.minus(R).norm1() < .001) {
        try_success("print()/read()...", "");
      } else {
        errorCount =
            try_failure(
                errorCount,
                "print()/read()...",
                "Matrix read from file does not match Matrix printed to file");
      }
    } catch (java.io.IOException ioe) {
      warningCount =
          try_warning(
              warningCount,
              "print()/read()...",
              "unexpected I/O error, unable to run print/read test;  check write permission in current directory and retry");
    } catch (Exception e) {
      try {
        e.printStackTrace(System.out);
        warningCount =
            try_warning(
                warningCount,
                "print()/read()...",
                "Formatting error... will try JDK1.1 reformulation...");
        DecimalFormat fmt = new DecimalFormat("0.0000");
        PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out"));
        A.print(FILE, fmt, 10);
        FILE.close();
        R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out")));
        if (A.minus(R).norm1() < .001) {
          try_success("print()/read()...", "");
        } else {
          errorCount =
              try_failure(
                  errorCount,
                  "print()/read() (2nd attempt) ...",
                  "Matrix read from file does not match Matrix printed to file");
        }
      } catch (java.io.IOException ioe) {
        warningCount =
            try_warning(
                warningCount,
                "print()/read()...",
                "unexpected I/O error, unable to run print/read test;  check write permission in current directory and retry");
      }
    }

    R = Matrix.random(A.getRowDimension(), A.getColumnDimension());
    String tmpname = "TMPMATRIX.serial";
    try {
      @SuppressWarnings("resource")
      ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmpname));
      out.writeObject(R);
      @SuppressWarnings("resource")
      ObjectInputStream sin = new ObjectInputStream(new FileInputStream(tmpname));
      A = (Matrix) sin.readObject();

      try {
        check(A, R);
        try_success("writeObject(Matrix)/readObject(Matrix)...", "");
      } catch (java.lang.RuntimeException e) {
        errorCount =
            try_failure(
                errorCount,
                "writeObject(Matrix)/readObject(Matrix)...",
                "Matrix not serialized correctly");
      }
    } catch (java.io.IOException ioe) {
      warningCount =
          try_warning(
              warningCount,
              "writeObject()/readObject()...",
              "unexpected I/O error, unable to run serialization test;  check write permission in current directory and retry");
    } catch (Exception e) {
      errorCount =
          try_failure(
              errorCount,
              "writeObject(Matrix)/readObject(Matrix)...",
              "unexpected error in serialization test");
    }

    /**
     * LA methods: transpose times cond rank det trace norm1 norm2 normF normInf solve
     * solveTranspose inverse chol eig lu qr svd
     */
    print("\nTesting linear algebra methods...\n");
    A = new Matrix(columnwise, 3);
    T = new Matrix(tvals);
    T = A.transpose();
    try {
      check(A.transpose(), T);
      try_success("transpose...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "transpose()...", "transpose unsuccessful");
    }
    A.transpose();
    try {
      check(A.norm1(), columnsummax);
      try_success("norm1...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "norm1()...", "incorrect norm calculation");
    }
    try {
      check(A.normInf(), rowsummax);
      try_success("normInf()...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "normInf()...", "incorrect norm calculation");
    }
    try {
      check(A.normF(), Math.sqrt(sumofsquares));
      try_success("normF...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "normF()...", "incorrect norm calculation");
    }
    try {
      check(A.trace(), sumofdiagonals);
      try_success("trace()...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "trace()...", "incorrect trace calculation");
    }
    try {
      check(A.getMatrix(0, A.getRowDimension() - 1, 0, A.getRowDimension() - 1).det(), 0.);
      try_success("det()...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "det()...", "incorrect determinant calculation");
    }
    SQ = new Matrix(square);
    try {
      check(A.times(A.transpose()), SQ);
      try_success("times(Matrix)...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(
              errorCount, "times(Matrix)...", "incorrect Matrix-Matrix product calculation");
    }
    try {
      check(A.times(0.), Z);
      try_success("times(double)...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(
              errorCount, "times(double)...", "incorrect Matrix-scalar product calculation");
    }

    A = new Matrix(columnwise, 4);
    QRDecomposition QR = A.qr();
    R = QR.getR();
    try {
      check(A, QR.getQ().times(R));
      try_success("QRDecomposition...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(errorCount, "QRDecomposition...", "incorrect QR decomposition calculation");
    }
    SingularValueDecomposition SVD = A.svd();
    try {
      check(A, SVD.getU().times(SVD.getS().times(SVD.getV().transpose())));
      try_success("SingularValueDecomposition...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(
              errorCount,
              "SingularValueDecomposition...",
              "incorrect singular value decomposition calculation");
    }
    DEF = new Matrix(rankdef);
    try {
      check(DEF.rank(), Math.min(DEF.getRowDimension(), DEF.getColumnDimension()) - 1);
      try_success("rank()...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "rank()...", "incorrect rank calculation");
    }
    B = new Matrix(condmat);
    SVD = B.svd();
    double[] singularvalues = SVD.getSingularValues();
    try {
      check(
          B.cond(),
          singularvalues[0]
              / singularvalues[Math.min(B.getRowDimension(), B.getColumnDimension()) - 1]);
      try_success("cond()...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "cond()...", "incorrect condition number calculation");
    }
    int n = A.getColumnDimension();
    A = A.getMatrix(0, n - 1, 0, n - 1);
    A.set(0, 0, 0.);
    LUDecomposition LU = A.lu();
    try {
      check(A.getMatrix(LU.getPivot(), 0, n - 1), LU.getL().times(LU.getU()));
      try_success("LUDecomposition...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(errorCount, "LUDecomposition...", "incorrect LU decomposition calculation");
    }
    X = A.inverse();
    try {
      check(A.times(X), Matrix.identity(3, 3));
      try_success("inverse()...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "inverse()...", "incorrect inverse calculation");
    }
    O = new Matrix(SUB.getRowDimension(), 1, 1.0);
    SOL = new Matrix(sqSolution);
    SQ = SUB.getMatrix(0, SUB.getRowDimension() - 1, 0, SUB.getRowDimension() - 1);
    try {
      check(SQ.solve(SOL), O);
      try_success("solve()...", "");
    } catch (java.lang.IllegalArgumentException e1) {
      errorCount = try_failure(errorCount, "solve()...", e1.getMessage());
    } catch (java.lang.RuntimeException e) {
      errorCount = try_failure(errorCount, "solve()...", e.getMessage());
    }
    A = new Matrix(pvals);
    CholeskyDecomposition Chol = A.chol();
    Matrix L = Chol.getL();
    try {
      check(A, L.times(L.transpose()));
      try_success("CholeskyDecomposition...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(
              errorCount,
              "CholeskyDecomposition...",
              "incorrect Cholesky decomposition calculation");
    }
    X = Chol.solve(Matrix.identity(3, 3));
    try {
      check(A.times(X), Matrix.identity(3, 3));
      try_success("CholeskyDecomposition solve()...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(
              errorCount,
              "CholeskyDecomposition solve()...",
              "incorrect Choleskydecomposition solve calculation");
    }
    EigenvalueDecomposition Eig = A.eig();
    Matrix D = Eig.getD();
    Matrix V = Eig.getV();
    try {
      check(A.times(V), V.times(D));
      try_success("EigenvalueDecomposition (symmetric)...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(
              errorCount,
              "EigenvalueDecomposition (symmetric)...",
              "incorrect symmetric Eigenvalue decomposition calculation");
    }
    A = new Matrix(evals);
    Eig = A.eig();
    D = Eig.getD();
    V = Eig.getV();
    try {
      check(A.times(V), V.times(D));
      try_success("EigenvalueDecomposition (nonsymmetric)...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(
              errorCount,
              "EigenvalueDecomposition (nonsymmetric)...",
              "incorrect nonsymmetric Eigenvalue decomposition calculation");
    }

    try {
      print("\nTesting Eigenvalue; If this hangs, we've failed\n");
      Matrix bA = new Matrix(badeigs);
      EigenvalueDecomposition bEig = bA.eig();
      try_success("EigenvalueDecomposition (hang)...", "");
    } catch (java.lang.RuntimeException e) {
      errorCount =
          try_failure(errorCount, "EigenvalueDecomposition (hang)...", "incorrect termination");
    }

    print("\nTestMatrix completed.\n");
    print("Total errors reported: " + Integer.toString(errorCount) + "\n");
    print("Total warnings reported: " + Integer.toString(warningCount) + "\n");
  }
Esempio n. 30
0
 public int cols() {
   return matrix.getColumnDimension();
 }