示例#1
0
    private Matrix SqrtSPKF(Matrix PDash) {
      // Only works with a symmetric Positive Definite matrix
      // [V,D] = eig(A)
      // S = V*diag(sqrt(diag(D)))*V'
      //
      // //PDash in
      // System.out.println("PDash: ");
      // PDash.print(3, 2);

      // Matrix NegKeeper = Matrix.identity(9, 9);
      // //Testing Forced Compliance
      // for(int i = 0; i< 9; i++){
      // if (PDash.get(i, i)< 0){
      // NegKeeper.set(i,i,-1);
      // PDash.set(i, i, -PDash.get(i, i));
      // }
      // }
      EigenvalueDecomposition eig = PDash.eig();
      Matrix V = eig.getV();
      Matrix D = eig.getD();
      int iDSize = D.getRowDimension();
      for (int i = 0; i < iDSize; i++) {
        D.set(i, i, Math.sqrt(D.get(i, i)));
      }
      Matrix S = V.times(D).times(V.inverse());
      // S = S.times(NegKeeper);
      return S;
    }
  public double[][] Eigenvectors(Matrix m) {
    EigenvalueDecomposition decomposition = m.eig();
    Matrix eigenVectorsMatrix = decomposition.getV();
    double[][] eigenvectors = eigenVectorsMatrix.getArray();

    //	   	System.out.println("eigenvectors matrix");
    //	   	eigenVectorsMatrix.print(2,2);

    return eigenvectors;
  }
  public double[] Eigenvalues(Matrix m) {
    EigenvalueDecomposition decomposition = m.eig();
    double[] eigenvalues = decomposition.getRealEigenvalues();

    //		System.out.println("eigenvalues: ");
    //		for(int i=0;i<eigenvalues.length;i++)
    //			System.out.println(""+eigenvalues[i]);

    return eigenvalues;
  }
示例#4
0
 public void testJacobian() throws Exception {
   OdeSystem sys = new SimpleTest();
   // (4,0) punto silla
   Matrix jac = sys.getJacobianMatrix(new double[] {4, 0});
   EigenvalueDecomposition eig = jac.eig();
   double[] imag = eig.getImagEigenvalues();
   double[] real = eig.getRealEigenvalues();
   print(real, imag);
   // TODO que devuelva numérico!
   assertEquals("hyperbolic unstable saddle point ", Stability.getPointType(real, imag));
   System.out.println(Stability.getPointType(real, imag));
 }
  @Override
  public void doWork() throws OperatorException {
    ExampleSet exampleSet = exampleSetInput.getData(ExampleSet.class);

    // only use numeric attributes
    Tools.onlyNumericalAttributes(exampleSet, "KernelPCA");
    Tools.onlyNonMissingValues(exampleSet, getOperatorClassName(), this);

    Attributes attributes = exampleSet.getAttributes();
    int numberOfExamples = exampleSet.size();

    // calculating means for later zero centering
    exampleSet.recalculateAllAttributeStatistics();
    double[] means = new double[exampleSet.getAttributes().size()];
    int i = 0;
    for (Attribute attribute : exampleSet.getAttributes()) {
      means[i] = exampleSet.getStatistics(attribute, Statistics.AVERAGE);
      i++;
    }

    // kernel
    Kernel kernel = Kernel.createKernel(this);

    // copying zero centered exampleValues
    ArrayList<double[]> exampleValues = new ArrayList<double[]>(numberOfExamples);
    i = 0;
    for (Example columnExample : exampleSet) {
      double[] columnValues = getAttributeValues(columnExample, attributes, means);
      exampleValues.add(columnValues);
      i++;
    }

    // filling kernel matrix
    Matrix kernelMatrix = new Matrix(numberOfExamples, numberOfExamples);
    for (i = 0; i < numberOfExamples; i++) {
      for (int j = 0; j < numberOfExamples; j++) {
        kernelMatrix.set(
            i, j, kernel.calculateDistance(exampleValues.get(i), exampleValues.get(j)));
      }
    }

    // calculating eigenVectors
    EigenvalueDecomposition eig = kernelMatrix.eig();
    Model model = new KernelPCAModel(exampleSet, means, eig.getV(), exampleValues, kernel);

    if (exampleSetOutput.isConnected()) {
      exampleSetOutput.deliver(model.apply(exampleSet));
    }
    originalOutput.deliver(exampleSet);
    modelOutput.deliver(model);
  }
 public static String getEigenValues(GraphModel g) {
   Matrix A = g.getWeightedAdjacencyMatrix();
   EigenvalueDecomposition ed = A.eig();
   double rv[] = ed.getRealEigenvalues();
   double iv[] = ed.getImagEigenvalues();
   String res = "";
   for (int i = 0; i < rv.length; i++) {
     if (iv[i] != 0) res += "" + round(rv[i], 3) + " + " + round(iv[i], 3) + "i";
     else res += "" + round(rv[i], 3);
     if (i != rv.length - 1) {
       res += ",";
     }
   }
   return res;
 }
  @Override
  public final void process(final Spot spot) {

    if (img.numDimensions() == 3) {

      // 3D case
      final SpotNeighborhood<T> neighborhood = new SpotNeighborhood<T>(spot, img);
      final SpotNeighborhoodCursor<T> cursor = neighborhood.cursor();

      double x, y, z;
      double x2, y2, z2;
      double mass, totalmass = 0;
      double Ixx = 0, Iyy = 0, Izz = 0, Ixy = 0, Ixz = 0, Iyz = 0;
      final double[] position = new double[img.numDimensions()];

      while (cursor.hasNext()) {
        cursor.fwd();
        mass = cursor.get().getRealDouble();
        cursor.getRelativePosition(position);
        x = position[0];
        y = position[1];
        z = position[2];
        totalmass += mass;
        x2 = x * x;
        y2 = y * y;
        z2 = z * z;
        Ixx += mass * (y2 + z2);
        Iyy += mass * (x2 + z2);
        Izz += mass * (x2 + y2);
        Ixy -= mass * x * y;
        Ixz -= mass * x * z;
        Iyz -= mass * y * z;
      }

      final Matrix mat =
          new Matrix(new double[][] {{Ixx, Ixy, Ixz}, {Ixy, Iyy, Iyz}, {Ixz, Iyz, Izz}});
      mat.timesEquals(1 / totalmass);
      final EigenvalueDecomposition eigdec = mat.eig();
      final double[] eigenvalues = eigdec.getRealEigenvalues();
      final Matrix eigenvectors = eigdec.getV();

      final double I1 = eigenvalues[0];
      final double I2 = eigenvalues[1];
      final double I3 = eigenvalues[2];
      final double a = Math.sqrt(2.5 * (I2 + I3 - I1));
      final double b = Math.sqrt(2.5 * (I3 + I1 - I2));
      final double c = Math.sqrt(2.5 * (I1 + I2 - I3));
      final double[] semiaxes = new double[] {a, b, c};

      // Sort semi-axes by ascendent order and get the sorting index
      final double[] semiaxes_ordered = semiaxes.clone();
      Arrays.sort(semiaxes_ordered);
      final int[] order = new int[3];
      for (int i = 0; i < semiaxes_ordered.length; i++)
        for (int j = 0; j < semiaxes.length; j++)
          if (semiaxes_ordered[i] == semiaxes[j]) order[i] = j;

      // Get the sorted eigenvalues
      final double[][] uvectors = new double[3][3];
      for (int i = 0; i < eigenvalues.length; i++) {
        uvectors[i][0] = eigenvectors.get(0, order[i]);
        uvectors[i][1] = eigenvectors.get(1, order[i]);
        uvectors[i][2] = eigenvectors.get(2, order[i]);
      }

      // Store in the Spot object
      double theta, phi;
      for (int i = 0; i < uvectors.length; i++) {
        theta =
            Math.acos(
                uvectors[i][2]
                    / Math.sqrt(
                        uvectors[i][0] * uvectors[i][0]
                            + uvectors[i][1] * uvectors[i][1]
                            + uvectors[i][2] * uvectors[i][2]));
        phi = Math.atan2(uvectors[i][1], uvectors[i][0]);
        if (phi < -Math.PI / 2) phi += Math.PI; // For an ellipsoid we care only for the
        // angles in [-pi/2 , pi/2]
        if (phi > Math.PI / 2) phi -= Math.PI;

        // Store in descending order
        spot.putFeature(featurelist_sa[i], semiaxes_ordered[i]);
        spot.putFeature(featurelist_phi[i], phi);
        spot.putFeature(featurelist_theta[i], theta);
      }

      // Store the Spot morphology (needs to be outside the above loop)
      spot.putFeature(MORPHOLOGY, estimateMorphology(semiaxes_ordered));

    } else if (img.numDimensions() == 2) {

      // 2D case
      final SpotNeighborhood<T> neighborhood = new SpotNeighborhood<T>(spot, img);
      final SpotNeighborhoodCursor<T> cursor = neighborhood.cursor();
      double x, y;
      double x2, y2;
      double mass, totalmass = 0;
      double Ixx = 0, Iyy = 0, Ixy = 0;
      final double[] position = new double[img.numDimensions()];

      while (cursor.hasNext()) {
        cursor.fwd();
        mass = cursor.get().getRealDouble();
        cursor.getRelativePosition(position);
        x = position[0];
        y = position[1];
        totalmass += mass;
        x2 = x * x;
        y2 = y * y;
        Ixx += mass * (y2);
        Iyy += mass * (x2);
        Ixy -= mass * x * y;
      }

      final Matrix mat = new Matrix(new double[][] {{Ixx, Ixy}, {Ixy, Iyy}});
      mat.timesEquals(1 / totalmass);
      final EigenvalueDecomposition eigdec = mat.eig();
      final double[] eigenvalues = eigdec.getRealEigenvalues();
      final Matrix eigenvectors = eigdec.getV();

      final double I1 = eigenvalues[0];
      final double I2 = eigenvalues[1];
      final double a = Math.sqrt(4 * I1);
      final double b = Math.sqrt(4 * I2);
      final double[] semiaxes = new double[] {a, b};

      // Sort semi-axes by ascendent order and get the sorting index
      final double[] semiaxes_ordered = semiaxes.clone();
      Arrays.sort(semiaxes_ordered);
      final int[] order = new int[2];
      for (int i = 0; i < semiaxes_ordered.length; i++)
        for (int j = 0; j < semiaxes.length; j++)
          if (semiaxes_ordered[i] == semiaxes[j]) order[i] = j;

      // Get the sorted eigenvalues
      final double[][] uvectors = new double[2][2];
      for (int i = 0; i < eigenvalues.length; i++) {
        uvectors[i][0] = eigenvectors.get(0, order[i]);
        uvectors[i][1] = eigenvectors.get(1, order[i]);
      }

      // Store in the Spot object
      double theta, phi;
      for (int i = 0; i < uvectors.length; i++) {
        theta = 0;
        phi = Math.atan2(uvectors[i][1], uvectors[i][0]);
        if (phi < -Math.PI / 2) phi += Math.PI; // For an ellipsoid we care only for the
        // angles in [-pi/2 , pi/2]
        if (phi > Math.PI / 2) phi -= Math.PI;

        // Store in descending order
        spot.putFeature(featurelist_sa[i], semiaxes_ordered[i]);
        spot.putFeature(featurelist_phi[i], phi);
        spot.putFeature(featurelist_theta[i], theta);
      }
      spot.putFeature(featurelist_sa[2], Double.valueOf(0));
      spot.putFeature(featurelist_phi[2], Double.valueOf(0));
      spot.putFeature(featurelist_theta[2], Double.valueOf(0));

      // Store the Spot morphology (needs to be outside the above loop)
      spot.putFeature(MORPHOLOGY, estimateMorphology(semiaxes_ordered));
    }
  }
  public Object calculate(GraphModel g) {
    ZagrebIndexFunctions zif = new ZagrebIndexFunctions(g);
    RenderTable ret = new RenderTable();
    Vector<String> titles = new Vector<>();
    titles.add(" E(G) ");
    titles.add(" 1.1 ");
    titles.add(" 1.2 ");
    titles.add(" 1.3 ");
    titles.add(" 1.4 ");
    titles.add(" 1.5 ");
    titles.add(" 1.6 ");
    titles.add(" 1.7 ");
    titles.add(" Eigenvalues ");
    titles.add(" 2-degree sum ");
    titles.add("new query");
    ret.setTitles(titles);

    Matrix A = g.getWeightedAdjacencyMatrix();
    EigenvalueDecomposition ed = A.eig();
    double rv[] = ed.getRealEigenvalues();
    double sum = 0;
    double detA = Math.abs(A.det());

    // positiv RV
    Double[] prv = new Double[rv.length];
    for (int i = 0; i < rv.length; i++) {
      prv[i] = Math.abs(rv[i]);
      prv[i] = (double) Math.round(prv[i] * 100000d) / 100000d;
      sum += prv[i];
    }

    Arrays.sort(prv, Collections.reverseOrder());

    double maxDeg = 0;
    double maxDeg2 = 0;
    double minDeg = Integer.MAX_VALUE;

    ArrayList<Integer> al = AlgorithmUtils.getDegreesList(g);
    Collections.sort(al);
    maxDeg = al.get(al.size() - 1);
    if (al.size() - 2 >= 0) maxDeg2 = al.get(al.size() - 2);
    else maxDeg2 = maxDeg;
    minDeg = al.get(0);

    if (maxDeg2 == 0) maxDeg2 = maxDeg;

    double a = 0;
    double b = 0;

    for (Vertex v : g) {
      if (g.getDegree(v) == maxDeg) a++;
      if (g.getDegree(v) == minDeg) b++;
    }
    if (maxDeg == minDeg) b = 0;

    double m = g.getEdgesCount();
    double n = g.getVerticesCount();

    double M12 = zif.getSecondZagreb(1);
    double M21 = zif.getFirstZagreb(1);
    double M22 = zif.getSecondZagreb(2);
    double Mm11 = zif.getFirstZagreb(-2);

    Vector<Object> v = new Vector<>();
    v.add(sum);
    // 1
    v.add(Math.sqrt(2 * m));
    // 2
    v.add(
        (2 * Math.sqrt(2 * m * n) * Math.sqrt(prv[0] * prv[prv.length - 1]))
            / (prv[0] + prv[prv.length - 1]));
    // 3
    v.add((prv[0] * prv[prv.length - 1] * n + 2 * m) / (prv[0] + prv[prv.length - 1]));
    // 4
    v.add(Math.sqrt(2 * m * n - (Math.pow(n * (prv[0] - prv[prv.length - 1]), 2) / 4)));
    // 5
    double alpha = n * Math.floor(n / 2) * (1 - (1 / n) * Math.floor(n / 2));
    v.add(Math.sqrt(2 * m * n - (Math.pow((prv[0] - prv[prv.length - 1]), 2) * alpha)));
    // 6
    if (detA == 0) v.add(0);
    else v.add(Math.sqrt(2 * m + n * (n - 1) * Math.pow(detA, 2 / n)));

    // 7
    double up = n * Math.pow(prv[0] - prv[prv.length - 1], 2);
    double down = 4 * (prv[0] + prv[prv.length - 1]);
    v.add(Math.sqrt(2 * m * n) - (up / down));

    // eigenvalues
    v.add(getEigenValues(g));

    // 2-degree sum
    v.add(Utils.getDegreeSum(g, 1));

    // new query
    double eigenVal_k = prv[prv.length - 1];
    int cnt = prv.length - 1;

    if (eigenVal_k == 0) {
      while (eigenVal_k == 0) {
        eigenVal_k = prv[--cnt];
      }
    }

    int numOfNZEigenValue = 0;
    for (int i = 0; i < prv.length; i++) {
      if (prv[i] != 0) numOfNZEigenValue++;
    }

    double alpha_k =
        numOfNZEigenValue
            * Math.floor(numOfNZEigenValue / 2)
            * (1 - (1 / numOfNZEigenValue) * Math.floor(numOfNZEigenValue / 2));
    System.out.println(alpha_k + "  " + numOfNZEigenValue);
    System.out.println(prv[0] + "  " + eigenVal_k);
    v.add(Math.sqrt(2 * m * numOfNZEigenValue - (Math.pow((prv[0] - eigenVal_k), 2) * alpha_k)));

    ret.add(v);
    return ret;
  }
  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");
  }
  @Override
  public void run() {
    amIActive = true;

    String shapefile = null;
    String inputFieldsString = null;
    String[] fieldNames = null;
    double z;
    int numFields;
    int progress = 0;
    int lastProgress = 0;
    int row;
    int a, i, j;
    double[] fieldAverages;
    double[] fieldTotals;
    boolean standardizedPCA = false;
    int numberOfComponentsOutput = 0;

    if (args.length <= 0) {
      showFeedback("Plugin parameters have not been set.");
      return;
    }

    // read the input parameters

    inputFieldsString = args[0];
    standardizedPCA = Boolean.parseBoolean(args[1]);
    if (args[2].toLowerCase().contains("not")) { // not specified
      numberOfComponentsOutput = 0;
    } else {
      numberOfComponentsOutput = Integer.parseInt(args[2]);
    }

    try {
      // deal with the input fields
      String[] inputs = inputFieldsString.split(";");
      shapefile = inputs[0];
      numFields = inputs.length - 1;
      fieldNames = new String[numFields];
      System.arraycopy(inputs, 1, fieldNames, 0, numFields);

      // read the appropriate field from the dbf file into an array
      AttributeTable table = new AttributeTable(shapefile.replace(".shp", ".dbf"));
      int numRecs = table.getNumberOfRecords();
      DBFField[] fields = table.getAllFields();
      ArrayList<Integer> PCAFields = new ArrayList<>();
      for (j = 0; j < fieldNames.length; j++) {
        for (i = 0; i < fields.length; i++) {
          if (fields[i].getName().equals(fieldNames[j])
              && (fields[i].getDataType() == DBFField.DBFDataType.NUMERIC
                  || fields[i].getDataType() == DBFField.DBFDataType.FLOAT)) {
            PCAFields.add(i);
          }
        }
      }

      if (numFields != PCAFields.size()) {
        showFeedback(
            "Not all of the specified database fields were found in the file or "
                + "a field of a non-numerical type was selected.");
        return;
      }

      double[][] fieldArray = new double[numRecs][numFields];
      Object[] rec;
      for (i = 0; i < numRecs; i++) {
        rec = table.getRecord(i);
        for (j = 0; j < numFields; j++) {
          fieldArray[i][j] = (Double) (rec[PCAFields.get(j)]);
        }
        if (cancelOp) {
          cancelOperation();
          return;
        }
        progress = (int) (100f * i / (numRecs - 1));
        if (progress != lastProgress) {
          updateProgress("Reading data:", progress);
        }
        lastProgress = progress;
      }

      fieldAverages = new double[numFields];
      fieldTotals = new double[numFields];

      // Calculate the means
      for (row = 0; row < numRecs; row++) {
        for (i = 0; i < numFields; i++) {
          fieldTotals[i] += fieldArray[row][i];
        }
      }

      for (i = 0; i < numFields; i++) {
        fieldAverages[i] = fieldTotals[i] / numRecs;
      }

      // Calculate the covariance matrix and total deviations
      double[] fieldTotalDeviation = new double[numFields];
      double[][] covariances = new double[numFields][numFields];
      double[][] correlationMatrix = new double[numFields][numFields];

      for (row = 0; row < numRecs; row++) {
        for (i = 0; i < numFields; i++) {
          fieldTotalDeviation[i] +=
              (fieldArray[row][i] - fieldAverages[i]) * (fieldArray[row][i] - fieldAverages[i]);
          for (a = 0; a < numFields; a++) {
            covariances[i][a] +=
                (fieldArray[row][i] - fieldAverages[i]) * (fieldArray[row][a] - fieldAverages[a]);
          }
        }
        if (cancelOp) {
          cancelOperation();
          return;
        }
        progress = (int) (100f * row / (numRecs - 1));
        if (progress != lastProgress) {
          updateProgress("Calculating covariances:", progress);
        }
        lastProgress = progress;
      }

      for (i = 0; i < numFields; i++) {
        for (a = 0; a < numFields; a++) {
          correlationMatrix[i][a] =
              covariances[i][a] / (Math.sqrt(fieldTotalDeviation[i] * fieldTotalDeviation[a]));
        }
      }

      for (i = 0; i < numFields; i++) {
        for (a = 0; a < numFields; a++) {
          covariances[i][a] = covariances[i][a] / (numRecs - 1);
        }
      }

      // Calculate the eigenvalues and eigenvectors
      Matrix cov = null;
      if (!standardizedPCA) {
        cov = new Matrix(covariances);
      } else {
        cov = new Matrix(correlationMatrix);
      }
      EigenvalueDecomposition eigen = cov.eig();
      double[] eigenvalues;
      Matrix eigenvectors;
      SortedSet<PrincipalComponent> principalComponents;
      eigenvalues = eigen.getRealEigenvalues();
      eigenvectors = eigen.getV();

      double[][] vecs = eigenvectors.getArray();
      int numComponents = eigenvectors.getColumnDimension(); // same as num rows.
      principalComponents = new TreeSet<PrincipalComponent>();
      for (i = 0; i < numComponents; i++) {
        double[] eigenvector = new double[numComponents];
        for (j = 0; j < numComponents; j++) {
          eigenvector[j] = vecs[j][i];
        }
        principalComponents.add(new PrincipalComponent(eigenvalues[i], eigenvector));
      }

      double totalEigenvalue = 0;
      for (i = 0; i < numComponents; i++) {
        totalEigenvalue += eigenvalues[i];
      }

      double[][] explainedVarianceArray = new double[numComponents][2]; // percent and cum. percent
      j = 0;
      for (PrincipalComponent pc : principalComponents) {
        explainedVarianceArray[j][0] = pc.eigenValue / totalEigenvalue * 100.0;
        if (j == 0) {
          explainedVarianceArray[j][1] = explainedVarianceArray[j][0];
        } else {
          explainedVarianceArray[j][1] =
              explainedVarianceArray[j][0] + explainedVarianceArray[j - 1][1];
        }
        j++;
      }

      DecimalFormat df1 = new DecimalFormat("0.00");
      DecimalFormat df2 = new DecimalFormat("0.0000");
      DecimalFormat df3 = new DecimalFormat("0.000000");
      DecimalFormat df4 = new DecimalFormat("0.000");
      String ret = "Principal Component Analysis Report:\n\n";
      ret += "Component\tExplained Var.\tCum. %\tEigenvalue\tEigenvector\n";
      j = 0;
      for (PrincipalComponent pc : principalComponents) {

        String explainedVariance = df1.format(explainedVarianceArray[j][0]);
        String explainedCumVariance = df1.format(explainedVarianceArray[j][1]);
        double[] eigenvector = pc.eigenVector.clone();
        ret +=
            (j + 1)
                + "\t"
                + explainedVariance
                + "\t"
                + explainedCumVariance
                + "\t"
                + df2.format(pc.eigenValue)
                + "\t";
        String eigenvec = "[";
        for (i = 0; i < numComponents; i++) {
          if (i < numComponents - 1) {
            eigenvec += df3.format(eigenvector[i]) + ", ";
          } else {
            eigenvec += df3.format(eigenvector[i]);
          }
        }
        eigenvec += "]";
        ret += eigenvec + "\n";

        if (j < numberOfComponentsOutput) {
          DBFField field = new DBFField();
          field = new DBFField();
          field.setName("COMP" + (j + 1));
          field.setDataType(DBFField.DBFDataType.NUMERIC);
          field.setFieldLength(10);
          field.setDecimalCount(4);
          table.addField(field);

          for (row = 0; row < numRecs; row++) {
            z = 0;
            for (i = 0; i < numFields; i++) {
              z += fieldArray[row][i] * eigenvector[i];
            }

            Object[] recData = table.getRecord(row);
            recData[recData.length - 1] = new Double(z);
            table.updateRecord(row, recData);

            if (cancelOp) {
              cancelOperation();
              return;
            }
            progress = (int) (100f * row / (numRecs - 1));
            if (progress != lastProgress) {
              updateProgress("Outputing Component " + (j + 1) + ":", progress);
            }
            lastProgress = progress;
          }
        }
        j++;
      }

      // calculate the factor loadings.
      ret += "\nFactor Loadings:\n";
      ret += "\t\tComponent\n\t";
      for (i = 0; i < numComponents; i++) {
        ret += (i + 1) + "\t";
      }
      ret += "\n";
      double loading = 0;
      if (!standardizedPCA) {
        for (i = 0; i < numFields; i++) {
          ret += "field " + (i + 1) + "\t";
          for (PrincipalComponent pc : principalComponents) {
            double[] eigenvector = pc.eigenVector.clone();
            double ev = pc.eigenValue;
            loading = (eigenvector[i] * Math.sqrt(ev)) / Math.sqrt(covariances[i][i]);
            ret += df4.format(loading) + "\t";
          }
          ret += "\n";
        }
      } else {
        for (i = 0; i < numFields; i++) {
          ret += "field " + (i + 1) + "\t";
          for (PrincipalComponent pc : principalComponents) {
            double[] eigenvector = pc.eigenVector.clone();
            double ev = pc.eigenValue;
            loading = (eigenvector[i] * Math.sqrt(ev));
            ret += df4.format(loading) + "\t";
          }
          ret += "\n";
        }
      }

      ret += "\n";
      for (i = 0; i < numFields; i++) {
        ret += "field " + (i + 1) + "\t" + fieldNames[i] + "\n";
      }

      returnData(ret);

      if (numberOfComponentsOutput > 0) {
        returnData(table.getFileName());
      }

      ScreePlot plot = new ScreePlot(explainedVarianceArray);
      returnData(plot);

    } catch (OutOfMemoryError oe) {
      myHost.showFeedback("An out-of-memory error has occurred during operation.");
    } catch (Exception e) {
      myHost.showFeedback("An error has occurred during operation. See log file for details.");
      myHost.logException("Error in " + getDescriptiveName(), e);
    } finally {
      updateProgress("Progress: ", 0);
      // tells the main application that this process is completed.
      amIActive = false;
      myHost.pluginComplete();
    }
  }
示例#11
0
  /**
   * Calculates the 3 MI's, 3 ration and the R_gyr value.
   *
   * <p>The molecule should have hydrogens
   *
   * @param container Parameter is the atom container.
   * @return An ArrayList containing 7 elements in the order described above
   */
  @TestMethod("testCalculate_IAtomContainer")
  public DescriptorValue calculate(IAtomContainer container) {
    if (!GeometryTools.has3DCoordinates(container))
      return getDummyDescriptorValue(new CDKException("Molecule must have 3D coordinates"));

    IAtomContainer clone;
    IsotopeFactory factory;
    try {
      clone = (IAtomContainer) container.clone();
      factory = IsotopeFactory.getInstance(container.getBuilder());
      factory.configureAtoms(clone);
    } catch (Exception e) {
      logger.debug(e);
      return getDummyDescriptorValue(e);
    }

    DoubleArrayResult retval = new DoubleArrayResult(7);

    double ccf = 1.000138;
    double eps = 1e-5;

    double[][] imat = new double[3][3];
    Point3d centerOfMass = GeometryTools.get3DCentreOfMass(clone);

    double xdif;
    double ydif;
    double zdif;
    double xsq;
    double ysq;
    double zsq;
    for (int i = 0; i < clone.getAtomCount(); i++) {
      IAtom currentAtom = clone.getAtom(i);

      double mass = factory.getMajorIsotope(currentAtom.getSymbol()).getExactMass();

      xdif = currentAtom.getPoint3d().x - centerOfMass.x;
      ydif = currentAtom.getPoint3d().y - centerOfMass.y;
      zdif = currentAtom.getPoint3d().z - centerOfMass.z;
      xsq = xdif * xdif;
      ysq = ydif * ydif;
      zsq = zdif * zdif;

      imat[0][0] += mass * (ysq + zsq);
      imat[1][1] += mass * (xsq + zsq);
      imat[2][2] += mass * (xsq + ysq);

      imat[1][0] += -1 * mass * ydif * xdif;
      imat[0][1] = imat[1][0];

      imat[2][0] += -1 * mass * xdif * zdif;
      imat[0][2] = imat[2][0];

      imat[2][1] += -1 * mass * ydif * zdif;
      imat[1][2] = imat[2][1];
    }

    // diagonalize the MI tensor
    Matrix tmp = new Matrix(imat);
    EigenvalueDecomposition eigenDecomp = tmp.eig();
    double[] eval = eigenDecomp.getRealEigenvalues();

    retval.add(eval[2]);
    retval.add(eval[1]);
    retval.add(eval[0]);

    double etmp = eval[0];
    eval[0] = eval[2];
    eval[2] = etmp;

    if (Math.abs(eval[1]) > 1e-3) retval.add(eval[0] / eval[1]);
    else retval.add(1000);

    if (Math.abs(eval[2]) > 1e-3) {
      retval.add(eval[0] / eval[2]);
      retval.add(eval[1] / eval[2]);
    } else {
      retval.add(1000);
      retval.add(1000);
    }

    // finally get the radius of gyration
    double pri;
    IMolecularFormula formula = MolecularFormulaManipulator.getMolecularFormula(clone);
    if (Math.abs(eval[2]) > eps) pri = Math.pow(eval[0] * eval[1] * eval[2], 1.0 / 3.0);
    else pri = Math.sqrt(eval[0] * ccf / MolecularFormulaManipulator.getTotalExactMass(formula));
    retval.add(
        Math.sqrt(
            Math.PI * 2 * pri * ccf / MolecularFormulaManipulator.getTotalExactMass(formula)));

    return new DescriptorValue(
        getSpecification(), getParameterNames(), getParameters(), retval, getDescriptorNames());
  }
示例#12
0
  private double generalizedCorrelationRatio(SampleIterator it, int inputDim, int out) {
    Map<Double, Integer> n_y = new HashMap<>();
    Map<Double, MultivariateSummaryStatistics> stat_y = new HashMap<>();
    List<RealMatrix> x = new ArrayList<>();
    MultivariateSummaryStatistics stat = new MultivariateSummaryStatistics(inputDim, unbiased);

    for (int i = 0; i < maxSamples && it.hasNext(); i++) {
      Sample sample = it.next();
      double[] input = sample.getEncodedInput().toArray();
      double output = sample.getEncodedOutput().getEntry(out);
      if (!n_y.containsKey(output)) {
        n_y.put(output, 0);
        stat_y.put(output, new MultivariateSummaryStatistics(inputDim, unbiased));
      }

      injectNoise(input);
      n_y.put(output, n_y.get(output) + 1);
      stat_y.get(output).addValue(input);
      x.add(new Array2DRowRealMatrix(input));
      stat.addValue(input);
    }

    RealMatrix x_sum = new Array2DRowRealMatrix(stat.getSum());
    Map<Double, RealMatrix> x_y_sum = new HashMap<>();
    for (Entry<Double, MultivariateSummaryStatistics> entry : stat_y.entrySet()) {
      x_y_sum.put(entry.getKey(), new Array2DRowRealMatrix(entry.getValue().getSum()));
    }

    RealMatrix H = new Array2DRowRealMatrix(inputDim, inputDim);
    RealMatrix temp = new Array2DRowRealMatrix(inputDim, inputDim);

    for (double key : n_y.keySet()) {
      temp =
          temp.add(
              x_y_sum
                  .get(key)
                  .multiply(x_y_sum.get(key).transpose())
                  .scalarMultiply(1.0 / n_y.get(key)));
    }
    H = temp.subtract(x_sum.multiply(x_sum.transpose()).scalarMultiply(1.0 / x.size()));

    RealMatrix E = new Array2DRowRealMatrix(inputDim, inputDim);
    for (RealMatrix m : x) {
      E = E.add(m.multiply(m.transpose()));
    }
    E = E.subtract(temp);

    List<Integer> zeroColumns = findZeroColumns(E);
    E = removeZeroColumns(E, zeroColumns);
    H = removeZeroColumns(H, zeroColumns);

    Matrix JE = new Matrix(E.getData());
    Matrix JH = new Matrix(H.getData());

    if (JE.rank() < JE.getRowDimension()) {
      Log.write(this, "Some error occurred (E matrix is singular)");
      return -1;
    } else {
      double lambda;
      if (useEigenvalues) {
        Matrix L = JE.inverse().times(JH);
        double[] eigs = L.eig().getRealEigenvalues();
        Arrays.sort(eigs);

        lambda = 1;
        int nonNullEigs = n_y.keySet().size() - 1;
        for (int i = eigs.length - nonNullEigs; i < eigs.length; i++) {
          if (Math.abs(eigs[i]) < zeroThreshold) {
            Log.write(this, "Some error occurred (E matrix has too many null eigenvalues)");
            return -1;
          }
          lambda *= 1.0 / (1.0 + eigs[i]);
        }
      } else {
        Matrix sum = JE.plus(JH);
        if (sum.rank() < sum.getRowDimension()) {
          Log.write(this, "Some error occourred (E+H is singular");
          return -1;
        }
        lambda = JE.det() / sum.det();
      }

      return Math.sqrt(1 - lambda);
    }
  }
示例#13
0
  public boolean calcNearPD(Matrix x) {

    int n = x.getRowDimension();
    Matrix X;
    // Init local variables
    double[] diagX0 = new double[n];
    double[] d = new double[n];
    Matrix D_S = new Matrix(n, n);
    Matrix R = new Matrix(n, n);
    Matrix Y = new Matrix(n, n);
    EigenvalueDecomposition eig;
    Matrix D_plus = new Matrix(n, n);
    Matrix Q = new Matrix(n, n);

    if (keepDiag) {
      for (int i = 0; i < n; i++) {
        diagX0[i] = x.get(i, i);
      }
    }

    X = x.copy();

    // Set iteration, convergence criteria
    int iter = 0;
    boolean converged = false;
    double conv = Double.POSITIVE_INFINITY;
    // Loop
    while ((iter < maxit) & !converged) {
      Y = X.copy();

      // Dykstra correction
      if (doDykstra) {
        R = Y.minus(D_S);
      }

      // project onto PSD matrices  X_k  =  P_S (R_k)
      if (doDykstra) {
        eig = R.eig();
      } else {
        eig = Y.eig();
      }
      d = eig.getRealEigenvalues();
      Q = eig.getV();
      // Get the maximum eigenvalue
      double eigMax = Double.NEGATIVE_INFINITY;
      for (int i = 0; i < n; i++) {
        if (d[i] > eigMax) eigMax = d[i];
      }
      // compute the D_plus diagonal matricies
      for (int i = 0; i < n; i++) {
        double d_plus = Math.max(d[i], eigTol * eigMax);
        D_plus.set(i, i, d_plus);
      }

      X = (Q.times(D_plus)).times(Q.transpose());

      // Update Dykstra correction
      if (doDykstra) D_S = X.minus(R);

      // project onto symmetric and possibly 'given diag' matrices:
      if (keepDiag) {
        for (int i = 0; i < n; i++) {
          X.set(i, i, diagX0[i]);
        }
      }

      // update convergence and iteration values
      conv = (Y.minus(X)).normInf() / Y.normInf();
      iter = iter + 1;

      // check convergence criteria
      if (conv <= convTol) converged = true;
    }

    // Set solution local variables as globals
    this.X = X;
    this.conv = conv;
    this.normF = (x.minus(X)).normF();
    this.iter = iter;
    this.eigVals = d;

    return converged;
  }
示例#14
0
  /**
   * This method tests the NearPD class for a approx correlation matrix. This test has been
   * implemented in Matlab for verification
   *
   * @param args
   */
  public static void main(String[] args) {

    //		int n=11;
    int n = 10;
    //		int n=17;
    double[][] rho = new double[n][n];

    //		String rhoString=
    //	      "1.0000      0.9459      0.8018      0.6580      0.5526      0.4665      0.3909
    // 0.3200      0.2486      0.1682     -0.0946     -0.1157     -0.1355      0.9652      0.2520
    //   0.8299      0.5164 " +
    //	      "0.9459      1.0000      0.7642      0.6108      0.5027      0.4173      0.3446
    // 0.2785      0.2139      0.1432     -0.1256     -0.1358     -0.1252      0.9446      0.3705
    //   0.8809      0.5569 " +
    //	      "0.8018      0.7642      1.0000      0.8139      0.6787      0.5695      0.4745
    // 0.3865      0.2989      0.2014     -0.1337     -0.1508     -0.1513      0.8722      0.2323
    //   0.9336      0.4744 " +
    //	      "0.6580      0.6108      0.8139      1.0000      0.8398      0.7086      0.5931
    // 0.4850      0.3764      0.2543     -0.1279     -0.1470     -0.1526      0.7762      0.2969
    //   0.9358      0.4703 " +
    //	      "0.5526      0.5027      0.6787      0.8398      1.0000      0.8465      0.7105
    // 0.5823      0.4529      0.3066     -0.1182     -0.1372     -0.1452      0.6840      0.4004
    //   0.8400      0.4664 " +
    //	      "0.4665      0.4173      0.5695      0.7086      0.8465      1.0000      0.8409
    // 0.6903      0.5376      0.3643     -0.1069     -0.1249     -0.1337      0.5948      0.4537
    //   0.7401      0.4421 " +
    //	      "0.3909      0.3446      0.4745      0.5931      0.7105      0.8409      1.0000
    // 0.8219      0.6407      0.4346     -0.0944     -0.1109     -0.1197      0.5070      0.4544
    //   0.6354      0.4050 " +
    //	      "0.3200      0.2785      0.3865      0.4850      0.5823      0.6903      0.8219
    // 1.0000      0.7802      0.5296     -0.0807     -0.0951     -0.1033      0.4188      0.4166
    //   0.5261      0.3618 " +
    //	      "0.2486      0.2139      0.2989      0.3764      0.4529      0.5376      0.6407
    // 0.7802      1.0000      0.6792     -0.0650     -0.0768     -0.0839      0.3265      0.3494
    //   0.4097      0.2997 " +
    //	      "0.1682      0.1432      0.2014      0.2543      0.3066      0.3643      0.4346
    // 0.5296      0.6792      1.0000     -0.0453     -0.0537     -0.0589      0.2207      0.2495
    //   0.2760      0.2086 " +
    //	     "-0.0946     -0.1256     -0.1337     -0.1279     -0.1182     -0.1069     -0.0944
    // -0.0807     -0.0650     -0.0453      1.0000      0.7538      0.5695     -0.0437      0.7922
    //   -0.0830      0.4212 " +
    //	     "-0.1157     -0.1358     -0.1508     -0.1470     -0.1372     -0.1249     -0.1109
    // -0.0951     -0.0768     -0.0537      0.7538      1.0000      0.7648     -0.0076      0.8310
    //   -0.0258      0.5696 " +
    //	     "-0.1355     -0.1252     -0.1513     -0.1526     -0.1452     -0.1337     -0.1197
    // -0.1033     -0.0839     -0.0589      0.5695      0.7648      1.0000      0.0581      0.8930
    //    0.0665      0.6871 " +
    //	      "0.9652      0.9446      0.8722      0.7762      0.6840      0.5948      0.5070
    // 0.4188      0.3265      0.2207     -0.0437     -0.0076      0.0581      1.0000      0.2931
    //   0.8956      0.5861 " +
    //	      "0.2520      0.3705      0.2323      0.2969      0.4004      0.4537      0.4544
    // 0.4166      0.3494      0.2495      0.7922      0.8310      0.8930      0.2931      1.0000
    //   0.3191      0.6704 " +
    //	      "0.8299      0.8809      0.9336      0.9358      0.8400      0.7401      0.6354
    // 0.5261      0.4097      0.2760     -0.0830     -0.0258      0.0665      0.8956      0.3191
    //   1.0000      0.5372 " +
    //	      "0.5164      0.5569      0.4744      0.4703      0.4664      0.4421      0.4050
    // 0.3618      0.2997      0.2086      0.4212      0.5696      0.6871      0.5861      0.6704
    //   0.5372      1.0000";
    String rhoString =
        "1.0000      0.8646      0.5412     -0.0070     -0.4291     -0.2727      0.5448      0.4981     -0.4579     -0.4481 "
            + "0.8646      1.0000      0.5343     -0.0141     -0.4832     -0.4705      0.4392      0.4716     -0.3771     -0.3660 "
            + "0.5412      0.5343      1.0000      0.0427     -0.7999     -0.8240      0.2005      0.1926     -0.2985     -0.2684 "
            + "-0.0070     -0.0141      0.0427      1.0000     -0.4071     -0.8087     -0.1396     -0.1775     -0.0304     -0.0340 "
            + "-0.4291     -0.4832     -0.7999     -0.4071      1.0000      0.0594     -0.1627     -0.2604      0.2474      0.2541 "
            + "-0.2727     -0.4705     -0.8240     -0.8087      0.0594      1.0000      0.2672      0.0173      0.3205      0.3749 "
            + "0.5448      0.4392      0.2005     -0.1396     -0.1627      0.2672      1.0000      0.2581     -0.3109     -0.3051 "
            + "0.4981      0.4716      0.1926     -0.1775     -0.2604      0.0173      0.2581      1.0000      0.2289      0.2408 "
            + "-0.4579     -0.3771     -0.2985     -0.0304      0.2474      0.3205     -0.3109      0.2289      1.0000      0.8425 "
            + "-0.4481     -0.3660     -0.2684     -0.0340      0.2541      0.3749     -0.3051      0.2408      0.8425      1.0000";

    //		String rhoString=" 1.000 0.399 0.426 0.484 0.585 0.713 0.822 0.887 0.918 0.929 0.897 " +
    //				      "0.399 1.000 0.911 0.791 0.675 0.563 0.458 0.360 0.272 0.195 0.129 " +
    //				      "0.426 0.911 1.000 0.878 0.759 0.643 0.532 0.428 0.332 0.247 0.173 " +
    //				      "0.484 0.791 0.878 1.000 0.878 0.759 0.643 0.532 0.428 0.332 0.247 " +
    //				      "0.585 0.675 0.759 0.878 1.000 0.878 0.759 0.643 0.532 0.428 0.332 " +
    //				      "0.713 0.563 0.643 0.759 0.878 1.000 0.878 0.759 0.643 0.532 0.428 " +
    //				      "0.822 0.458 0.532 0.643 0.759 0.878 1.000 0.878 0.759 0.643 0.532 " +
    //				      "0.887 0.360 0.428 0.532 0.643 0.759 0.878 1.000 0.878 0.759 0.643 " +
    //				      "0.918 0.272 0.332 0.428 0.532 0.643 0.759 0.878 1.000 0.878 0.759 " +
    //				      "0.929 0.195 0.247 0.332 0.428 0.532 0.643 0.759 0.878 1.000 0.878 " +
    //				      "0.897 0.129 0.173 0.247 0.332 0.428 0.532 0.643 0.759 0.878 1.000";
    // Create string tokenizer
    StringTokenizer st = new StringTokenizer(rhoString);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        rho[i][j] = Double.parseDouble(st.nextToken().trim());
      }
    }

    Matrix rho_matrix = new Matrix(rho);
    //		CholeskyDecomposition chol = rho_matrix.chol();
    CholeskyDecomposition chol = new CholeskyDecomposition(rho_matrix);
    if (!chol.isSPD()) System.out.println("The rho matrix is not SPD");

    // Get the eigen values for this matrix
    EigenvalueDecomposition eig = rho_matrix.eig();
    String eigValsString = "";
    double[] eigVals = eig.getRealEigenvalues();
    for (int i = 0; i < n; i++)
      eigValsString = eigValsString + " " + Math.round(eigVals[i] * 1000) / 1000.;
    System.out.println("The eigVals are: " + eigValsString);

    NearPD nearPd = new NearPD();
    nearPd.setKeepDiag(true);
    nearPd.calcNearPD(rho_matrix);
    Matrix rho_PDmatrix = nearPd.getX();

    String rhoPDString_Matlab =
        "1.0000    0.3944    0.4262    0.4865    0.5863    0.7108    0.8179    0.8836    0.9155    0.9246    0.8882 "
            + "0.3944    1.0000    0.9110    0.7905    0.6747    0.5635    0.4589    0.3607    0.2725    0.1959    0.1308 "
            + "0.4262    0.9110    1.0000    0.8780    0.7590    0.6430    0.5320    0.4280    0.3320    0.2470    0.1729 "
            + "0.4865    0.7905    0.8780    1.0000    0.8782    0.7588    0.6425    0.5316    0.4277    0.3315    0.2460 "
            + "0.5863    0.6747    0.7590    0.8782    1.0000    0.8779    0.7587    0.6428    0.5318    0.4277    0.3315 "
            + "0.7108    0.5635    0.6430    0.7588    0.8779    1.0000    0.8784    0.7593    0.6432    0.5324    0.4289 "
            + "0.8179    0.4589    0.5320    0.6425    0.7587    0.8784    1.0000    0.8787    0.7595    0.6438    0.5337 "
            + "0.8836    0.3607    0.4280    0.5316    0.6428    0.7593    0.8787    1.0000    0.8784    0.7597    0.6444 "
            + "0.9155    0.2725    0.3320    0.4277    0.5318    0.6432    0.7595    0.8784    1.0000    0.8785    0.7600 "
            + "0.9246    0.1959    0.2470    0.3315    0.4277    0.5324    0.6438    0.7597    0.8785    1.0000    0.8798 "
            + "0.8882    0.1308    0.1729    0.2460    0.3315    0.4289    0.5337    0.6444    0.7600    0.8798    1.0000";

    // Output the PD matrix and the convergence parameters
    System.out.println("Testing NearPD: nearest PD matrix \n " + "Rho_PD = \n");
    rho_PDmatrix.print(12, 8);
    CholeskyDecomposition cholDecompPD = new CholeskyDecomposition(rho_PDmatrix);
    if (!cholDecompPD.isSPD()) {
      throw new RuntimeException("Error: Even after NearPD the matrix is not PD");
    }
  }