private static void modi(DoubleMatrix syndrome, int radix) {
   for (int i = 0; i < syndrome.getRows(); i++) {
     for (int j = 0; j < syndrome.getColumns(); j++) {
       syndrome.put(i, j, ((int) syndrome.get(i, j)) % radix);
     }
   }
 }
  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);
      }*/
    }
  }
  private void learn(
      DoubleMatrix trainingExample,
      DoubleMatrix result,
      double learningFactor,
      double momentum,
      List<DoubleMatrix> previousModifications,
      EvaluationContext evalCtx) {
    List<Layer> layers = getLayers();
    Layer outputLayer = layers.get(layers.size() - 1);

    if (outputLayer.getLayerSize() != result.getRows()) {
      throw new IllegalArgumentException("wrong vector size!");
    }

    evalCtx.resetContext();
    DoubleMatrix output = evaluate(trainingExample, evalCtx);
    modifyWeights(
        trainingExample, result, output, learningFactor, momentum, previousModifications, evalCtx);
  }
Beispiel #4
0
  public StateSpaceModel(
      DoubleMatrix state_transition_matrix,
      DoubleMatrix observation_matrix,
      DoubleMatrix transition_covariance_matrix,
      DoubleMatrix observation_covariance_matrix,
      DoubleMatrix initial_state_mean,
      DoubleMatrix initial_state_covariance,
      DoubleMatrix[] observations) {
    dimension_of_states_ = observation_matrix.getColumns();
    dimension_of_observations_ = observation_matrix.getRows();
    observation_matrix_ref_ = observation_matrix;

    if (!state_transition_matrix.isSquare()
        || state_transition_matrix.getRows() != dimension_of_states_) {
      throw new MatrixDimensionMismatchException(
          state_transition_matrix.getRows(),
          state_transition_matrix.getColumns(),
          dimension_of_states_,
          dimension_of_states_);
    }
    state_transition_matrix_ref_ = state_transition_matrix;

    if (!transition_covariance_matrix.isSquare()
        || transition_covariance_matrix.getRows() != dimension_of_states_) {
      throw new MatrixDimensionMismatchException(
          transition_covariance_matrix.getRows(),
          transition_covariance_matrix.getColumns(),
          dimension_of_states_,
          dimension_of_states_);
    }
    transition_covariance_matrix_ref_ = transition_covariance_matrix;

    if (!observation_covariance_matrix.isSquare()
        || observation_covariance_matrix.getRows() != dimension_of_observations_) {
      throw new MatrixDimensionMismatchException(
          observation_covariance_matrix.getRows(),
          observation_covariance_matrix.getColumns(),
          dimension_of_observations_,
          dimension_of_observations_);
    }
    observation_covariance_matrix_ref_ = observation_covariance_matrix;

    if (initial_state_mean.getRows() != dimension_of_states_
        || initial_state_mean.getColumns() != 1) {
      throw new MatrixDimensionMismatchException(
          initial_state_mean.getRows(), initial_state_mean.getColumns(), dimension_of_states_, 1);
    }
    initial_state_mean_ref_ = initial_state_mean;

    if (!initial_state_covariance.isSquare()
        || initial_state_covariance.getRows() != dimension_of_states_) {
      throw new MatrixDimensionMismatchException(
          initial_state_covariance.getRows(),
          initial_state_covariance.getColumns(),
          dimension_of_states_,
          dimension_of_states_);
    }
    initial_state_covariance_ref_ = initial_state_covariance;

    number_of_observations_ = observations.length;

    observations_ref_ = observations;

    estimated_state_means_ = new DoubleMatrix[number_of_observations_];
    estimated_state_covariances_ = new DoubleMatrix[number_of_observations_];
    predicted_observation_means_ = new DoubleMatrix[number_of_observations_];
    predicted_observation_covariances_ = new DoubleMatrix[number_of_observations_];

    estimated_means_ = new DoubleMatrix[number_of_observations_];
    estimated_covariances_ = new DoubleMatrix[number_of_observations_];

    UpdateFilteredStates();
    CalculateLogLikelihood();
  }
Beispiel #5
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();
  }
Beispiel #6
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();
  }