Ejemplo n.º 1
0
  public void CalculatePrediction(int steps_ahead) {
    if (steps_ahead > 0) {
      predicted_means_ = new DoubleMatrix[steps_ahead];
      predicted_variances_ = new DoubleMatrix[steps_ahead];

      DoubleMatrix previous_state_mean = estimated_state_means_[estimated_state_means_.length - 1];
      DoubleMatrix previous_state_covariance =
          estimated_state_covariances_[estimated_state_covariances_.length - 1];
      for (int ii = 0; ii < steps_ahead; ii++) {
        DoubleMatrix a = state_transition_matrix_ref_.mmul(previous_state_mean);
        DoubleMatrix R =
            state_transition_matrix_ref_
                .mmul(previous_state_covariance)
                .mmul(state_transition_matrix_ref_.transpose())
                .addi(transition_covariance_matrix_ref_);
        // One-step-ahead observation prediction.
        predicted_means_[ii] = observation_matrix_ref_.mmul(a);
        predicted_variances_[ii] =
            observation_matrix_ref_
                .mmul(R)
                .mmul(observation_matrix_ref_.transpose())
                .addi(observation_covariance_matrix_ref_);
        previous_state_mean = a;
        previous_state_covariance = R;
      }
    } else {
      // smoothing
      predicted_means_ = predicted_observation_means_;
      predicted_variances_ = predicted_observation_covariances_;
    }
  }
 public DoubleMatrix free_energy(DoubleMatrix v_sample) {
   DoubleMatrix wv_hb =
       weights.mmul(v_sample.transpose()).addi(this.hbias.repmat(v_sample.rows, 1).transpose());
   DoubleMatrix vb = v_sample.mmul(this.vbias.transpose());
   DoubleMatrix hi = MatrixMath.sum(MatrixMath.log(MatrixMath.exp(wv_hb).addi(1.0)), 1);
   return hi.mul(-1.0).subi(vb);
 }
  /**
   * Reconstruction entropy. This compares the similarity of two probability distributions, in this
   * case that would be the input and the reconstructed input with gaussian noise. This will account
   * for either regularization or none depending on the configuration.
   *
   * @return reconstruction error
   */
  public double getReConstructionCrossEntropy() {
    DoubleMatrix preSigH = input.mmul(W).addRowVector(hBias);
    DoubleMatrix sigH = sigmoid(preSigH);

    DoubleMatrix preSigV = sigH.mmul(W.transpose()).addRowVector(vBias);
    DoubleMatrix sigV = sigmoid(preSigV);
    DoubleMatrix inner = input.mul(log(sigV)).add(oneMinus(input).mul(log(oneMinus(sigV))));

    double ret = inner.rowSums().mean();
    if (normalizeByInputRows) ret /= input.rows;

    return ret;
  }
Ejemplo n.º 4
0
  private void UpdateFilteredStates() {
    DoubleMatrix state_transition_matrix_T = state_transition_matrix_ref_.transpose();
    DoubleMatrix observation_matrix_T = observation_matrix_ref_.transpose();

    for (int ii = 0; ii < number_of_observations_; ii++) {
      DoubleMatrix previous_state_mean =
          (ii == 0) ? initial_state_mean_ref_ : estimated_state_means_[ii - 1];
      DoubleMatrix previous_state_covariance =
          (ii == 0) ? initial_state_covariance_ref_ : estimated_state_covariances_[ii - 1];

      // One-step-ahead state prediction. (i)
      DoubleMatrix a = state_transition_matrix_ref_.mmul(previous_state_mean);
      DoubleMatrix R =
          state_transition_matrix_ref_
              .mmul(previous_state_covariance)
              .mmul(state_transition_matrix_T)
              .addi(transition_covariance_matrix_ref_);
      // One-step-ahead observation prediction(ii)
      predicted_observation_means_[ii] = observation_matrix_ref_.mmul(a);

      predicted_observation_covariances_[ii] =
          observation_matrix_ref_
              .mmul(R)
              .mmul(observation_matrix_T)
              .addi(observation_covariance_matrix_ref_);

      // if current observation is null:
      if (observations_ref_[ii] == null) {
        estimated_state_means_[ii] = a;
        estimated_state_covariances_[ii] = R;
      } else {
        DoubleMatrix inv_predicted_observation_covariances =
            InverseMatrix.inverse(predicted_observation_covariances_[ii]);
        DoubleMatrix R_obs_mat_T_inv_pred_obs_cov =
            R.mmul(observation_matrix_T).mmuli(inv_predicted_observation_covariances);
        // forward filtering states.(iii)
        estimated_state_means_[ii] =
            R_obs_mat_T_inv_pred_obs_cov.mmul(
                    observations_ref_[ii].sub(predicted_observation_means_[ii]))
                .addi(a);

        estimated_state_covariances_[ii] =
            R.sub(R_obs_mat_T_inv_pred_obs_cov.mmul(observation_matrix_ref_).mmuli(R));
        estimated_means_[ii] = observation_matrix_ref_.mmul(estimated_state_means_[ii]);
        estimated_covariances_[ii] =
            observation_matrix_ref_
                .mmul(estimated_state_covariances_[ii])
                .mmul(observation_matrix_T)
                .addi(observation_covariance_matrix_ref_);
      }
    }
  }
Ejemplo n.º 5
0
 /**
  * 求广义逆矩阵,使用正交投影方法
  *
  * @param ht
  * @return
  */
 public DoubleMatrix getMPMatrixByOP(DoubleMatrix H) {
   DoubleMatrix M;
   try {
     M = H.mmul(H.transpose()); // HHt
     addPositiveValue(M);
     return H.transpose().mmul(inverse(M));
   } catch (LapackException e) {
     M = H.transpose().mmul(H); // HtH
     addPositiveValue(M);
     return inverse(M).mmul(H.transpose());
   }
 }
Ejemplo n.º 6
0
  public static void main(String[] args) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader("matrix_test"))) {
      // read table from file
      List<String[]> rows =
          reader.lines().map(line -> line.split(" ")).collect(Collectors.toList());
      double[][] values = new double[rows.size()][rows.get(0).length];
      for (int i = 0; i < values.length; i++) {
        String[] row = rows.get(i);
        for (int j = 0; j < values[0].length; j++) {
          values[i][j] = Double.parseDouble(row[j]);
        }
      }

      DoubleMatrix matrix = new DoubleMatrix(values);
      Vector coordVector = new Vector(matrix.getRows()); // 000..00 (n-times)
      while (coordVector.hasNextVector()) {
        coordVector.nextVector(); // get next vector (eg 000..00 -> 000..01)
        DoubleMatrix coord = coordVector.row();
        DoubleMatrix codeWord = coord.mmul(matrix); // m * G
        modi(codeWord, 2);
        String prefix = "0 0 0 0 1 ";
        String word = MatrixUtils.toString(codeWord);
        if (word.startsWith(prefix)) {
          System.out.println(word);
        }
      }

      /*// find syndromes
      Syndrome syndrome = new Syndrome(new DoubleMatrix(values));
      syndrome.build();

      // generate xls file with table
      HSSFWorkbook wb = new HSSFWorkbook();
      HSSFSheet sheet = wb.createSheet("Syndrome table");
      int rowNumber = 0;

      Vector syndromeVector = new Vector(values.length);
      putValue(sheet, rowNumber++, syndromeVector.toString(),
              syndrome.getErrorVector(syndromeVector.toString()));
      while (syndromeVector.hasNextVector()) {
          syndromeVector.nextVector();
          putValue(sheet, rowNumber++, syndromeVector.toString(),
                  syndrome.getErrorVector(syndromeVector.toString()));
      }

      try (FileOutputStream fileOut = new FileOutputStream("syndrome_table.xls")) {
          wb.write(fileOut);
      }*/
    }
  }
Ejemplo n.º 7
0
  /**
   * 求广义逆矩阵 Theory:最大秩分解 U*S*Vt = A C=U*sqrt(S) D=sqrt(S)*Vt <==> A=C*D MP(A) =
   * D'*inv(D*D')*inv(C'*C)*C'
   *
   * @param ht
   * @return
   */
  public DoubleMatrix getMPMatrix(DoubleMatrix ht) {

    int m = ht.rows;
    int n = ht.columns;
    DoubleMatrix[] USV = Singular.fullSVD(ht);
    DoubleMatrix U = USV[0];
    double[] s_raw = USV[1].data.clone(); // 奇异值
    // 去除0
    int k = 0;
    while (k < s_raw.length && s_raw[k] > 0.1e-5) {
      k++;
    }
    double[] s = new double[k];
    for (int i = 0; i < s.length; i++) {
      s[i] = s_raw[i];
    }

    DoubleMatrix Vt = USV[2].transpose(); // n*n
    int sn = s.length;
    for (int i = 0; i < sn; i++) {
      s[i] = Math.sqrt(s[i]);
    }

    // 构造m*sn sn*n矩阵
    DoubleMatrix S1 = new DoubleMatrix(m, sn);
    DoubleMatrix S2 = new DoubleMatrix(sn, n);
    for (int i = 0; i < sn; i++) {
      S1.put(i, i, s[i]);
      S2.put(i, i, s[i]);
    }
    DoubleMatrix C = U.mmul(S1);
    DoubleMatrix D = S2.mmul(Vt);

    DoubleMatrix DT = D.transpose();
    DoubleMatrix DD = D.mmul(DT);
    DoubleMatrix invDD = inverse(DD);

    DoubleMatrix DDD = DT.mmul(invDD);

    DoubleMatrix CT = C.transpose();
    DoubleMatrix CC = CT.mmul(C);
    DoubleMatrix invCC = inverse(CC);

    DoubleMatrix CCC = invCC.mmul(CT);
    DoubleMatrix Ainv = DDD.mmul(CCC);

    return Ainv;
  }
  private List<DoubleMatrix> countErrors(DoubleMatrix result, DoubleMatrix output) {

    ArrayList<DoubleMatrix> errors = new ArrayList<DoubleMatrix>();
    List<Layer> layers = getLayers();

    DoubleMatrix err = result.sub(output);
    errors.add(err);

    for (int i = layers.size() - 1; i > 1; i--) {
      DoubleMatrix previousErrors = errors.get(errors.size() - 1);
      Layer layer = layers.get(i);

      DoubleMatrix transposedWeights = layer.getWeights().transpose();
      DoubleMatrix errorOfCurrentLayer = transposedWeights.mmul(previousErrors);
      errors.add(errorOfCurrentLayer);
    }

    Collections.reverse(errors);

    return errors;
  }
Ejemplo n.º 9
0
  public void model(
      final SLCImage master, final SLCImage slave, Orbit masterOrbit, Orbit slaveOrbit)
      throws Exception {

    if (!masterOrbit.isInterpolated()) {
      logger.debug("Baseline cannot be computed, master orbit not initialized.");
      throw new Exception("Baseline.model_parameters: master orbit not initialized");
    } else if (!slaveOrbit.isInterpolated()) {
      logger.debug("Baseline cannot be computed, slave orbit not initialized.");
      throw new Exception("Baseline.model_parameters: slave orbit not initialized");
    }

    if (isInitialized) {
      logger.warn("baseline already isInitialized??? (returning)");
      return;
    }

    masterWavelength = master.getRadarWavelength();

    // Model r = nearRange + drange_dp*p -- p starts at 1
    nearRange = master.pix2range(1.0);
    drange_dp = master.pix2range(2.0) - master.pix2range(1.0);
    nearRange -= drange_dp; // -- p starts at 1

    // Set min/maxima for normalization
    linMin = master.currentWindow.linelo; // also used during polyval...
    linMax = master.currentWindow.linehi;
    pixMin = master.currentWindow.pixlo;
    pixMax = master.currentWindow.pixhi;
    hMin = 0.0;
    hMax = 5000.0;

    // Loop counters and sampling
    int cnt = 0; // matrix index
    final double deltaPixels = master.currentWindow.pixels() / N_POINTS_RNG;
    final double deltaLines = master.currentWindow.lines() / N_POINTS_AZI;
    final double deltaHeight = (hMax - hMin) / N_HEIGHTS;

    // Declare matrices for modeling Bperp
    // Note: for stability of normalmatrix, fill aMatrix with normalized line, etc.

    // perpendicular baseline
    DoubleMatrix bPerpMatrix = new DoubleMatrix(N_POINTS_AZI * N_POINTS_RNG * N_HEIGHTS, 1);

    // parallel baseline
    DoubleMatrix bParMatrix = new DoubleMatrix(N_POINTS_AZI * N_POINTS_RNG * N_HEIGHTS, 1);

    // viewing angle
    DoubleMatrix thetaMatrix = new DoubleMatrix(N_POINTS_AZI * N_POINTS_RNG * N_HEIGHTS, 1);

    // incidence angle
    DoubleMatrix thetaIncMatrix = new DoubleMatrix(N_POINTS_AZI * N_POINTS_RNG * N_HEIGHTS, 1);

    // design matrix
    DoubleMatrix aMatrix = new DoubleMatrix(N_POINTS_AZI * N_POINTS_RNG * N_HEIGHTS, numCoeffs);

    // Loop over heights(k), lines(i), pixels(j) to estimate baseline
    // height levels
    for (long k = 0; k < N_HEIGHTS; ++k) {

      final double height = hMin + k * deltaHeight;

      // azimuth direction
      for (long i = 0; i < N_POINTS_AZI; ++i) {

        final double line = master.currentWindow.linelo + i * deltaLines;
        Point pointOnEllips; // point, returned by lp2xyz
        double sTazi, sTrange;

        // Azimuth time for this line
        final double mTazi = master.line2ta(line);

        // xyz for master satellite from time
        final Point pointOnMasterOrb = masterOrbit.getXYZ(mTazi);

        // Continue looping in range direction
        for (long j = 0; j < N_POINTS_RNG; ++j) {

          final double pixel = master.currentWindow.pixlo + j * deltaPixels;

          // ______ Range time for this pixel ______
          // final double m_trange = master.pix2tr(pixel);
          pointOnEllips = masterOrbit.lph2xyz(line, pixel, height, master);

          // Compute xyz for slave satellite from pointOnEllips
          Point pointTime = slaveOrbit.xyz2t(pointOnEllips, slave);
          sTazi = pointTime.y;
          sTrange = pointTime.x;

          // Slave position
          final Point pointOnSlaveOrb = slaveOrbit.getXYZ(sTazi);

          // Compute angle between near parallel orbits
          final Point velOnMasterOrb = masterOrbit.getXYZDot(mTazi);
          final Point velOnSlaveOrb = slaveOrbit.getXYZDot(sTazi);
          final double angleOrbits = velOnMasterOrb.angle(velOnSlaveOrb);

          logger.debug(
              "Angle between orbits master-slave (at l,p= "
                  + line
                  + ","
                  + pixel
                  + ") = "
                  + rad2deg(angleOrbits)
                  + " [deg]");

          // Note: convergence assumed constant!
          orbitConvergence = angleOrbits;
          // final heading = angle(velOnMasterOrb,[1 0 0]) //?
          // orbitHeading = 0.0; // not yet used

          // The baseline parameters, derived from the positions (x,y,z)
          //    alpha is angle counterclockwize(b, plane with normal=rho1=rho2)
          //    theta is angle counterclockwize(rho1 = pointOnMasterOrb, r1 = pointOnMasterOrb -
          // pointOnEllips, r2 = pointOnSlaveOrb - pointOnEllips)

          // construct helper class
          BaselineComponents baselineComponents = new BaselineComponents().invoke();
          compute_B_Bpar_Bperp_Theta(
              baselineComponents, pointOnEllips, pointOnMasterOrb, pointOnSlaveOrb);

          final double b = baselineComponents.getB();
          final double bPar = baselineComponents.getBpar();
          final double bPerp = baselineComponents.getBperp();
          final double theta = baselineComponents.getTheta();
          final double thetaInc = computeIncAngle(pointOnMasterOrb, pointOnEllips); // [rad]!!!

          // Modelling of bPerp(l,p) = a00 + a10*l + a01*p
          bPerpMatrix.put(cnt, 0, bPerp);
          bParMatrix.put(cnt, 0, bPar);
          thetaMatrix.put(cnt, 0, theta);
          thetaIncMatrix.put(cnt, 0, thetaInc);

          // --- b(l,p,h) = a000 +
          //                a100*l   + a010*p   + a001*h   +
          //                a110*l*p + a101*l*h + a011*p*h +
          //                a200*l^2 + a020*p^2 + a002*h^2
          aMatrix.put(cnt, 0, 1.0);
          aMatrix.put(cnt, 1, normalize2(line, linMin, linMax));

          aMatrix.put(cnt, 2, normalize2(pixel, pixMin, pixMax));
          aMatrix.put(cnt, 3, normalize2(height, hMin, hMax));
          aMatrix.put(cnt, 4, normalize2(line, linMin, linMax) * normalize2(pixel, pixMin, pixMax));
          aMatrix.put(cnt, 5, normalize2(line, linMin, linMax) * normalize2(height, hMin, hMax));
          aMatrix.put(cnt, 6, normalize2(pixel, pixMin, pixMax) * normalize2(height, hMin, hMax));
          aMatrix.put(cnt, 7, sqr(normalize2(line, linMin, linMax)));
          aMatrix.put(cnt, 8, sqr(normalize2(pixel, pixMin, pixMax)));
          aMatrix.put(cnt, 9, sqr(normalize2(height, hMin, hMax)));
          cnt++;

          // b/alpha representation of baseline
          final double alpha =
              (bPar == 0 && bPerp == 0)
                  ? Double.NaN
                  : theta - Math.atan2(bPar, bPerp); // sign ok atan2

          // horizontal/vertical representation of baseline
          final double bH = b * Math.cos(alpha); // sign ok
          final double bV = b * Math.sin(alpha); // sign ok

          // TODO: check sign of infinity!!!
          // Height ambiguity: [h] = -lambda/4pi * (r1sin(theta)/bPerp) * phi==2pi
          final double hAmbiguity =
              (bPerp == 0)
                  ? Double.POSITIVE_INFINITY
                  : -master.getRadarWavelength()
                      * (pointOnMasterOrb.min(pointOnEllips)).norm()
                      * Math.sin(theta)
                      / (2.0 * bPerp);

          // Some extra info if in DEBUG unwrapMode
          logger.debug(
              "The baseline parameters for (l,p,h) = " + line + ", " + pixel + ", " + height);
          logger.debug("\talpha (deg), BASELINE: \t" + rad2deg(alpha) + " \t" + b);
          logger.debug("\tbPar, bPerp:      \t" + bPar + " \t" + bPerp);
          logger.debug("\tbH, bV:           \t" + bH + " \t" + bV);
          logger.debug("\tHeight ambiguity: \t" + hAmbiguity);
          logger.debug("\ttheta (deg):      \t" + rad2deg(theta));
          logger.debug("\tthetaInc (deg):  \t" + rad2deg(thetaInc));
          logger.debug("\tpointOnMasterOrb (x,y,z) = " + pointOnMasterOrb.toString());
          logger.debug("\tpointOnSlaveOrb (x,y,z) = " + pointOnSlaveOrb.toString());
          logger.debug("\tpointOnEllips (x,y,z) = " + pointOnEllips.toString());
        } // loop pixels
      } // loop lines
    } // loop heights

    // Model all Baselines as 2d polynomial of degree 1
    DoubleMatrix nMatrix = matTxmat(aMatrix, aMatrix);
    DoubleMatrix rhsBperp = matTxmat(aMatrix, bPerpMatrix);
    DoubleMatrix rhsBpar = matTxmat(aMatrix, bParMatrix);
    DoubleMatrix rhsTheta = matTxmat(aMatrix, thetaMatrix);
    DoubleMatrix rhsThetaInc = matTxmat(aMatrix, thetaIncMatrix);
    //        DoubleMatrix Qx_hat   = nMatrix;

    final DoubleMatrix Qx_hat =
        LinearAlgebraUtils.invertChol(Decompose.cholesky(nMatrix).transpose());

    // TODO: refactor to _internal_ cholesky decomposition
    // choles(Qx_hat);               // Cholesky factorisation normalmatrix
    // solvechol(Qx_hat,rhsBperp);   // Solution Bperp coefficients in rhsB
    // solvechol(Qx_hat,rhsBpar);    // Solution Theta coefficients in rhsTheta
    // solvechol(Qx_hat,rhsTheta);       // Solution Theta coefficients in rhsTheta
    // solvechol(Qx_hat,rhsThetaInc);   // Solution Theta_inc coefficients in rhsThetaInc
    // invertchol(Qx_hat);           // Covariance matrix of normalized unknowns

    rhsBperp = Solve.solvePositive(nMatrix, rhsBperp);
    rhsBpar = Solve.solvePositive(nMatrix, rhsBpar);
    rhsTheta = Solve.solvePositive(nMatrix, rhsTheta);
    rhsThetaInc = Solve.solvePositive(nMatrix, rhsThetaInc);

    // Info on inversion, normalization is ok______
    final DoubleMatrix yHatBperp = aMatrix.mmul(rhsBperp);
    final DoubleMatrix eHatBperp = bPerpMatrix.sub(yHatBperp);
    // DoubleMatrix Qe_hat  = Qy - Qy_hat;
    // DoubleMatrix y_hatT  = aMatrix * rhsTheta;
    // DoubleMatrix e_hatT  = thetaMatrix - y_hatT;

    // Copy estimated coefficients to private fields
    bperpCoeffs = rhsBperp;
    bparCoeffs = rhsBpar;
    thetaCoeffs = rhsTheta;
    thetaIncCoeffs = rhsThetaInc;

    // Test inverse -- repair matrix!!!
    for (int i = 0; i < Qx_hat.rows; i++) {
      for (int j = 0; j < i; j++) {
        Qx_hat.put(j, i, Qx_hat.get(i, j));
      }
    }

    final double maxDev = abs(nMatrix.mmul(Qx_hat).sub(DoubleMatrix.eye(Qx_hat.rows))).max();

    logger.debug("BASELINE: max(abs(nMatrix*inv(nMatrix)-I)) = " + maxDev);

    if (maxDev > .01) {
      logger.warn(
          "BASELINE: max. deviation nMatrix*inv(nMatrix) from unity = "
              + maxDev
              + ". This is larger than .01: do not use this!");
    } else if (maxDev > .001) {
      logger.warn(
          "BASELINE: max. deviation nMatrix*inv(nMatrix) from unity = "
              + maxDev
              + ". This is between 0.01 and 0.001 (maybe not use it)");
    }

    // Output solution and give max error
    // --- B(l,p,h) = a000 +
    //                a100*l   + a010*p   + a001*h   +
    //                a110*l*p + a101*l*h + a011*p*h +
    //                a200*l^2 + a020*p^2 + a002*h^2
    logger.debug("--------------------");
    logger.debug("Result of modeling: Bperp(l,p) = a000 + a100*l + a010*p + a001*h + ");
    logger.debug(" a110*l*p + a101*l*h + a011*p*h + a200*l^2 + a020*p^2 + a002*h^2");
    logger.debug("l,p,h in normalized coordinates [-2:2].");
    logger.debug("Bperp_a000 = " + rhsBperp.get(0, 0));
    logger.debug("Bperp_a100 = " + rhsBperp.get(1, 0));
    logger.debug("Bperp_a010 = " + rhsBperp.get(2, 0));
    logger.debug("Bperp_a001 = " + rhsBperp.get(3, 0));
    logger.debug("Bperp_a110 = " + rhsBperp.get(4, 0));
    logger.debug("Bperp_a101 = " + rhsBperp.get(5, 0));
    logger.debug("Bperp_a011 = " + rhsBperp.get(6, 0));
    logger.debug("Bperp_a200 = " + rhsBperp.get(7, 0));
    logger.debug("Bperp_a020 = " + rhsBperp.get(8, 0));
    logger.debug("Bperp_a002 = " + rhsBperp.get(9, 0));
    double maxerr = (abs(eHatBperp)).max();

    if (maxerr > 2.00) //
    {
      logger.warn("Max. error bperp modeling at 3D datapoints: " + maxerr + "m");

    } else {
      logger.info("Max. error bperp modeling at 3D datapoints: " + maxerr + "m");
    }
    logger.debug("--------------------");
    logger.debug("Range: r(p) = r0 + dr*p");
    logger.debug("l and p in un-normalized, absolute, coordinates (1:nMatrix).");
    final double range1 = master.pix2range(1.0);
    final double range5000 = master.pix2range(5000.0);
    final double drange = (range5000 - range1) / 5000.0;
    logger.debug("range = " + (range1 - drange) + " + " + drange + "*p");

    // orbit initialized
    isInitialized = true;
  }
Ejemplo n.º 10
0
  public static double[] polyFit2D(
      final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix z, final int degree)
      throws IllegalArgumentException {

    logger.setLevel(Level.INFO);

    if (x.length != y.length || !x.isVector() || !y.isVector()) {
      logger.error("polyfit: require same size vectors.");
      throw new IllegalArgumentException("polyfit: require same size vectors.");
    }

    final int numOfObs = x.length;
    final int numOfUnkn = numberOfCoefficients(degree) + 1;

    DoubleMatrix A = new DoubleMatrix(numOfObs, numOfUnkn); // designmatrix

    DoubleMatrix mul;

    /** Set up design-matrix */
    for (int p = 0; p <= degree; p++) {
      for (int q = 0; q <= p; q++) {
        mul = pow(y, (p - q)).mul(pow(x, q));
        if (q == 0 && p == 0) {
          A = mul;
        } else {
          A = DoubleMatrix.concatHorizontally(A, mul);
        }
      }
    }

    // Fit polynomial
    logger.debug("Solving lin. system of equations with Cholesky.");
    DoubleMatrix N = A.transpose().mmul(A);
    DoubleMatrix rhs = A.transpose().mmul(z);

    // solution seems to be OK up to 10^-09!
    rhs = Solve.solveSymmetric(N, rhs);

    DoubleMatrix Qx_hat = Solve.solveSymmetric(N, DoubleMatrix.eye(N.getRows()));

    double maxDeviation = (N.mmul(Qx_hat).sub(DoubleMatrix.eye(Qx_hat.rows))).normmax();
    logger.debug("polyfit orbit: max(abs(N*inv(N)-I)) = " + maxDeviation);

    // ___ report max error... (seems sometimes this can be extremely large) ___
    if (maxDeviation > 1e-6) {
      logger.warn("polyfit orbit: max(abs(N*inv(N)-I)) = {}", maxDeviation);
      logger.warn("polyfit orbit interpolation unstable!");
    }

    // work out residuals
    DoubleMatrix y_hat = A.mmul(rhs);
    DoubleMatrix e_hat = y.sub(y_hat);

    if (e_hat.normmax() > 0.02) {
      logger.warn(
          "WARNING: Max. polyFit2D approximation error at datapoints (x,y,or z?): {}",
          e_hat.normmax());
    } else {
      logger.info(
          "Max. polyFit2D approximation error at datapoints (x,y,or z?): {}", e_hat.normmax());
    }

    if (logger.isDebugEnabled()) {
      logger.debug("REPORTING POLYFIT LEAST SQUARES ERRORS");
      logger.debug(" time \t\t\t y \t\t\t yhat  \t\t\t ehat");
      for (int i = 0; i < numOfObs; i++) {
        logger.debug(
            " ("
                + x.get(i)
                + ","
                + y.get(i)
                + ") :"
                + "\t"
                + y.get(i)
                + "\t"
                + y_hat.get(i)
                + "\t"
                + e_hat.get(i));
      }
    }
    return rhs.toArray();
  }
Ejemplo n.º 11
0
  public static double[] polyFit(DoubleMatrix t, DoubleMatrix y, final int degree)
      throws IllegalArgumentException {

    logger.setLevel(Level.INFO);

    if (t.length != y.length || !t.isVector() || !y.isVector()) {
      logger.error("polyfit: require same size vectors.");
      throw new IllegalArgumentException("polyfit: require same size vectors.");
    }

    // Normalize _posting_ for numerical reasons
    final int numOfPoints = t.length;

    // Check redundancy
    final int numOfUnknowns = degree + 1;
    logger.debug("Degree of interpolating polynomial: {}", degree);
    logger.debug("Number of unknowns: {}", numOfUnknowns);
    logger.debug("Number of data points: {}", numOfPoints);

    if (numOfPoints < numOfUnknowns) {
      logger.error("Number of points is smaller than parameters solved for.");
      throw new IllegalArgumentException("Number of points is smaller than parameters solved for.");
    }

    // Set up system of equations to solve coeff :: Design matrix
    logger.debug("Setting up linear system of equations");
    DoubleMatrix A = new DoubleMatrix(numOfPoints, numOfUnknowns);
    // work with columns
    for (int j = 0; j <= degree; j++) {
      A.putColumn(j, pow(t, j));
    }

    // Fit polynomial through computed vector of phases
    logger.debug("Solving lin. system of equations with Cholesky.");

    DoubleMatrix N = A.transpose().mmul(A);
    DoubleMatrix rhs = A.transpose().mmul(y);

    // solution seems to be OK up to 10^-09!
    DoubleMatrix x = Solve.solveSymmetric(N, rhs);
    DoubleMatrix Qx_hat = Solve.solveSymmetric(N, DoubleMatrix.eye(N.getRows()));

    double maxDeviation = (N.mmul(Qx_hat).sub(DoubleMatrix.eye(Qx_hat.rows))).normmax();
    logger.debug("polyfit orbit: max(abs(N*inv(N)-I)) = " + maxDeviation);

    // ___ report max error... (seems sometimes this can be extremely large) ___
    if (maxDeviation > 1e-6) {
      logger.warn("polyfit orbit: max(abs(N*inv(N)-I)) = {}", maxDeviation);
      logger.warn("polyfit orbit interpolation unstable!");
    }

    // work out residuals
    DoubleMatrix y_hat = A.mmul(x);
    DoubleMatrix e_hat = y.sub(y_hat);

    // 0.05 is already 1 wavelength! (?)
    if (e_hat.normmax() > 0.02) {
      logger.warn(
          "WARNING: Max. approximation error at datapoints (x,y,or z?): {}", e_hat.normmax());
    } else {
      logger.debug("Max. approximation error at datapoints (x,y,or z?): {}", e_hat.normmax());
    }

    if (logger.isDebugEnabled()) {
      logger.debug("REPORTING POLYFIT LEAST SQUARES ERRORS");
      logger.debug(" time \t\t\t y \t\t\t yhat  \t\t\t ehat");
      for (int i = 0; i < numOfPoints; i++) {
        logger.debug(" " + t.get(i) + "\t" + y.get(i) + "\t" + y_hat.get(i) + "\t" + e_hat.get(i));
      }

      for (int i = 0; i < numOfPoints - 1; i++) {
        // ___ check if dt is constant, not necessary for me, but may ___
        // ___ signal error in header data of SLC image ___
        double dt = t.get(i + 1) - t.get(i);
        logger.debug("Time step between point " + i + 1 + " and " + i + "= " + dt);

        if (Math.abs(dt - (t.get(1) - t.get(0))) > 0.001) // 1ms of difference we allow...
        logger.warn("WARNING: Orbit: data does not have equidistant time interval?");
      }
    }
    return x.toArray();
  }
Ejemplo n.º 12
0
  /** 训练模型 */
  private void train() {
    printInfo("训练数据载入完毕,开始训练模型………………训练数据规模" + train_set.rows + "x" + train_set.columns);
    // 输入矩阵初始化 横向即每列为一组输入
    /*
     *    4 8 …… N
     *
     *    1 5 …… N
     *    2 6 …… N
     *    3 7 …… N
     */
    P = new DoubleMatrix(NumberofInputNeurons, train_data_Count);
    // 测试机输出矩阵 横向
    T = new DoubleMatrix(NumberofOutputNeurons, train_data_Count);
    // 初始化
    for (int i = 0; i < train_data_Count; i++) {

      for (int j = 0; j < totalColCount; j++) {
        if (j < NumberofInputNeurons) {
          // 输入部分
          P.put(j, i, train_set.get(i, j));
        } else {
          T.put(j - NumberofInputNeurons, i, train_set.get(i, j));
        }
      }
    }
    printInfo("训练矩阵初始化完毕………………开始隐含层神经元权重与阈值");
    // end 初始化
    long start_time_train = System.currentTimeMillis();
    // 随机初始化输入权值矩阵
    // 行数为隐含层神经元个数,列数为输入层神经元
    /**
     * W11 W12 W13(第一个隐含神经元对应各输入的权值) W21 W22 W23(第二个隐含神经元对应各输入的权值) ………………………………(第N个隐含神经元对应各输入的权值)
     */
    InputWeight = DoubleMatrix.rand(NumberofHiddenNeurons, NumberofInputNeurons);

    // 初始化阈值
    BiasofHiddenNeurons = DoubleMatrix.rand(NumberofHiddenNeurons, 1);
    printInfo("隐含层神经元权重与阈值初始化完毕………………开始计算输入权重");
    DoubleMatrix tmpH = new DoubleMatrix(NumberofHiddenNeurons, train_data_Count);
    tmpH = InputWeight.mmul(P);
    printInfo("输入矩阵计算权重完毕………………开始计算输入权重");
    // 加阈值
    // 注意横向问题
    for (int i = 0; i < NumberofHiddenNeurons; i++) {
      for (int j = 0; j < train_data_Count; j++) {
        tmpH.put(i, j, tmpH.get(i, j) + BiasofHiddenNeurons.get(i, 0));
      }
    }
    printInfo("输入矩阵计算阈值完毕………………开始计算输入激活函数");
    // 输出矩阵
    DoubleMatrix H = new DoubleMatrix(NumberofHiddenNeurons, train_data_Count);

    if (func.startsWith("sig")) {
      for (int i = 0; i < NumberofHiddenNeurons; i++) {
        for (int j = 0; j < train_data_Count; j++) {
          double tmp = tmpH.get(i, j);
          tmp = 1.0f / (1 + Math.exp(-tmp));
          H.put(i, j, tmp);
        }
      }
    } else {
      throw new IllegalArgumentException("不支持的激活函数类型");
    }
    printInfo("输出矩阵计算激活函数完毕,开始求解广义逆………………矩阵规模" + H.columns + "x" + H.rows);
    // 将H转置
    DoubleMatrix Ht = H.transpose();

    // 求广义逆
    DoubleMatrix Ht_MP = getMPMatrix(Ht);
    printInfo("输出矩阵广义逆求解完毕………………开始求解输出矩阵权重");
    // 隐含层输出权重矩阵= Ht_MP * Tt
    OutputWeight = Ht_MP.mmul(T.transpose());
    printInfo("输出矩阵权重求解完毕………………");
    long end_time_train = System.currentTimeMillis();
    TrainingTime = (end_time_train - start_time_train) * 1.0f / 1000;

    printInfo("模型训练完毕………………开始评估模型");

    // 误差评估
    DoubleMatrix Yt = new DoubleMatrix(train_data_Count, NumberofOutputNeurons);
    Yt = Ht.mmul(OutputWeight);
    double MSE = 0;
    printInfo("共有" + NumberofOutputNeurons + "个输出值");
    for (int out = 0; out < NumberofOutputNeurons; out++) {
      printInfo("计算第" + (out + 1) + "个输出值");
      double mseTem = 0.0;
      for (int i = 0; i < train_data_Count; i++) {
        System.out.println(Yt.get(i, out) + " " + T.get(out, i));
        mseTem += (Yt.get(i, out) - T.get(out, i)) * (Yt.get(i, out) - T.get(out, i));
      }
      printInfo(
          "第" + NumberofOutputNeurons + "个输出值计算完毕,MSE=" + Math.sqrt(mseTem / train_data_Count));
      MSE += mseTem;
    }

    TrainingAccuracy = Math.sqrt(MSE / train_data_Count);
    printInfo("模型评估完毕………………");
  }
 public DoubleMatrix propdown(DoubleMatrix h) {
   return MatrixMath.sigmoid(h.mmul(this.weights).addi(vbias.repmat(v_data.rows, 1)));
 }
Ejemplo n.º 14
0
  /**
   * 测试模型
   *
   * @param filename
   */
  public void test_model(String filename, int testCount) {
    try {
      this.test_data_Count = testCount;
      test_set = loadMatrix(filename, test_data_Count, totalColCount);
    } catch (Exception e) {
      e.printStackTrace();
    }
    printInfo("测试数据载入完毕…………");
    // 测试数据输入矩阵初始化 横向即每列为一组输入
    testP = new DoubleMatrix(NumberofInputNeurons, test_data_Count);
    // 测试机输出矩阵 横向
    testT = new DoubleMatrix(NumberofOutputNeurons, test_data_Count);
    // 初始化
    for (int i = 0; i < test_data_Count; i++) {

      for (int j = 0; j < totalColCount; j++) {
        if (j < NumberofInputNeurons) {
          // 输入部分
          testP.put(j, i, test_set.get(i, j));
        } else {
          testT.put(j - NumberofInputNeurons, i, test_set.get(i, j));
        }
      }
    }
    // end 初始化
    printInfo("测试数据初始化完毕…………");
    long start_time_test = System.currentTimeMillis();
    // 计算输入权重与阈值部分

    DoubleMatrix tmpH = new DoubleMatrix(NumberofHiddenNeurons, test_data_Count);
    tmpH = InputWeight.mmul(testP);
    printInfo("权重计算完毕…………");
    // 加阈值
    // 注意横向问题
    for (int i = 0; i < NumberofHiddenNeurons; i++) {
      for (int j = 0; j < test_data_Count; j++) {
        tmpH.put(i, j, tmpH.get(i, j) + BiasofHiddenNeurons.get(i, 0));
      }
    }
    printInfo("阈值计算完毕…………");
    // 输出矩阵
    DoubleMatrix H = new DoubleMatrix(NumberofHiddenNeurons, test_data_Count);

    if (func.startsWith("sig")) {
      for (int i = 0; i < NumberofHiddenNeurons; i++) {
        for (int j = 0; j < test_data_Count; j++) {
          double tmp = tmpH.get(i, j);
          tmp = 1.0f / (1 + Math.exp(-tmp));
          H.put(i, j, tmp);
        }
      }
    } else {
      throw new IllegalArgumentException("不支持的激活函数类型");
    }
    printInfo("激活函数计算完毕…………");
    // 将H转置
    DoubleMatrix Ht = H.transpose();

    // 测试误差
    DoubleMatrix Yt = new DoubleMatrix(test_data_Count, NumberofOutputNeurons);
    Yt = Ht.mmul(OutputWeight);
    printInfo("测试完毕…………");
    long end_time_test = System.currentTimeMillis();
    TestingTime = (end_time_test - start_time_test) * 1.0f / 1000;
    double MSE = 0;
    printInfo("共有" + NumberofOutputNeurons + "个输出值");
    for (int out = 0; out < NumberofOutputNeurons; out++) {
      printInfo("计算第" + (out + 1) + "个输出值");
      double mseTem = 0.0;
      for (int i = 0; i < test_data_Count; i++) {
        mseTem += (Yt.get(i, out) - testT.get(out, i)) * (Yt.get(i, out) - testT.get(out, i));
      }
      printInfo(
          "第" + NumberofOutputNeurons + "个输出值计算完毕,MSE=" + Math.sqrt(mseTem / train_data_Count));
      MSE += mseTem;
    }
    TestingAccuracy = Math.sqrt(MSE / test_data_Count);
    printInfo("计算MSE完毕…………");
  }
Ejemplo n.º 15
0
  public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    int n = s.nextInt();
    int nn = n;
    DoubleMatrix d = DoubleMatrix.zeros(2 * n, 2 * n);
    DoubleMatrix d2 = DoubleMatrix.zeros(n, n);

    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        d.put(i, j, s.nextDouble());
        d2.put(i, j, d.get(i, j));
      }
    }
    // d2 = new DoubleMatrix(d.data);
    System.out.println(d);
    System.out.println(d);

    List<Integer> L = new ArrayList<Integer>(2 * n);
    List<Double> R = new ArrayList<Double>(2 * n);
    for (int i = 0; i < 2 * n; i++) {
      L.add(0);
      R.add(0.0);
    }
    // inicjalizacja lisci - jako etykiety kolejne liczby od 0
    for (int i = 0; i < n; i++) {
      L.set(i, i);
    }

    // V - drzewo addytywne, które tworzymy
    ArrayList[] V = new ArrayList[2 * n];
    for (int i = 0; i < V.length; i++) {
      V[i] = new ArrayList<Integer>();
    }

    double suma, rmin, rr;
    int i, j, vertNum = n;

    while (n > 3) {
      // wyznaczanie r dla każdego liścia
      for (int a = 0; a < n; a++) {
        suma = 0;
        for (int b = 0; b < n; b++) {
          suma = suma + d.get(L.get(a), L.get(b));
        }
        suma = suma / (n - 2);
        R.set(a, suma);
      }
      // wyznaczania sąsiadów na podstawie r
      i = 0;
      j = 1;
      rmin = d.get(L.get(0), L.get(1)) - (R.get(0) + R.get(1));
      for (int a = 0; a < n - 1; a++) {
        for (int b = a + 1; b < n; b++) {
          rr = d.get(L.get(a), L.get(b)) - (R.get(a) + R.get(b));
          if (rr < rmin) {
            rmin = rr;
            i = a;
            j = b;
          }
        }
      }

      // usuniecie ze zbioru lisci i,j oraz dodanie k
      L.set(n, vertNum);
      vertNum++;
      i = L.remove(i);
      j = L.remove(j - 1);
      n = n - 1;

      // uaktualnienie d dla każdego pozostałego liścia
      for (int l = 0; l < n - 1; l++) {
        double value = (d.get(i, L.get(l)) + d.get(j, L.get(l)) - d.get(i, j)) / 2;
        d.put(L.get(n - 1), L.get(l), value);
        d.put(L.get(l), L.get(n - 1), value);
      }

      // dodanie odpowiednich krawędzi do tworzonego drzewa
      V[i].add((vertNum - 1));
      V[j].add((vertNum - 1));
      V[vertNum - 1].add(i);
      V[vertNum - 1].add(j);

      // wyznaczenie odległości między nowym wierzchołkiem oraz i,j
      double value = (d.get(i, j) + d.get(i, L.get(0)) - d.get(j, L.get(0))) / 2;
      d.put(i, vertNum - 1, value);
      d.put(vertNum - 1, i, value);
      d.put(j, vertNum - 1, d.get(i, j) - d.get(i, vertNum - 1));
      d.put(vertNum - 1, j, d.get(i, j) - d.get(i, vertNum - 1));
    }

    // 3 elementowe drzewo
    double value;
    value = (d.get(L.get(0), L.get(1)) + d.get(L.get(0), L.get(2)) - d.get(L.get(1), L.get(2))) / 2;
    d.put(L.get(0), vertNum, value);
    d.put(vertNum, L.get(0), value);

    value = (d.get(L.get(0), L.get(1)) + d.get(L.get(1), L.get(2)) - d.get(L.get(0), L.get(2))) / 2;
    d.put(L.get(1), vertNum, value);
    d.put(vertNum, L.get(1), value);

    value = (d.get(L.get(0), L.get(2)) + d.get(L.get(1), L.get(2)) - d.get(L.get(0), L.get(1))) / 2;
    d.put(L.get(2), vertNum, value);
    d.put(vertNum, L.get(2), value);

    V[vertNum].add(L.get(0));
    V[vertNum].add(L.get(1));
    V[vertNum].add(L.get(2));
    V[L.get(0)].add(vertNum);
    V[L.get(1)].add(vertNum);
    V[L.get(2)].add(vertNum);

    // wypisanie wyników
    System.out.println(d);

    // DoubleMatrix w2 = DoubleMatrix.zeros(2*n, 2*n);
    ArrayList w = new ArrayList<Integer>();

    for (int a = 0; a <= vertNum; a++) {
      System.out.print(a);
      System.out.print(" : ");
      for (int b = 0; b < V[a].size(); b++) {
        System.out.print(V[a].get(b));
        System.out.print(" ");

        // w2.put(a,b,Integer.parseInt(V[a].get(b).toString()));
        w.add(V[a].get(b));
      }
      System.out.println("");
    }

    DoubleMatrix A = DoubleMatrix.zeros((nn * (nn - 1)) / 2, vertNum);
    DoubleMatrix g = DoubleMatrix.zeros((nn * (nn - 1)) / 2, 1);
    double blad = nk(A, d2, g, V, vertNum); // wrzucam to do siebie - mkd

    System.out.println(A);

    DoubleMatrix p = (new DoubleMatrix(A.rows, A.columns, A.data)).transpose();
    System.out.println(p.rows + " " + p.columns);
    DoubleMatrix p2 =
        (new DoubleMatrix(p.rows, p.columns, p.data))
            .mmul((new DoubleMatrix(A.rows, A.columns, A.data)));
    System.out.println("p2: " + p2);
    DoubleMatrix p3 = MatrixFunctions.pow(p2, -1);
    System.out.println("p3: " + p3);
    DoubleMatrix p4 = p3.mmul(p);
    DoubleMatrix b = p4.mmul(g);

    // DoubleMatrix b = MatrixFunctions.pow(A.transpose().mmul(A), -1).mmul(A.transpose()).mmul(g);
    System.out.println(g);
    System.out.println(b);
    System.out.println("Kwadrat bledu wynosi " + blad);
  }
Ejemplo n.º 16
0
  private void costantiniUnwrap() throws LPException {

    final int ny = wrappedPhase.rows - 1; // start from Zero!
    final int nx = wrappedPhase.columns - 1; // start from Zero!

    if (wrappedPhase.isVector()) throw new IllegalArgumentException("Input must be 2D array");
    if (wrappedPhase.rows < 2 || wrappedPhase.columns < 2)
      throw new IllegalArgumentException("Size of input must be larger than 2");

    // Default weight
    DoubleMatrix w1 = DoubleMatrix.ones(ny + 1, 1);
    w1.put(0, 0.5);
    w1.put(w1.length - 1, 0.5);
    DoubleMatrix w2 = DoubleMatrix.ones(1, nx + 1);
    w2.put(0, 0.5);
    w2.put(w2.length - 1, 0.5);
    DoubleMatrix weight = w1.mmul(w2);

    DoubleMatrix i, j, I_J, IP1_J, I_JP1;
    DoubleMatrix Psi1, Psi2;
    DoubleMatrix[] ROWS;

    // Compute partial derivative Psi1, eqt (1,3)
    i = intRangeDoubleMatrix(0, ny - 1);
    j = intRangeDoubleMatrix(0, nx);
    ROWS = grid2D(i, j);
    I_J = JblasUtils.sub2ind(wrappedPhase.rows, ROWS[0], ROWS[1]);
    IP1_J = JblasUtils.sub2ind(wrappedPhase.rows, ROWS[0].add(1), ROWS[1]);
    Psi1 =
        JblasUtils.getMatrixFromIdx(wrappedPhase, IP1_J)
            .sub(JblasUtils.getMatrixFromIdx(wrappedPhase, I_J));
    Psi1 = UnwrapUtils.wrapDoubleMatrix(Psi1);

    // Compute partial derivative Psi2, eqt (2,4)
    i = intRangeDoubleMatrix(0, ny);
    j = intRangeDoubleMatrix(0, nx - 1);
    ROWS = grid2D(i, j);
    I_J = JblasUtils.sub2ind(wrappedPhase.rows, ROWS[0], ROWS[1]);
    I_JP1 = JblasUtils.sub2ind(wrappedPhase.rows, ROWS[0], ROWS[1].add(1));
    Psi2 =
        JblasUtils.getMatrixFromIdx(wrappedPhase, I_JP1)
            .sub(JblasUtils.getMatrixFromIdx(wrappedPhase, I_J));
    Psi2 = UnwrapUtils.wrapDoubleMatrix(Psi2);

    // Compute beq
    DoubleMatrix beq = DoubleMatrix.zeros(ny, nx);
    i = intRangeDoubleMatrix(0, ny - 1);
    j = intRangeDoubleMatrix(0, nx - 1);
    ROWS = grid2D(i, j);
    I_J = JblasUtils.sub2ind(Psi1.rows, ROWS[0], ROWS[1]);
    I_JP1 = JblasUtils.sub2ind(Psi1.rows, ROWS[0], ROWS[1].add(1));
    beq.addi(JblasUtils.getMatrixFromIdx(Psi1, I_JP1).sub(JblasUtils.getMatrixFromIdx(Psi1, I_J)));
    I_J = JblasUtils.sub2ind(Psi2.rows, ROWS[0], ROWS[1]);
    I_JP1 = JblasUtils.sub2ind(Psi2.rows, ROWS[0].add(1), ROWS[1]);
    beq.subi(JblasUtils.getMatrixFromIdx(Psi2, I_JP1).sub(JblasUtils.getMatrixFromIdx(Psi2, I_J)));
    beq.muli(-1 / (2 * Constants._PI));
    for (int k = 0; k < beq.length; k++) {
      beq.put(k, Math.round(beq.get(k)));
    }
    beq.reshape(beq.length, 1);

    logger.debug("Constraint matrix");
    i = intRangeDoubleMatrix(0, ny - 1);
    j = intRangeDoubleMatrix(0, nx - 1);
    ROWS = grid2D(i, j);
    DoubleMatrix ROW_I_J = JblasUtils.sub2ind(i.length, ROWS[0], ROWS[1]);
    int nS0 = nx * ny;

    // Use by S1p, S1m
    DoubleMatrix[] COLS;
    COLS = grid2D(i, j);
    DoubleMatrix COL_IJ_1 = JblasUtils.sub2ind(i.length, COLS[0], COLS[1]);
    COLS = grid2D(i, j.add(1));
    DoubleMatrix COL_I_JP1 = JblasUtils.sub2ind(i.length, COLS[0], COLS[1]);
    int nS1 = (nx + 1) * (ny);

    // SOAPBinding.Use by S2p, S2m
    COLS = grid2D(i, j);
    DoubleMatrix COL_IJ_2 = JblasUtils.sub2ind(i.length + 1, COLS[0], COLS[1]);
    COLS = grid2D(i.add(1), j);
    DoubleMatrix COL_IP1_J = JblasUtils.sub2ind(i.length + 1, COLS[0], COLS[1]);
    int nS2 = nx * (ny + 1);

    // Equality constraint matrix (Aeq)
    /*
        S1p = + sparse(ROW_I_J, COL_I_JP1,1,nS0,nS1) ...
              - sparse(ROW_I_J, COL_IJ_1,1,nS0,nS1);
        S1m = -S1p;

        S2p = - sparse(ROW_I_J, COL_IP1_J,1,nS0,nS2) ...
              + sparse(ROW_I_J, COL_IJ_2,1,nS0,nS2);
        S2m = -S2p;
    */

    // ToDo: Aeq matrix should be sparse from it's initialization, look into JblasMatrix factory for
    // howto
    // ...otherwise even a data set of eg 40x40 pixels will exhaust heap:
    // ...    dimension of Aeq (equality constraints) matrix for 30x30 input is 1521x6240 matrix
    // ...    dimension of Aeq (                    ) matrix for 50x50 input is 2401x9800
    // ...    dimension of Aeq (                    ) matrix for 512x512 input is 261121x1046528
    DoubleMatrix S1p =
        JblasUtils.setUpMatrixFromIdx(nS0, nS1, ROW_I_J, COL_I_JP1)
            .sub(JblasUtils.setUpMatrixFromIdx(nS0, nS1, ROW_I_J, COL_IJ_1));
    DoubleMatrix S1m = S1p.neg();

    DoubleMatrix S2p =
        JblasUtils.setUpMatrixFromIdx(nS0, nS2, ROW_I_J, COL_IP1_J)
            .neg()
            .add(JblasUtils.setUpMatrixFromIdx(nS0, nS2, ROW_I_J, COL_IJ_2));
    DoubleMatrix S2m = S2p.neg();

    DoubleMatrix Aeq =
        concatHorizontally(concatHorizontally(S1p, S1m), concatHorizontally(S2p, S2m));

    final int nObs = Aeq.columns;
    final int nUnkn = Aeq.rows;

    DoubleMatrix c1 = JblasUtils.getMatrixFromRange(0, ny, 0, weight.columns, weight);
    DoubleMatrix c2 = JblasUtils.getMatrixFromRange(0, weight.rows, 0, nx, weight);

    c1.reshape(c1.length, 1);
    c2.reshape(c2.length, 1);

    DoubleMatrix cost =
        DoubleMatrix.concatVertically(
            DoubleMatrix.concatVertically(c1, c1), DoubleMatrix.concatVertically(c2, c2));

    logger.debug("Minimum network flow resolution");

    StopWatch clockLP = new StopWatch();
    LinearProgram lp = new LinearProgram(cost.data);
    lp.setMinProblem(true);

    boolean[] integerBool = new boolean[nObs];
    double[] lowerBound = new double[nObs];
    double[] upperBound = new double[nObs];

    for (int k = 0; k < nUnkn; k++) {
      lp.addConstraint(new LinearEqualsConstraint(Aeq.getRow(k).toArray(), beq.get(k), "cost"));
    }

    for (int k = 0; k < nObs; k++) {
      integerBool[k] = true;
      lowerBound[k] = 0;
      upperBound[k] = 99999;
    }

    // setup bounds and integer nature
    lp.setIsinteger(integerBool);
    lp.setUpperbound(upperBound);
    lp.setLowerbound(lowerBound);
    LinearProgramSolver solver = SolverFactory.newDefault();

    //        double[] solution;
    //        solution = solver.solve(lp);
    DoubleMatrix solution = new DoubleMatrix(solver.solve(lp));

    clockLP.stop();
    logger.debug("Total GLPK time: {} [sec]", (double) (clockLP.getElapsedTime()) / 1000);

    // Displatch the LP solution
    int offset;

    int[] idx1p = JblasUtils.intRangeIntArray(0, nS1 - 1);
    DoubleMatrix x1p = solution.get(idx1p);
    x1p.reshape(ny, nx + 1);
    offset = idx1p[nS1 - 1] + 1;

    int[] idx1m = JblasUtils.intRangeIntArray(offset, offset + nS1 - 1);
    DoubleMatrix x1m = solution.get(idx1m);
    x1m.reshape(ny, nx + 1);
    offset = idx1m[idx1m.length - 1] + 1;

    int[] idx2p = JblasUtils.intRangeIntArray(offset, offset + nS2 - 1);
    DoubleMatrix x2p = solution.get(idx2p);
    x2p.reshape(ny + 1, nx);
    offset = idx2p[idx2p.length - 1] + 1;

    int[] idx2m = JblasUtils.intRangeIntArray(offset, offset + nS2 - 1);
    DoubleMatrix x2m = solution.get(idx2m);
    x2m.reshape(ny + 1, nx);

    // Compute the derivative jumps, eqt (20,21)
    DoubleMatrix k1 = x1p.sub(x1m);
    DoubleMatrix k2 = x2p.sub(x2m);

    // (?) Round to integer solution
    if (roundK == true) {
      for (int idx = 0; idx < k1.length; idx++) {
        k1.put(idx, FastMath.floor(k1.get(idx)));
      }
      for (int idx = 0; idx < k2.length; idx++) {
        k2.put(idx, FastMath.floor(k2.get(idx)));
      }
    }

    // Sum the jumps with the wrapped partial derivatives, eqt (10,11)
    k1.reshape(ny, nx + 1);
    k2.reshape(ny + 1, nx);
    k1.addi(Psi1.div(Constants._TWO_PI));
    k2.addi(Psi2.div(Constants._TWO_PI));

    // Integrate the partial derivatives, eqt (6)
    // cumsum() method in JblasTester -> see cumsum_demo() in JblasTester.cumsum_demo()
    DoubleMatrix k2_temp = DoubleMatrix.concatHorizontally(DoubleMatrix.zeros(1), k2.getRow(0));
    k2_temp = JblasUtils.cumsum(k2_temp, 1);
    DoubleMatrix k = DoubleMatrix.concatVertically(k2_temp, k1);
    k = JblasUtils.cumsum(k, 1);

    // Unwrap - final solution
    unwrappedPhase = k.mul(Constants._TWO_PI);
  }
Ejemplo n.º 17
0
  public static void main(String[] args) {
    DoubleMatrix A = readJamaMatrixFromFile(".\\src\\test\\resources\\10_10_A");
    DoubleMatrix B = readJamaMatrixFromFile(".\\src\\test\\resources\\10_10_B");
    Long start = System.currentTimeMillis();
    DoubleMatrix result = A.mmul(B);
    Long end = System.currentTimeMillis();
    Long time = end - start;
    System.out.println("Time for JBLAS multiply 10x10 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\100_100_M1");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\100_100_M2");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 100x100 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\200_200_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\200_200_B");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 200x200 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\300_300_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\300_300_B");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 300x300 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\500_500_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\500_500_B");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 500x500 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\1000_1000_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\1000_1000_B");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 1000x1000 is: " + time);
    // Matrix Multiply x2
    A = readJamaMatrixFromFile(".\\src\\test\\resources\\2_2_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\2_2_B");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 2x2 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\4_4_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\4_4_B");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 4x4 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\8_8_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\8_8_A");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 8x8 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\16_16_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\16_16_A");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 16x16 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\32_32_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\32_32_A");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 32x32 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\64_64_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\64_64_A");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 64x64 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\128_128_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\128_128_A");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 128x128 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\256_256_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\256_256_A");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 256x256 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\512_512_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\512_512_A");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 512x512 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\1024_1024_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\1024_1024_A");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 1024x1024 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\2048_2048_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\2048_2048_A");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 2048x2048 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\4096_4096_A");
    B = readJamaMatrixFromFile(".\\src\\test\\resources\\4096_4096_A");
    start = System.currentTimeMillis();
    result = A.mmul(B);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS multiply 4096x4096 is: " + time);

    // LU Decomp
    A = readJamaMatrixFromFile(".\\src\\test\\resources\\2_2_A");
    Decompose lucalc = new Decompose();
    start = System.currentTimeMillis();
    Decompose.LUDecomposition<DoubleMatrix> resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 2x2 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\4_4_A");
    // Decompose lucalc = new Decompose();
    start = System.currentTimeMillis();
    resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 4x4 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\8_8_A");
    start = System.currentTimeMillis();
    resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 8x8 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\16_16_A");
    // Decompose lucalc = new Decompose();
    start = System.currentTimeMillis();
    resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 16x16 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\32_32_A");
    start = System.currentTimeMillis();
    resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 32x32 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\64_64_A");
    // Decompose lucalc = new Decompose();
    start = System.currentTimeMillis();
    resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 64x64 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\128_128_A");
    start = System.currentTimeMillis();
    resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 128x128 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\256_256_A");
    // Decompose lucalc = new Decompose();
    start = System.currentTimeMillis();
    resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 256x256 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\512_512_A");
    start = System.currentTimeMillis();
    resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 512x512 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\1024_1024_A");
    // Decompose lucalc = new Decompose();
    start = System.currentTimeMillis();
    resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 1024x1024 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\2048_2048_A");
    start = System.currentTimeMillis();
    resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 2048x2048 is: " + time);

    A = readJamaMatrixFromFile(".\\src\\test\\resources\\4096_4096_A");
    start = System.currentTimeMillis();
    resultLu = lucalc.lu(A);
    end = System.currentTimeMillis();
    time = end - start;
    System.out.println("Time for JBLAS LU 4096x4096 is: " + time);
  }