Beispiel #1
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);
 }
  /**
   * Update the covariance Matrix of the weight posterior distribution (SIGMA) along with its
   * cholesky factor:
   *
   * <p>SIGMA = (A + beta * PHI^t * PHI)^{-1}
   *
   * <p>SIGMA_chol with SIGMA_chol * SIGMA_chol^t = SIGMA
   */
  protected void updateSIGMA() {

    Matrix SIGMA_inv = PHI_t.times(PHI_t.transpose());
    SIGMA_inv.timesEquals(beta);
    SIGMA_inv.plusEquals(A);

    /** Update the factor ... */
    SECholeskyDecomposition CD = new SECholeskyDecomposition(SIGMA_inv.getArray());
    Matrix U = CD.getPTR().times(CD.getL());
    SIGMA_chol = U.inverse();

    /** Update SIGMA */
    SIGMA = (SIGMA_chol.transpose()).times(SIGMA_chol);
  }
  /**
   * Computes the pseudo-inverse of a matrix using Singular Value Decomposition
   *
   * @param M - the input {@link Matrix}
   * @param threshold - the threshold for inverting diagonal elements (suggested 0.001)
   * @return the inverted {@link Matrix} or an approximation with lowest possible squared error
   */
  public static final Matrix computePseudoInverseMatrix(final Matrix M, final double threshold) {
    final SingularValueDecomposition svd = new SingularValueDecomposition(M);

    Matrix U = svd.getU(); // U Left Matrix
    final Matrix S = svd.getS(); // W
    final Matrix V = svd.getV(); // VT Right Matrix

    double temp;

    // invert S
    for (int j = 0; j < S.getRowDimension(); ++j) {
      temp = S.get(j, j);

      if (temp < threshold) // this is an inaccurate inverting of the matrix
      temp = 1.0 / threshold;
      else temp = 1.0 / temp;

      S.set(j, j, temp);
    }

    // transponse U
    U = U.transpose();

    //
    // compute result
    //
    return ((V.times(S)).times(U));
  }
Beispiel #4
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();
  }
  public static void main(String[] argarray) {
    CoefArgs args = CoefArgs.parse(argarray);
    try {
      AllMultilevelCoefs coefs = new AllMultilevelCoefs(args);

      Matrix matrix = coefs.matrix(true);
      Matrix covar = matrix.transpose().times(matrix);
      SingularValueDecomposition svd = covar.svd();

      Matrix U = svd.getU();

      double[] d1 = normalize(column(U, 1));
      double[] d2 = normalize(column(U, 2));

      String[] genes = coefs.genes();

      DataFrame<MultilevelCoefs.XYPoint> points =
          new DataFrame<MultilevelCoefs.XYPoint>(MultilevelCoefs.XYPoint.class);

      for (int i = 0; i < genes.length; i++) {
        double[] gr = row(matrix, i);
        double x = inner(gr, d1), y = inner(gr, d2);
        MultilevelCoefs.XYPoint point = new MultilevelCoefs.XYPoint(x, y, genes[i]);
        points.addObject(point);
        System.out.println(point.toString());
      }

      System.out.println("U: ");
      println(U, System.out);

      ModelScatter scatter = new ModelScatter();
      scatter.addModels(points.iterator());

      scatter.setProperty(ModelScatter.colorKey, Coloring.clearer(Color.red));

      coefs.save(
          new File(
              String.format(
                  "C:\\Documents and Settings\\tdanford\\Desktop\\sigma_%s.txt", args.compare)));

      new ModelScatter.InteractiveFrame(scatter, "PCA");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /** Update beta (same as for the "normal" regression rvm) */
  protected void updateBeta() {

    /** Calculate gammas && their sum: gamma_i = 1 - alpha_i * SIGMA_ii */
    double[] gammas = new double[basisSet.size()];
    for (int j = 0; j < basisSet.size(); j++) {
      gammas[j] = 1.0d - alpha[basisSet.get(j)] * SIGMA.get(j, j);
    }

    double sumGammas = 0;
    for (int j = 0; j < gammas.length; j++) {
      sumGammas += gammas[j];
    }

    /** Calculate delta = t - PHI * mu */
    Matrix DELTA = (new Matrix(t)).minus(PHI_t.transpose().times(mu));

    /** beta = N - sum_i(gamma_i) / norm_l2(DELTA)^2 */
    beta = x.length - sumGammas / innerProduct(DELTA.getRowPackedCopy(), DELTA.getRowPackedCopy());
  }
  /* ERROR DETERMINATION */
  private void determineError() {
    double var_est = 1 / ((double) getDegreesOfFreedom()) * sumOfSquares();

    Matrix J = calcJ();
    Matrix JT = J.transpose();
    Matrix err = (JT.times(J)).inverse();
    covar = err.times(var_est);
    param_stdDev = new double[numFittable];
    double[][] matrixVals = new double[numFittable][numFittable];
    for (int i = 0; i < numFittable; i++) {
      param_stdDev[i] = Math.sqrt(covar.get(i, i));
      matrixVals[i][i] = param_stdDev[i];
    }
    for (int i = 0; i < numFittable; i++) {
      for (int j = i; j < numFittable; j++) {
        matrixVals[i][j] = covar.get(i, j) / (matrixVals[i][i] * matrixVals[j][j]);
      }
    }

    corr = new Matrix(matrixVals);
  }
Beispiel #8
0
  /**
   * use the online model to predict the target position given the positions measured at the bpms
   */
  public void performAnalysis(final List<BPM> bpms) throws Exception {
    final int measurementCount = VIEW_SCREEN_MEASUREMENTS.size();
    double meanDifference = 0.0; // TODO: CKA - NEVER USED
    final Matrix diag = new Matrix(measurementCount, 2);
    final Matrix viewScreenMeas = new Matrix(measurementCount, 1);
    final List<TargetAnalysisResultRecord> rawResults =
        new ArrayList<TargetAnalysisResultRecord>(measurementCount);
    int row = 0;
    for (final ViewScreenMeasurement measurement : VIEW_SCREEN_MEASUREMENTS) {
      final TargetAnalysisResultRecord rawResult = predictWithMatcher(bpms, measurement);
      rawResults.add(rawResult);
      final double measuredPosition = rawResult.getMeasuredPosition();
      viewScreenMeas.set(row, 0, measuredPosition);
      diag.set(row, 0, 1.0);
      diag.set(row, 1, rawResult.getPredictedPosition());
      meanDifference += rawResult.getMeasuredPosition() - rawResult.getPredictedPosition();
      ++row;
    }
    meanDifference /= measurementCount;
    final Matrix diagT = diag.transpose();
    final Matrix coef = diagT.times(diag).inverse().times(diagT).times(viewScreenMeas);
    final double offset = coef.get(0, 0);
    final double scale = coef.get(1, 0);

    final List<TargetAnalysisResultRecord> results = new ArrayList<TargetAnalysisResultRecord>();
    double errorSum = 0.0;
    for (final TargetAnalysisResultRecord rawResult : rawResults) {
      final double predictedPosition = scale * rawResult.getPredictedPosition() + offset;
      final double measuredPosition = rawResult.getMeasuredPosition();
      final TargetAnalysisResultRecord result =
          new TargetAnalysisResultRecord(measuredPosition, predictedPosition);
      results.add(result);
      errorSum += (measuredPosition - predictedPosition) * (measuredPosition - predictedPosition);
    }
    final double rmsError = Math.sqrt(errorSum / rawResults.size());

    _scale = scale;
    _offset = offset;
    _rmsError = rmsError;
  }
  /**
   * 输出特征脸 根据特征向量得出Image类型
   *
   * @param args
   */
  public static Image[] getFeatureFaces() {
    double[][] rfVec = Features.getInstance().getResultFeatureVector();
    Matrix mat = new Matrix(rfVec);
    mat = mat.transpose();
    rfVec = mat.getArray();

    Image[] img = new Image[rfVec.length];
    for (int i = 0; i < rfVec.length; i++) {
      System.out.println("i:" + i);
      // 这一步可能会有压缩损失
      // 最好找一个方法,直接从double[]转换成Image

      // 将double[]转换成int[]
      int[][] rfVecInt = new int[rfVec.length][rfVec[0].length];
      //			System.out.println("[" + rfVec.length + "]" + "[" + rfVec[0].length + "]");
      for (int j = 0; j < rfVec[0].length; j++) {

        //				rfVecInt[i][j] = (int)rfVec[i][j];//无四舍五入
        rfVecInt[i][j] =
            Integer.parseInt(new java.text.DecimalFormat("0").format(rfVec[i][j])); // 四舍五入
        //				System.out.print(rfVecInt[i][j] + " ");

        // ----------------整个if语句是测试语句,要删除
        //				if(i==9)
        //				{
        //					System.out.println("Yes!");
        //					rfVecInt[i][j] = Integer.parseInt(new
        // java.text.DecimalFormat("0").format(rfVec[i][j]));//四舍五入
        //				}
        // ----------------以上为测试语句
      }
      System.out.println("i:" + i);
      img[i] = getImgByPixels(width, height, rfVecInt[i]);
      //			System.out.println();
      //			img[i] = getImgByPixels(128, 128, rfVecInt[i]);
    }
    //		System.out.println("img length:" + img.length);

    return img;
  }
  /**
   * Compute the scalars s_m, q_m which are part of the criterium for inclusion / deletion of the
   * given basis m:
   *
   * <p>S_m = beta * phi^t_m * phi_m - beta^2 * phi^t_m * PHI * SIGMA * PHI^t * phi_m Q_m = beta *
   * phi^t_m * t - beta^2 * phi^t_m * PHI * SIGMA * PHI^t * t
   *
   * <p>s_m = alpha_m * S_m / (alpha_m - S_m) q_m = alpha_m * Q_m / (alpha_m - S_m)
   */
  protected void updateCriteriumScalars(int selectedBasis) {

    Matrix SigmaStuff = (PHI_t.transpose()).times(SIGMA.times(PHI_t));

    double S =
        beta * innerProduct(phi[selectedBasis], phi[selectedBasis])
            - beta
                * beta
                * innerProduct(
                    phi[selectedBasis],
                    SigmaStuff.times(new Matrix(phi[selectedBasis], phi[selectedBasis].length))
                        .getRowPackedCopy());

    double Q =
        beta * innerProduct(phi[selectedBasis], tVector)
            - beta
                * beta
                * innerProduct(
                    phi[selectedBasis], SigmaStuff.times(new Matrix(t)).getRowPackedCopy());

    s = alpha[selectedBasis] * S / (alpha[selectedBasis] - S);
    q = alpha[selectedBasis] * Q / (alpha[selectedBasis] - S);
  }
  /** 计算协方差矩阵 传入形参为 <方法:计算每张图片的均差> 的返回值 (其实这并不是协方差矩阵,若需要协方差矩阵,再用该矩阵除以N即可) */
  public static double[][] calCovarianceMatrix(double[][] vec) {
    int length = vec.length; // length指向量的维数,X={1,2,3,...,length}
    int n = vec[0].length; // n指向量的个数,X1,X2,X3...Xn;

    Matrix vecOld = new Matrix(vec);

    //		System.out.println("vecOld:");
    //		vecOld.print(6, 2);

    //		System.out.println();
    Matrix vecTrans = vecOld.transpose(); // 获取转置矩阵
    //		System.out.println("vecTrans:");
    //		vecTrans.print(6, 2);

    double[][] covArr = new double[nOld][nOld]; // 初始化协方差矩阵

    // 构造协方差矩阵
    //		Matrix cov = vecOld.times(vecTrans);
    Matrix cov = vecTrans.times(vecOld);

    covArr = cov.getArray();

    // 由于最终计算并不需要协方差矩阵,仅仅要的是一部分,所以不用除以N
    // 除以N
    //		for(int i=0; i<n; i++)
    //		{
    //			for(int j=0; j<length; j++)
    //			{
    //				covArr[i][j] = covArr[i][j] / n;
    //			}
    //		}

    Features.getInstance().setCovarianceMatrix(covArr);

    return covArr;
  }
 public double defaultHypothesis(Matrix input) throws IllegalArgumentException {
   double z = ((parameter.transpose()).times(input)).get(0, 0);
   return 1 / (1 + exp(-z));
 }
Beispiel #13
0
    private void RunSPKF() {
      // SPKF Steps:
      // 1) Generate Test Points
      // 2) Propagate Test Points
      // 3) Compute Predicted Mean and Covariance
      // 4) Compute Measurements
      // 5) Compute Innovations and Cross Covariance
      // 6) Compute corrections and update

      // Line up initial variables from the controller!
      Double dAlpha = dGreek.get(0);
      Double dBeta = dGreek.get(1);
      cController.setAlpha(dAlpha);
      cController.setBeta(dBeta);
      cController.setKappa(dGreek.get(2));
      Double dGamma = cController.getGamma();
      Double dLambda = cController.getLambda();

      // // DEBUG - Print the Greeks
      // System.out.println("Greeks!");
      // System.out.println("Alpha - " + dAlpha);
      // System.out.println("Beta - " + dBeta);
      // System.out.println("Kappa - " + dGreek.get(2));
      // System.out.println("Lambda - " + dLambda);
      // System.out.println("Gamma - " + dGamma);

      // Let's get started:
      // Step 1: Generate Test Points
      Vector<Matrix> Chi = new Vector<Matrix>();
      Vector<Matrix> UpChi = new Vector<Matrix>();
      Vector<Matrix> UpY = new Vector<Matrix>();
      Matrix UpPx = new Matrix(3, 3, 0.0);
      Matrix UpPy = new Matrix(3, 3, 0.0);
      Matrix UpPxy = new Matrix(3, 3, 0.0);
      Matrix K;
      Vector<Double> wc = new Vector<Double>();
      Vector<Double> wm = new Vector<Double>();
      Chi.add(X); // Add Chi_0 - the current state estimate (X, Y, Z)

      // Big P Matrix is LxL diagonal
      Matrix SqrtP = SqrtSPKF(P);
      SqrtP = SqrtP.times(dGamma);

      // Set up Sigma Points
      for (int i = 0; i <= 8; i++) {
        Matrix tempVec = SqrtP.getMatrix(0, 8, i, i);
        Matrix tempX = X;
        Matrix tempPlus = tempX.plus(tempVec);
        // System.out.println("TempPlus");
        // tempPlus.print(3, 2);
        Matrix tempMinu = tempX.minus(tempVec);
        // System.out.println("TempMinus");
        // tempMinu.print(3, 2);
        // tempX = X.copy();
        // tempX.setMatrix(i, i, 0, 2, tempPlus);
        Chi.add(tempPlus);
        // tempX = X.copy();
        // tempX.setMatrix(i, i, 0, 2, tempMinu);
        Chi.add(tempMinu);
      }

      // DEBUG Print the lines inside the Chi Matrix (2L x L)
      // for (int i = 0; i<=(2*L); i++){
      // System.out.println("Chi Matrix Set: "+i);
      // Chi.get(i).print(5, 2);
      // }

      // Generate weights
      Double WeightZero = (dLambda / (L + dLambda));
      Double OtherWeight = (1 / (2 * (L + dLambda)));
      Double TotalWeight = WeightZero;
      wm.add(WeightZero);
      wc.add(WeightZero + (1 - (dAlpha * dAlpha) + dBeta));
      for (int i = 1; i <= (2 * L); i++) {
        TotalWeight = TotalWeight + OtherWeight;
        wm.add(OtherWeight);
        wc.add(OtherWeight);
      }
      // Weights MUST BE 1 in total
      for (int i = 0; i <= (2 * L); i++) {
        wm.set(i, wm.get(i) / TotalWeight);
        wc.set(i, wc.get(i) / TotalWeight);
      }

      // //DEBUG Print the weights
      // System.out.println("Total Weight:");
      // System.out.println(TotalWeight);
      // for (int i = 0; i<=(2*L); i++){
      // System.out.println("Weight M for "+i+" Entry");
      // System.out.println(wm.get(i));
      // System.out.println("Weight C for "+i+" Entry");
      // System.out.println(wc.get(i));
      // }

      // Step 2: Propagate Test Points
      // This will also handle computing the mean
      Double ux = dControl.elementAt(0);
      Double uy = dControl.elementAt(1);
      Double uz = dControl.elementAt(2);
      Matrix XhatMean = new Matrix(3, 1, 0.0);
      for (int i = 0; i < Chi.size(); i++) {
        Matrix ChiOne = Chi.get(i);
        Matrix Chixminus = new Matrix(3, 1, 0.0);
        Double Xhat = ChiOne.get(0, 0);
        Double Yhat = ChiOne.get(1, 0);
        Double Zhat = ChiOne.get(2, 0);
        Double Xerr = ChiOne.get(3, 0);
        Double Yerr = ChiOne.get(4, 0);
        Double Zerr = ChiOne.get(5, 0);

        Xhat = Xhat + ux + Xerr;
        Yhat = Yhat + uy + Yerr;
        Zhat = Zhat + uz + Zerr;

        Chixminus.set(0, 0, Xhat);
        Chixminus.set(1, 0, Yhat);
        Chixminus.set(2, 0, Zhat);
        // System.out.println("ChixMinus:");
        // Chixminus.print(3, 2);
        UpChi.add(Chixminus);
        XhatMean = XhatMean.plus(Chixminus.times(wm.get(i)));
      }

      // Mean is right!

      // System.out.println("XhatMean: ");
      // XhatMean.print(3, 2);

      // Step 3: Compute Predicted Mean and Covariance
      // Welp, we already solved the mean - let's do the covariance now
      for (int i = 0; i <= (2 * L); i++) {
        Matrix tempP = UpChi.get(i).minus(XhatMean);
        Matrix tempPw = tempP.times(wc.get(i));
        tempP = tempPw.times(tempP.transpose());
        UpPx = UpPx.plus(tempP);
      }

      // New Steps!

      // Step 4: Compute Measurements! (and Y mean!)
      Matrix YhatMean = new Matrix(3, 1, 0.0);
      for (int i = 0; i <= (2 * L); i++) {
        Matrix ChiOne = Chi.get(i);
        Matrix Chiyminus = new Matrix(3, 1, 0.0);
        Double Xhat = UpChi.get(i).get(0, 0);
        Double Yhat = UpChi.get(i).get(1, 0);
        Double Zhat = UpChi.get(i).get(2, 0);
        Double Xerr = ChiOne.get(6, 0);
        Double Yerr = ChiOne.get(7, 0);
        Double Zerr = ChiOne.get(8, 0);

        Xhat = Xhat + Xerr;
        Yhat = Yhat + Yerr;
        Zhat = Zhat + Zerr;

        Chiyminus.set(0, 0, Xhat);
        Chiyminus.set(1, 0, Yhat);
        Chiyminus.set(2, 0, Zhat);
        UpY.add(Chiyminus);
        YhatMean = YhatMean.plus(Chiyminus.times(wm.get(i)));
      }

      // // Welp, we already solved the mean - let's do the covariances
      // now
      // System.out.println("XHatMean and YHatMean = ");
      // XhatMean.print(3, 2);
      // YhatMean.print(3, 2);

      for (int i = 0; i <= (2 * L); i++) {
        Matrix tempPx = UpChi.get(i).minus(XhatMean);
        Matrix tempPy = UpY.get(i).minus(YhatMean);
        // System.out.println("ChiX - XhatMean and ChiY-YhatMean");
        // tempPx.print(3, 2);
        // tempPy.print(3, 2);

        Matrix tempPxw = tempPx.times(wc.get(i));
        Matrix tempPyw = tempPy.times(wc.get(i));

        tempPx = tempPxw.times(tempPy.transpose());
        tempPy = tempPyw.times(tempPy.transpose());
        UpPy = UpPy.plus(tempPy);
        UpPxy = UpPxy.plus(tempPx);
      }

      // Step 6: Compute Corrections and Update

      // Compute Kalman Gain!
      // System.out.println("Updated Px");
      // UpPx.print(5, 2);
      // System.out.println("Updated Py");
      // UpPy.print(5, 2);
      // System.out.println("Updated Pxy");
      // UpPxy.print(5, 2);
      K = UpPxy.times(UpPy.inverse());
      // System.out.println("Kalman");
      // K.print(5, 2);

      Matrix Mea = new Matrix(3, 1, 0.0);
      Mea.set(0, 0, dMeasure.get(0));
      Mea.set(1, 0, dMeasure.get(1));
      Mea.set(2, 0, dMeasure.get(2));

      Matrix Out = K.times(Mea.minus(YhatMean));
      Out = Out.plus(XhatMean);
      // System.out.println("Out:");
      // Out.print(3, 2);

      Matrix Px = UpPx.minus(K.times(UpPy.times(K.transpose())));

      // Update Stuff!
      // Push the P to the controller
      Matrix OutP = P.copy();
      OutP.setMatrix(0, 2, 0, 2, Px);
      X.setMatrix(0, 2, 0, 0, Out);

      Residual = XhatMean.minus(Out);
      cController.inputState(OutP, Residual);
      // cController.setL(L);

      cController.startProcess();
      while (!cController.finishedProcess()) {
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }

      // System.out.println("Post Greeks: " + cController.getAlpha() + " ,
      // "+ cController.getBeta());

      dGreek.set(0, cController.getAlpha());
      dGreek.set(1, cController.getBeta());
      dGreek.set(2, cController.getKappa());
      P = cController.getP();

      // System.out.println("P is post Process:");
      // P.print(3, 2);

      StepDone = true;
    }
  public static void main(String[] args) throws IOException {

    String train_file_name = "150(1000)-100-train.csv",
        test_file_name = "test-1000-100.csv",
        train_data,
        test_data,
        output_file;
    int training_rows = 0, training_cols = 0, testing_rows = 0, testing_cols = 0;

    BufferedReader CSVTrain = new BufferedReader(new FileReader(train_file_name));
    train_data = CSVTrain.readLine();
    BufferedReader CSVTest = new BufferedReader(new FileReader(test_file_name));
    test_data = CSVTest.readLine();

    ArrayList<String[]> train_array_list = new ArrayList<String[]>();
    ArrayList<String[]> test_array_list = new ArrayList<String[]>();

    training_cols = countColumns(train_data, training_cols);
    testing_cols = countColumns(test_data, testing_cols);
    training_rows = readData(CSVTrain, train_array_list, training_rows, training_cols);
    testing_rows = readData(CSVTest, test_array_list, testing_rows, testing_cols);

    double X_train[][] = new double[training_rows][training_cols];
    double Y_train[][] = new double[training_rows][1];
    double X_test[][] = new double[testing_rows][testing_cols];
    double Y_test[][] = new double[testing_rows][1];

    insertX0(training_rows, X_train);
    insertX0(testing_rows, X_test);

    createXYarray(train_array_list, training_cols, X_train, Y_train);
    createXYarray(test_array_list, testing_cols, X_test, Y_test);

    Matrix mx_train = Matrix.constructWithCopy(X_train);
    Matrix my_train = Matrix.constructWithCopy(Y_train);
    Matrix mx_test = Matrix.constructWithCopy(X_test);
    Matrix my_test = Matrix.constructWithCopy(Y_test);

    double minimum_error = (double) 1000;
    int optimal_lambda = 0;

    output_file = "output-" + train_file_name;
    PrintStream output = new PrintStream(new File(output_file));

    for (int lambda = 0; lambda <= 150; lambda++) {
      Matrix w =
          ((((mx_train.transpose().times(mx_train))
                      .plus(Matrix.identity(training_cols, training_cols).times((double) lambda)))
                  .inverse())
              .times((mx_train.transpose()).times(my_train)));

      Matrix E_train = calculateMSE(training_rows, mx_train, my_train, w);
      Matrix E_test = calculateMSE(testing_rows, mx_test, my_test, w);

      output.append(Double.toString(E_train.get(0, 0)) + ",");
      output.append(Double.toString(E_test.get(0, 0)) + ",");
      output.append(Integer.toString(lambda) + ",");
      output.println();

      if (E_test.get(0, 0) < minimum_error) {
        minimum_error = E_test.get(0, 0);
        optimal_lambda = lambda;
      }
    }

    System.out.println("Minimum Error:" + minimum_error);
    System.out.println("Optimal Lambda:" + optimal_lambda);
    output.close();
  }
  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");
  }
 public MyMatrix transpose() {
   return new MyMatrix(a.transpose());
 }
Beispiel #17
0
 /**
  * Assume une relation linéaire entre les angles et la longueur, les moments faisant office de
  * "rayons". En normalisant, on peut oublier ce moment.
  *
  * @param angles (in rad)
  * @return normalized length of muscle.
  */
 public Matrix computeLength(Matrix angles) {
   Matrix l = _minL0.minus(_k.arrayTimes((angles.minus(_minA)).times(_mom.transpose())));
   return l;
 }
Beispiel #18
0
 /**
  * Assume une relation linéaire entre les angles et la longueur, les moments faisant office de
  * "rayons". En normalisant, on peut oublier ce moment. Ici, les angles sont inutiles...
  *
  * @param angles (in rad)
  * @param angSpeed (in rad/s)
  * @return normalized speed on muscle.
  */
 public Matrix computeSpeed(Matrix angles, Matrix angSpeed) {
   Matrix v = _k.arrayTimes(angSpeed.times(_mom.transpose()));
   return v;
 }
Beispiel #19
0
  public static Matrix find(Stack<?> from, Stack<?> to) {

    //		System.out.println("Homographie:");
    //		System.out.println("From:");
    //		System.out.println("   "+from);
    //		System.out.println("To:");
    //		System.out.println("   "+to);

    Stack fromC = new Stack(), toC = new Stack();
    for (Object p : from) {
      fromC.push(p);
    }
    for (Object p : to) {
      toC.push(p);
    }

    int n = from.size();
    if (n < 4) {
      throw new Error("Homographie.find: Not enought point");
    }
    if (n != to.size()) {
      throw new Error("Homographie.find: The 2 args don't have the same number of point");
    }
    if (!((from.peek() instanceof Pt2 && from.peek() instanceof Pt2)
        || (from.peek() instanceof Pt3 && from.peek() instanceof Pt3))) {
      throw new Error("Homographie.find: The 2 args don't have the same class, among Pt or Vect");
    }
    boolean typeIsPt = from.peek() instanceof Pt2;
    // On definit la matrice A et Q
    double[][] A_array = new double[2 * n][8];
    double[][] Q_array = new double[2 * n][1];
    int i = 0;
    while (!fromC.isEmpty()) {
      Pt2 p = (typeIsPt) ? (Pt2) fromC.pop() : new Pt2((Pt3) fromC.pop());
      Pt2 q = (typeIsPt) ? (Pt2) toC.pop() : new Pt2((Pt3) toC.pop());
      //		while (!from.isEmpty()) {
      //			Pt2 p = (typeIsPt) ? (Pt2) from.pop() : new Pt2((Pt3) from.pop());
      //			Pt2 q = (typeIsPt) ? (Pt2)   to.pop() : new Pt2((Pt3)   to.pop());
      double[] l1 = {p.x, p.y, 1, 0, 0, 0, -p.x * q.x, -p.y * q.x};
      double[] l2 = {0, 0, 0, p.x, p.y, 1, -p.x * q.y, -p.y * q.y};
      A_array[i] = l1;
      A_array[i + 1] = l2;
      Q_array[i][0] = q.x;
      Q_array[i + 1][0] = q.y;
      i += 2;
    }
    Matrix A = new Matrix(A_array);
    Matrix Q = new Matrix(Q_array);
    // On calcule son inverse ou son pseudo-inverse B
    Matrix B;
    if (n == 4) {
      B = A.inverse();
    } else {
      Matrix At = A.transpose();
      B = At.times(A).inverse().times(At);
    }
    // On calcule l'homographie
    Matrix h_vert = B.times(Q);
    double[][] H_array = {
      {h_vert.get(0, 0), h_vert.get(1, 0), h_vert.get(2, 0)},
      {h_vert.get(3, 0), h_vert.get(4, 0), h_vert.get(5, 0)},
      {h_vert.get(6, 0), h_vert.get(7, 0), 1}
    };
    Matrix H = new Matrix(H_array);
    return (typeIsPt) ? H : H.inverse().transpose();
  }
Beispiel #20
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;
  }