public static void DFS(
      DoubleMatrix A, DoubleMatrix d, DoubleMatrix g, ArrayList[] V, int vertNum) {
    int krawedzie = 0;
    for (int i = 0; i <= vertNum; i++) {
      krawedzie += V[i].size();
    }

    krawedzie /= 2;
    // System.out.println("A wymiar: " + A.columns + " rows: "+A.rows);

    int t = 0;

    VertexState state[] = new VertexState[(d.rows - 1) * d.rows / 2]; // tyle stanów

    for (int i = 0; i < d.rows - 1; i++) {
      for (int j = i + 1; j < d.columns; j++) {
        for (int x = 0; x < state.length; x++) {
          state[x] = VertexState.White; // na początku białe
        }
        g.put(t, 0, d.get(i, j));
        runDFS(i, j, state, d, V, vertNum);
        for (int ii = 0; ii < krawedzie; ii++) {
          if (state[ii] == VertexState.Black) {
            A.put(t, ii, 1);
          }
        }

        t++;
      }
    }
    System.out.println(g);
    System.out.println("t:" + t);
    return;
  }
  /**
   * 求广义逆矩阵 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;
  }
Exemple #3
0
 /**
  * Loads ground truth responses
  *
  * @param groundTruth is a Map from questions to responses
  */
 public void setGroundTruth(Map<TypeQ, TypeR> groundTruth) {
   log.debug("Setting ground truth...");
   if (!(categToInt != null)) log.error("Result Vector not computed.");
   assert categToInt != null : "Result Vector not computed.";
   DoubleMatrix indicator = DoubleMatrix.zeros(sortedQuestions.size());
   DoubleMatrix gtVec = DoubleMatrix.zeros(sortedQuestions.size());
   int idx = 0;
   for (TypeQ iter : sortedQuestions) {
     if (groundTruth.containsKey(iter)) {
       indicator.put(idx, 1.0d);
       gtVec.put(idx, categToInt.get(groundTruth.get(iter)));
     }
     idx++;
   }
   groundTruthVector = new Pair<DoubleMatrix, DoubleMatrix>(gtVec, indicator);
 }
  public static void main(String argv[]) {
    modshogun.init_shogun_with_defaults();
    int dim = 7;

    DoubleMatrix data = DoubleMatrix.rand(dim, dim);
    RealFeatures feats = new RealFeatures(data);
    DoubleMatrix data_T = data.transpose();
    DoubleMatrix symdata = data.add(data_T);

    int cols = (1 + dim) * dim / 2;
    DoubleMatrix lowertriangle = DoubleMatrix.zeros(1, cols);
    int count = 0;
    for (int i = 0; i < dim; i++) {
      for (int j = 0; j < dim; j++) {
        if (j <= i) {
          lowertriangle.put(0, count++, symdata.get(i, j));
        }
      }
    }

    CustomKernel kernel = new CustomKernel();
    kernel.set_triangle_kernel_matrix_from_triangle(lowertriangle);
    DoubleMatrix km_triangletriangle = kernel.get_kernel_matrix();

    kernel.set_triangle_kernel_matrix_from_full(symdata);
    DoubleMatrix km_fulltriangle = kernel.get_kernel_matrix();

    kernel.set_full_kernel_matrix_from_full(data);
    DoubleMatrix km_fullfull = kernel.get_kernel_matrix();

    modshogun.exit_shogun();
  }
  public DoubleMatrix getScoreMatrix(File file) {
    Counter<String> docWords = new Counter<String>();
    try {
      LineIterator iter = FileUtils.lineIterator(file);
      while (iter.hasNext()) {
        Tokenizer t =
            tokenizerFactory.create((new InputHomogenization(iter.nextLine()).transform()));
        while (t.hasMoreTokens()) {
          docWords.incrementCount(t.nextToken(), 1.0);
        }
      }

      iter.close();
    } catch (IOException e) {
      throw new IllegalStateException("Unable to read file", e);
    }
    DoubleMatrix ret = new DoubleMatrix(1, currVocab.size());

    for (int i = 0; i < currVocab.size(); i++) {
      if (docWords.getCount(currVocab.get(i).toString()) > 0) {
        ret.put(i, wordScores.getCount(currVocab.get(i).toString()));
      }
    }

    return ret;
  }
 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);
     }
   }
 }
Exemple #7
0
 /**
  * Loads tune responses
  *
  * @param tuneSet is a Map from questions to responses
  */
 public void setTune(Map<TypeQ, TypeR> tuneSet) {
   log.debug("Setting tune set...");
   if (!(categToInt != null)) log.error("Result Vector not computed.");
   assert categToInt != null : "Result Vector not computed.";
   DoubleMatrix indicator = DoubleMatrix.zeros(sortedQuestions.size());
   DoubleMatrix tuneVec = DoubleMatrix.zeros(sortedQuestions.size());
   int idx = 0;
   for (TypeQ iter : sortedQuestions) {
     if (tuneSet.containsKey(iter)) {
       indicator.put(idx, 1.0d);
       tuneVec.put(idx, categToInt.get(tuneSet.get(iter)));
     }
     idx++;
   }
   tuneVector = new Pair<DoubleMatrix, DoubleMatrix>(tuneVec, indicator);
 }
  /**
   * 对角线增加值
   *
   * @param matrix
   * @throws Exception
   */
  private void addPositiveValue(DoubleMatrix matrix) {
    int m = matrix.rows;

    if (matrix.columns != m) return;
    for (int i = 0; i < m; i++) {
      matrix.put(i, i, matrix.get(i, i) + Math.random());
    }
  }
 /**
  * 求逆矩阵
  *
  * @param mt
  * @return
  */
 public DoubleMatrix inverse(DoubleMatrix mt) {
   int m = mt.rows;
   DoubleMatrix E = DoubleMatrix.zeros(m, m);
   for (int i = 0; i < m; i++) {
     E.put(i, i, 1);
   }
   return Solve.solve(mt, E);
 }
 /**
  * Transforms the matrix
  *
  * @param text
  * @return
  */
 @Override
 public DoubleMatrix transform(String text) {
   Tokenizer tokenizer = tokenizerFactory.create(text);
   List<String> tokens = tokenizer.getTokens();
   DoubleMatrix input = new DoubleMatrix(1, vocab.size());
   for (int i = 0; i < tokens.size(); i++) {
     int idx = vocab.indexOf(tokens.get(i));
     if (vocab.indexOf(tokens.get(i)) >= 0) input.put(idx, wordCounts.getCount(tokens.get(i)));
   }
   return input;
 }
    public void reduce(
        IntWritable sameNum,
        Iterator<Text> data,
        OutputCollector<Text, jBLASArrayWritable> output,
        Reporter reporter)
        throws IOException {
      int totalBatchCount = exampleCount / batchSize;

      DoubleMatrix weights = DoubleMatrix.randn(hiddenNodes, visibleNodes);
      DoubleMatrix hbias = DoubleMatrix.zeros(hiddenNodes);
      DoubleMatrix vbias = DoubleMatrix.zeros(visibleNodes);
      DoubleMatrix label = DoubleMatrix.zeros(1);
      DoubleMatrix hidden_chain = null;
      DoubleMatrix vdata = DoubleMatrix.zeros(batchSize, visibleNodes);

      ArrayList<DoubleMatrix> outputmatricies = new ArrayList<DoubleMatrix>();
      outputmatricies.add(weights);
      outputmatricies.add(hbias);
      outputmatricies.add(vbias);
      outputmatricies.add(label);
      outputmatricies.add(vdata);
      outputmatricies.add(hidden_chain);

      int j;
      for (int i = 0; i < totalBatchCount; i++) {
        j = 0;
        while (data.hasNext() && j < batchSize) {
          j++;
          StringTokenizer tk = new StringTokenizer(data.next().toString());
          label.put(0, Double.parseDouble(tk.nextToken()));
          String image = tk.nextToken();
          for (int k = 0; k < image.length(); k++) {
            Integer val = new Integer(image.charAt(k));
            vdata.put(j, k, val.doubleValue());
          }
          dataArray = new jBLASArrayWritable(outputmatricies);
          batchID.set("1\t" + i);
          output.collect(batchID, dataArray);
        }
      }
    }
  public static DoubleMatrix conv2d(DoubleMatrix input, DoubleMatrix kernel, Type type) {

    DoubleMatrix xShape = new DoubleMatrix(1, 2);
    xShape.put(0, input.rows);
    xShape.put(1, input.columns);

    DoubleMatrix yShape = new DoubleMatrix(1, 2);
    yShape.put(0, kernel.rows);
    yShape.put(1, kernel.columns);

    DoubleMatrix zShape = xShape.addi(yShape).subi(1);
    int retRows = (int) zShape.get(0);
    int retCols = (int) zShape.get(1);

    ComplexDoubleMatrix fftInput = complexDisceteFourierTransform(input, retRows, retCols);
    ComplexDoubleMatrix fftKernel = complexDisceteFourierTransform(kernel, retRows, retCols);
    ComplexDoubleMatrix mul = fftKernel.muli(fftInput);
    ComplexDoubleMatrix retComplex = complexInverseDisceteFourierTransform(mul);
    DoubleMatrix ret = retComplex.getReal();

    if (type == Type.VALID) {

      DoubleMatrix validShape = xShape.subi(yShape).addi(1);

      DoubleMatrix start = zShape.subi(validShape).divi(2);
      DoubleMatrix end = start.addi(validShape);
      if (start.get(0) < 1 || start.get(1) < 1)
        throw new IllegalStateException("Illegal row index " + start);
      if (end.get(0) < 1 || end.get(1) < 1)
        throw new IllegalStateException("Illegal column index " + end);

      ret =
          ret.get(
              RangeUtils.interval((int) start.get(0), (int) end.get(0)),
              RangeUtils.interval((int) start.get(1), (int) end.get(1)));
    }

    return ret;
  }
  /**
   * Vectorizes the passed in text treating it as one document
   *
   * @param text the text to vectorize
   * @param label the label of the text
   * @return a dataset with a applyTransformToDestination of weights(relative to impl; could be word
   *     counts or tfidf scores)
   */
  @Override
  public DataSet vectorize(String text, String label) {
    Tokenizer tokenizer = tokenizerFactory.create(text);
    List<String> tokens = tokenizer.getTokens();
    DoubleMatrix input = new DoubleMatrix(1, vocab.size());
    for (int i = 0; i < tokens.size(); i++) {
      int idx = vocab.indexOf(tokens.get(i));
      if (vocab.indexOf(tokens.get(i)) >= 0) input.put(idx, wordCounts.getCount(tokens.get(i)));
    }

    DoubleMatrix labelMatrix = MatrixUtil.toOutcomeVector(labels.indexOf(label), labels.size());
    return new DataSet(input, labelMatrix);
  }
Exemple #14
0
 /** Computes results as a vector of type DoubleMatrix */
 public void computeComparableResultVector() {
   log.info("Computing comparable result vector...");
   if (!(sortedRePrPairs != null))
     log.error("Attempted to compute results vector before results.");
   assert sortedRePrPairs != null : "Attempted to compute results vector before results.";
   categToInt = new HashMap<TypeR, Integer>();
   resultVector = DoubleMatrix.zeros(sortedQuestions.size());
   categoriesMat = DoubleMatrix.zeros(responseCategories.size());
   int temp = 1;
   for (TypeR iter : responseCategories) {
     categToInt.put(iter, temp);
     categoriesMat.put(temp - 1, temp);
     temp++;
   }
   if (log.isDebugEnabled()) log.debug("Computed map from categories to integers:\n" + categToInt);
   temp = 0;
   for (Pair<TypeR, Double> iter : sortedRePrPairs) {
     resultVector.put(temp, categToInt.get(iter.getFirst()));
     temp++;
   }
   if (log.isDebugEnabled()) log.debug("Computed results vector:\n" + resultVector);
   log.info("Computed result vector.");
 }
 public static DoubleMatrix readFileIntoMatrix(String filename, char delimiter)
     throws IOException {
   File csvData = new File(filename);
   CSVFormat format = CSVFormat.DEFAULT.withHeader().withDelimiter(delimiter);
   CSVParser parser = CSVParser.parse(csvData, StandardCharsets.UTF_8, format);
   int row = 0;
   List<CSVRecord> records = parser.getRecords();
   DoubleMatrix x = new DoubleMatrix(records.size(), records.get(0).size());
   for (CSVRecord csvRecord : records) {
     for (int column = 0; column < csvRecord.size(); column++) {
       String s = csvRecord.get(column);
       x.put(row, column, Double.valueOf(s));
     }
     row++;
   }
   return x;
 }
Exemple #16
0
 /** 文件载入矩阵 */
 private DoubleMatrix loadMatrix(String trainSetPath, int rowNum, int colNum) throws IOException {
   BufferedReader br = new BufferedReader(new FileReader(new File(trainSetPath)));
   // 第一行为文件信息
   DoubleMatrix matrix = new DoubleMatrix(rowNum, colNum);
   String lineStr = "";
   for (int i = 0; i < rowNum; i++) {
     lineStr = br.readLine();
     if (lineStr.startsWith("#") || "".equals(lineStr)) {
       continue;
     }
     String[] strings = lineStr.split(",");
     for (int j = 0; j < colNum; j++) {
       matrix.put(i, j, Double.parseDouble(strings[j]));
     }
   }
   br.close();
   return matrix;
 }
Exemple #17
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("模型评估完毕………………");
  }
Exemple #18
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);
  }
Exemple #19
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;
  }
    // TODO: DOUBLECHECK EVERYTHING
    @Override
    public void map(Text key, jBLASArrayWritable input, GibbsSampling.Context context)
        throws IOException, InterruptedException {
      /* *******************************************************************/
      /* initialize all memory we're going to use during the process		 */
      long start_time = System.nanoTime();
      ArrayList<DoubleMatrix> data = input.getData();
      label = data.get(4);
      v_data = data.get(5);

      // check to see if we are in the first layer or there are layers beneath us we must sample
      // from
      if (data.size() > 6) {
        int prelayer = (data.size() - 6) / 3;
        DoubleMatrix[] preWeights = new DoubleMatrix[prelayer],
            preHbias = new DoubleMatrix[prelayer],
            preVbias = new DoubleMatrix[prelayer];
        for (int i = 0; i < prelayer; i++) {
          preWeights[i] = data.get(6 + i * 3);
          preHbias[i] = data.get(7 + i * 3);
          preVbias[i] = data.get(8 + i * 3);
        }
        DoubleMatrix vnew = null;
        for (int i = 0; i < prelayer; i++) {
          weights = preWeights[i];
          vbias = preVbias[i];
          hbias = preHbias[i];
          vnew = sample_h_from_v(i == 0 ? v_data : vnew);
        }
        v_data = vnew;
      }

      weights = data.get(0);
      hbias = data.get(1);
      hiddenChain = data.get(2);
      vbias = data.get(3);

      // check if we need to attach labels to the observed variables
      if (vbias.columns != v_data.columns) {
        DoubleMatrix labels = DoubleMatrix.zeros(1, classCount);
        int labelNum = (new Double(label.get(0))).intValue();
        labels.put(labelNum, 1.0);
        v_data = DoubleMatrix.concatHorizontally(v_data, labels);
      }

      w1 = DoubleMatrix.zeros(weights.rows, weights.columns);
      hb1 = DoubleMatrix.zeros(hbias.rows, hbias.columns);
      vb1 = DoubleMatrix.zeros(vbias.rows, vbias.columns);

      /* ********************************************************************/
      // sample hidden state to get positive phase
      // if empty, use it as the start of the chain
      // or use persistent hidden state from pCD

      DoubleMatrix phaseSample = sample_h_from_v(v_data);
      h1_data = new DoubleMatrix();
      v1_data = new DoubleMatrix();

      if (hiddenChain == null) {
        data.set(2, new DoubleMatrix(hbias.rows, hbias.columns));
        hiddenChain = data.get(2);
        hiddenChain.copy(phaseSample);
        h1_data.copy(phaseSample);
      } else {
        h1_data.copy(hiddenChain);
      }
      // run Gibbs chain for k steps
      for (int j = 0; j < gibbsSteps; j++) {
        v1_data.copy(sample_v_from_h(h1_data));
        h1_data.copy(sample_h_from_v(v1_data));
      }
      DoubleMatrix hprob = propup(v1_data);
      weight_contribution(hiddenChain, v_data, hprob, v1_data);
      hiddenChain.copy(h1_data);

      data.get(0).copy(w1);
      data.get(1).copy(hb1);
      data.get(2).copy(hiddenChain);
      data.get(3).copy(vb1);

      jBLASArrayWritable outputmatrix = new jBLASArrayWritable(data);
      context.write(key, outputmatrix);
      log.info("Job completed in: " + (System.nanoTime() - start_time) / (1E6) + " ms");
    }
Exemple #21
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);
  }
Exemple #22
0
  public static DoubleMatrix polyval(
      final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix coeff, int degree) {

    if (!x.isColumnVector()) {
      logger.warn("polyValGrid: require (x) standing data vectors!");
      throw new IllegalArgumentException("polyval functions require (x) standing data vectors!");
    }

    if (!y.isColumnVector()) {
      logger.warn("polyValGrid: require (y) standing data vectors!");
      throw new IllegalArgumentException("polyval functions require (y) standing data vectors!");
    }

    if (!coeff.isColumnVector()) {
      logger.warn("polyValGrid: require (coeff) standing data vectors!");
      throw new IllegalArgumentException(
          "polyval functions require (coeff) standing data vectors!");
    }

    if (degree < -1) {
      logger.warn("polyValGrid: degree < -1 ????");
    }

    if (x.length > y.length) {
      logger.warn("polValGrid: x larger than y, while optimized for y larger x");
    }

    if (degree == -1) {
      degree = degreeFromCoefficients(coeff.length);
    }

    // evaluate polynomial //
    DoubleMatrix result = new DoubleMatrix(x.length, y.length);
    int i;
    int j;
    double c00,
        c10,
        c01,
        c20,
        c11,
        c02,
        c30,
        c21,
        c12,
        c03,
        c40,
        c31,
        c22,
        c13,
        c04,
        c50,
        c41,
        c32,
        c23,
        c14,
        c05;

    switch (degree) {
      case 0:
        result.put(0, 0, coeff.get(0, 0));
        break;
      case 1:
        c00 = coeff.get(0, 0);
        c10 = coeff.get(1, 0);
        c01 = coeff.get(2, 0);
        for (j = 0; j < result.columns; j++) {
          double c00pc01y1 = c00 + c01 * y.get(j, 0);
          for (i = 0; i < result.rows; i++) {
            result.put(i, j, c00pc01y1 + c10 * x.get(i, 0));
          }
        }
        break;
      case 2:
        c00 = coeff.get(0, 0);
        c10 = coeff.get(1, 0);
        c01 = coeff.get(2, 0);
        c20 = coeff.get(3, 0);
        c11 = coeff.get(4, 0);
        c02 = coeff.get(5, 0);
        for (j = 0; j < result.columns; j++) {
          double y1 = y.get(j, 0);
          double c00pc01y1 = c00 + c01 * y1;
          double c02y2 = c02 * Math.pow(y1, 2);
          double c11y1 = c11 * y1;
          for (i = 0; i < result.rows; i++) {
            double x1 = x.get(i, 0);
            result.put(i, j, c00pc01y1 + c10 * x1 + c20 * Math.pow(x1, 2) + c11y1 * x1 + c02y2);
          }
        }
        break;
      case 3:
        c00 = coeff.get(0, 0);
        c10 = coeff.get(1, 0);
        c01 = coeff.get(2, 0);
        c20 = coeff.get(3, 0);
        c11 = coeff.get(4, 0);
        c02 = coeff.get(5, 0);
        c30 = coeff.get(6, 0);
        c21 = coeff.get(7, 0);
        c12 = coeff.get(8, 0);
        c03 = coeff.get(9, 0);
        for (j = 0; j < result.columns; j++) {
          double y1 = y.get(j, 0);
          double y2 = Math.pow(y1, 2);
          double c00pc01y1 = c00 + c01 * y1;
          double c02y2 = c02 * y2;
          double c11y1 = c11 * y1;
          double c21y1 = c21 * y1;
          double c12y2 = c12 * y2;
          double c03y3 = c03 * y1 * y2;
          for (i = 0; i < result.rows; i++) {
            double x1 = x.get(i, 0);
            double x2 = Math.pow(x1, 2);
            result.put(
                i,
                j,
                c00pc01y1
                    + c10 * x1
                    + c20 * x2
                    + c11y1 * x1
                    + c02y2
                    + c30 * x1 * x2
                    + c21y1 * x2
                    + c12y2 * x1
                    + c03y3);
          }
        }
        break;

      case 4:
        c00 = coeff.get(0, 0);
        c10 = coeff.get(1, 0);
        c01 = coeff.get(2, 0);
        c20 = coeff.get(3, 0);
        c11 = coeff.get(4, 0);
        c02 = coeff.get(5, 0);
        c30 = coeff.get(6, 0);
        c21 = coeff.get(7, 0);
        c12 = coeff.get(8, 0);
        c03 = coeff.get(9, 0);
        c40 = coeff.get(10, 0);
        c31 = coeff.get(11, 0);
        c22 = coeff.get(12, 0);
        c13 = coeff.get(13, 0);
        c04 = coeff.get(14, 0);
        for (j = 0; j < result.columns; j++) {
          double y1 = y.get(j, 0);
          double y2 = Math.pow(y1, 2);
          double c00pc01y1 = c00 + c01 * y1;
          double c02y2 = c02 * y2;
          double c11y1 = c11 * y1;
          double c21y1 = c21 * y1;
          double c12y2 = c12 * y2;
          double c03y3 = c03 * y1 * y2;
          double c31y1 = c31 * y1;
          double c22y2 = c22 * y2;
          double c13y3 = c13 * y2 * y1;
          double c04y4 = c04 * y2 * y2;
          for (i = 0; i < result.rows; i++) {
            double x1 = x.get(i, 0);
            double x2 = Math.pow(x1, 2);
            result.put(
                i,
                j,
                c00pc01y1
                    + c10 * x1
                    + c20 * x2
                    + c11y1 * x1
                    + c02y2
                    + c30 * x1 * x2
                    + c21y1 * x2
                    + c12y2 * x1
                    + c03y3
                    + c40 * x2 * x2
                    + c31y1 * x2 * x1
                    + c22y2 * x2
                    + c13y3 * x1
                    + c04y4);
          }
        }
        break;
      case 5:
        c00 = coeff.get(0, 0);
        c10 = coeff.get(1, 0);
        c01 = coeff.get(2, 0);
        c20 = coeff.get(3, 0);
        c11 = coeff.get(4, 0);
        c02 = coeff.get(5, 0);
        c30 = coeff.get(6, 0);
        c21 = coeff.get(7, 0);
        c12 = coeff.get(8, 0);
        c03 = coeff.get(9, 0);
        c40 = coeff.get(10, 0);
        c31 = coeff.get(11, 0);
        c22 = coeff.get(12, 0);
        c13 = coeff.get(13, 0);
        c04 = coeff.get(14, 0);
        c50 = coeff.get(15, 0);
        c41 = coeff.get(16, 0);
        c32 = coeff.get(17, 0);
        c23 = coeff.get(18, 0);
        c14 = coeff.get(19, 0);
        c05 = coeff.get(20, 0);
        for (j = 0; j < result.columns; j++) {
          double y1 = y.get(j, 0);
          double y2 = Math.pow(y1, 2);
          double y3 = y2 * y1;
          double c00pc01y1 = c00 + c01 * y1;
          double c02y2 = c02 * y2;
          double c11y1 = c11 * y1;
          double c21y1 = c21 * y1;
          double c12y2 = c12 * y2;
          double c03y3 = c03 * y3;
          double c31y1 = c31 * y1;
          double c22y2 = c22 * y2;
          double c13y3 = c13 * y3;
          double c04y4 = c04 * y2 * y2;
          double c41y1 = c41 * y1;
          double c32y2 = c32 * y2;
          double c23y3 = c23 * y3;
          double c14y4 = c14 * y2 * y2;
          double c05y5 = c05 * y3 * y2;
          for (i = 0; i < result.rows; i++) {
            double x1 = x.get(i, 0);
            double x2 = Math.pow(x1, 2);
            double x3 = x1 * x2;
            result.put(
                i,
                j,
                c00pc01y1
                    + c10 * x1
                    + c20 * x2
                    + c11y1 * x1
                    + c02y2
                    + c30 * x3
                    + c21y1 * x2
                    + c12y2 * x1
                    + c03y3
                    + c40 * x2 * x2
                    + c31y1 * x3
                    + c22y2 * x2
                    + c13y3 * x1
                    + c04y4
                    + c50 * x3 * x2
                    + c41y1 * x2 * x2
                    + c32y2 * x3
                    + c23y3 * x2
                    + c14y4 * x1
                    + c05y5);
          }
        }
        break;

        // TODO: solve up to 5 efficiently, do rest in loop
      default:
        for (j = 0; j < result.columns; j++) {
          double yy = y.get(j, 0);
          for (i = 0; i < result.rows; i++) {
            double xx = x.get(i, 0);
            result.put(i, j, polyval(xx, yy, coeff, degree));
          }
        }
    } // switch degree

    return result;
  }
Exemple #23
0
  public static void exportResult(
      TrueSolutionCTM trueSolutionCTM,
      TrueSolution[] trueSolution,
      TrueSolution[] trueSolution1,
      TrueSolution[] trueSolution2,
      int limite,
      String folder) {
    try {

      int bdry = 1; // *set boundary type
      int numSections = trueSolution[0].numSections;
      int numSections1 = trueSolution1[0].numSections;
      int numSections2 = trueSolution2[0].numSections;

      BufferedWriter[] writerSection = new BufferedWriter[numSections];
      BufferedWriter[] writerSection1 = new BufferedWriter[numSections1];
      BufferedWriter[] writerSection2 = new BufferedWriter[numSections2];

      BufferedWriter[] LyapSection = new BufferedWriter[numSections];

      BufferedWriter writerTrue;
      BufferedWriter writerConsensusTerm;

      BufferedWriter writerAvr;
      BufferedWriter writerAvr1;
      BufferedWriter writerAvr2;

      BufferedWriter Error;
      BufferedWriter Error1;
      BufferedWriter Error2;

      BufferedWriter Lyap;

      BufferedWriter[] Mode = new BufferedWriter[numSections];
      BufferedWriter[] Mode1 = new BufferedWriter[numSections1];
      BufferedWriter[] Mode2 = new BufferedWriter[numSections2];
      BufferedWriter[] GammaWrite = new BufferedWriter[numSections];

      BufferedWriter writerDisagreement;
      BufferedWriter writerDisagreement1;
      BufferedWriter writerDisagreement2;

      System.out.print("Beginning of simulation ");

      new File("results/" + folder).mkdir();

      RoadModel[] roadModels = new RoadModel[numSections];
      RoadModel[] roadModels1 = new RoadModel[numSections1];
      RoadModel[] roadModels2 = new RoadModel[numSections2];

      for (int i = 0; i < numSections; i++) {
        trueSolution[i].section = trueSolution[i].setSections();
      }
      for (int i = 0; i < numSections1; i++) {
        trueSolution1[i].section = trueSolution1[i].setSections();
      }
      for (int i = 0; i < numSections2; i++) {
        trueSolution2[i].section = trueSolution2[i].setSections();
      }

      for (int i = 0; i < numSections; i++) {
        roadModels[i] = trueSolution[i].setRoadModels();
      }
      for (int i = 0; i < numSections1; i++) {
        roadModels1[i] = trueSolution1[i].setRoadModels();
      }
      for (int i = 0; i < numSections2; i++) {
        roadModels2[i] = trueSolution2[i].setRoadModels();
      }

      writerTrue =
          new BufferedWriter(new FileWriter(new File("results/" + folder + "/" + "trueState.csv")));
      writerConsensusTerm =
          new BufferedWriter(
              new FileWriter(new File("results/" + folder + "/" + "consensusTerm.csv")));
      writerAvr =
          new BufferedWriter(new FileWriter(new File("results/" + folder + "/" + "writerAvr.csv")));
      writerAvr1 =
          new BufferedWriter(
              new FileWriter(new File("results/" + folder + "/" + "writerAvr1.csv")));
      writerAvr2 =
          new BufferedWriter(
              new FileWriter(new File("results/" + folder + "/" + "writerAvr2.csv")));
      Error = new BufferedWriter(new FileWriter(new File("results/" + folder + "/" + "Error.csv")));
      Error1 =
          new BufferedWriter(new FileWriter(new File("results/" + folder + "/" + "Error1.csv")));
      Error2 =
          new BufferedWriter(new FileWriter(new File("results/" + folder + "/" + "Error2.csv")));
      Lyap =
          new BufferedWriter(new FileWriter(new File("results/" + folder + "/" + "Lyapunov.csv")));
      writerDisagreement =
          new BufferedWriter(
              new FileWriter(new File("results/" + folder + "/" + "Disagreement.csv")));
      writerDisagreement1 =
          new BufferedWriter(
              new FileWriter(new File("results/" + folder + "/" + "Disagreement1.csv")));
      writerDisagreement2 =
          new BufferedWriter(
              new FileWriter(new File("results/" + folder + "/" + "Disagreement2.csv")));

      Estimation[] estimations = new Estimation[numSections];
      Estimation[] estimations1 = new Estimation[numSections1];
      Estimation[] estimations2 = new Estimation[numSections2];

      for (int i = 0; i < numSections; i++) {
        estimations[i] =
            new Estimation(
                roadModels[i],
                "KCF",
                true); // *set the last variable to indicate if consensus is needed
        String S = "results/" + folder + "/" + roadModels[i].nameModel;
        writerSection[i] = new BufferedWriter(new FileWriter(new File(S + ".csv")));
        Mode[i] = new BufferedWriter(new FileWriter(new File(S + "Mode.csv")));
        GammaWrite[i] = new BufferedWriter(new FileWriter(new File(S + "Gamma.csv")));
        LyapSection[i] = new BufferedWriter(new FileWriter(new File(S + "LyapSection.csv")));
      }

      for (int i = 0; i < numSections1; i++) {
        estimations1[i] =
            new Estimation(
                roadModels1[i],
                "KCF",
                false); // *set the last variable to indicate if consensus is needed
        String S = "results/" + folder + "/" + roadModels1[i].nameModel;
        writerSection1[i] = new BufferedWriter(new FileWriter(new File(S + "_1.csv")));
        Mode1[i] = new BufferedWriter(new FileWriter(new File(S + "Mode1.csv")));
      }

      for (int i = 0; i < numSections2; i++) {
        estimations2[i] =
            new Estimation(
                roadModels2[i],
                "KCF",
                false); // *set the last variable to indicate if consensus is needed
        String S = "results/" + folder + "/" + roadModels2[i].nameModel;
        writerSection2[i] = new BufferedWriter(new FileWriter(new File(S + "_2.csv")));
        Mode2[i] = new BufferedWriter(new FileWriter(new File(S + "Mode2.csv")));
      }

      int overlap = roadModels[0].trueSolution.overlapsec;
      int cellsec = roadModels[0].section.cellsec;
      int overlap1 = roadModels1[0].trueSolution.overlapsec;
      int cellsec1 = roadModels1[0].section.cellsec;
      int overlap2 = roadModels2[0].trueSolution.overlapsec;
      int cellsec2 = roadModels2[0].section.cellsec;

      DoubleMatrix I1 = DoubleMatrix.zeros(roadModels[0].section.cellsec, overlap);
      for (int i = 0; i < overlap; i++) {
        I1.put(i, i, 1);
      }
      DoubleMatrix I2 = DoubleMatrix.zeros(roadModels[0].section.cellsec, overlap);
      for (int i = roadModels[0].section.cellsec - overlap;
          i < roadModels[0].section.cellsec;
          i++) {
        I2.put(i, i - (roadModels[0].section.cellsec - overlap), 1);
      }
      DoubleMatrix I123 = DoubleMatrix.concatVertically(I1.transpose(), I2.transpose());
      DoubleMatrix H_hat = I2.transpose();
      for (int i = 0; i < numSections - 2; i++) {
        H_hat = Concat.Diagonal(H_hat, I123);
      }
      H_hat = Concat.Diagonal(H_hat, I1.transpose());
      DoubleMatrix L_tilde =
          DoubleMatrix.zeros((numSections - 1) * 2 * overlap, numSections * cellsec);
      for (int i = 0; i < numSections - 1; i++) {
        for (int j = 0; j < overlap; j++) {
          L_tilde.put(i * (2 * overlap) + j, (i + 1) * (cellsec) + j, 1);
        }
        for (int j = 0; j < overlap; j++) {
          L_tilde.put(i * (2 * overlap) + overlap + j, (i + 1) * (cellsec) - overlap + j, 1);
        }
        for (int j = 0; j < overlap; j++) {
          L_tilde.put(i * (2 * overlap) + j, (i + 1) * (cellsec) - overlap + j, -1);
        }
        for (int j = 0; j < overlap; j++) {
          L_tilde.put(i * (2 * overlap) + overlap + j, (i + 1) * (cellsec) + j, -1);
        }
      }
      DoubleMatrix[] S = new DoubleMatrix[numSections];
      trueSolutionCTM.getMeasurement();
      for (int i = 0; i < numSections; i++) {
        if (i == 0) {
          estimations[i].filter.Ltilde = L_tilde.getRange(i, i + overlap, i, i + 2 * cellsec);

        } else if (i == numSections - 1) {
          estimations[i].filter.Ltilde =
              L_tilde.getRange(
                  (2 * (numSections - 1) - 1) * overlap,
                  (2 * (numSections - 1) - 1) * overlap + overlap,
                  (i - 1) * cellsec,
                  (i + 1) * cellsec);

        } else {
          estimations[i].filter.Ltilde =
              L_tilde.getRange(
                  (2 * i - 1) * overlap,
                  (2 * i + 1) * overlap,
                  (i - 1) * cellsec,
                  (i + 2) * cellsec);
        }
        estimations[i].filter.I1 = I1;
        estimations[i].filter.I2 = I2;
      }

      double[] disagAvg = new double[3];
      double[] errorAvg = new double[3];
      double[] errAvgEntire = new double[3];

      for (int k = 0; k < limite; k++) {
        System.out.println("time step=" + k);
        for (int i = 0; i < trueSolutionCTM.trueStatesCTM.getRows(); i++) {
          writerTrue.write(trueSolutionCTM.trueStatesCTM.get(i, 0) + ",");
        }
        writerTrue.write("\n");
        DoubleMatrix[] mean = new DoubleMatrix[numSections];
        DoubleMatrix[] mean_1 = new DoubleMatrix[numSections1];
        DoubleMatrix[] mean_2 = new DoubleMatrix[numSections2];
        double ErrorAvg = 0;
        double ErrorEntire = 0;
        double ErrorAvg1 = 0;
        double ErrorAvg2 = 0;
        double LyapAvg = 0;

        double[] errorAvgk = new double[3];
        for (int i = 0; i < numSections; i++) {
          mean[i] = estimations[i].getDensityMean();
          if (numSections == 1) {
            for (int j = 0; j < mean[i].length; j++) {
              writerAvr.write(mean[i].get(j) + ",");
              errorAvgk[0] =
                  (mean[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                          * (mean[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                      + errorAvgk[0];
            }
          } else {
            if (i == 0) {
              for (int j = 0; j < mean[i].length - overlap; j++) {
                writerAvr.write(mean[i].get(j) + ",");
                errorAvgk[0] =
                    (mean[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                            * (mean[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                        + errorAvgk[0];
              }
            } else if (i > 0 && i < numSections - 1) {
              for (int j = 0; j < overlap; j++) {
                writerAvr.write(
                    (mean[i].get(j) + mean[i - 1].get(cellsec - overlap + j)) / 2 + ",");
                errorAvgk[0] =
                    ((mean[i].get(j) + mean[i - 1].get(cellsec - overlap + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean[i].length - overlap) + j, 0))
                            * ((mean[i].get(j) + mean[i - 1].get(cellsec - overlap + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean[i].length - overlap) + j, 0))
                        + errorAvgk[0];
              }
              for (int j = 0; j < mean[i].length - 2 * overlap; j++) {
                writerAvr.write(mean[i].get(overlap + j) + ",");
                errorAvgk[0] =
                    (mean[i].get(overlap + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean[i].length - overlap) + overlap + j, 0))
                            * (mean[i].get(overlap + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean[i].length - overlap) + overlap + j, 0))
                        + errorAvgk[0];
              }
            } else if (i == numSections - 1) {
              for (int j = 0; j < overlap; j++) {
                writerAvr.write(
                    (mean[i].get(j) + mean[i - 1].get(cellsec - overlap + j)) / 2 + ",");
                errorAvgk[0] =
                    ((mean[i].get(j) + mean[i - 1].get(cellsec - overlap + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean[i].length - overlap) + j, 0))
                            * ((mean[i].get(j) + mean[i - 1].get(cellsec - overlap + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean[i].length - overlap) + j, 0))
                        + errorAvgk[0];
              }
              for (int j = 0; j < mean[i].length - overlap; j++) {
                writerAvr.write(mean[i].get(overlap + j) + ",");
                errorAvgk[0] =
                    (mean[i].get(overlap + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean[i].length - overlap) + overlap + j, 0))
                            * (mean[i].get(overlap + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean[i].length - overlap) + overlap + j, 0))
                        + errorAvgk[0];
              }
            }
          }

          for (int j = 0; j < mean[i].length; j++) {
            writerSection[i].write(mean[i].get(j) + ",");
          }
          double errorSection =
              (((mean[i].sub(trueSolution[i].trueStates))
                          .transpose()
                          .mmul((mean[i].sub(trueSolution[i].trueStates))))
                      .get(0, 0))
                  / ((double) cellsec);
          Error.write(errorSection + ",");
          ErrorAvg = ErrorAvg + errorSection / ((double) numSections);
          writerSection[i].write("\n");
          double lyapunovSection =
              ((mean[i].sub(trueSolution[i].trueStates)).transpose())
                  .mmul(InverseMatrix.invPoSym(estimations[i].filter.var))
                  .mmul(mean[i].sub(trueSolution[i].trueStates))
                  .get(0, 0);
          double tracevar = 0;
          for (int c = 0; c < mean[i].getRows(); c++) {
            tracevar = tracevar + estimations[i].filter.var.get(c, c);
          }

          LyapSection[i].write(lyapunovSection + ",");
          LyapSection[i].write(tracevar + "\n");
          if (i != 0) {
            LyapAvg = LyapAvg + lyapunovSection / ((double) (numSections - 1));
          }
        }
        errAvgEntire[0] =
            errorAvgk[0] / ((double) (limite * trueSolutionCTM.cells)) + errAvgEntire[0];
        Error.write(ErrorAvg + ",");
        errorAvg[0] = errorAvg[0] + ErrorAvg / ((double) (limite));
        Lyap.write(LyapAvg + "\n");

        for (int i = 0; i < numSections1; i++) {
          mean_1[i] = estimations1[i].getDensityMean();
          if (numSections1 == 1) {
            for (int j = 0; j < mean_1[i].length; j++) {
              writerAvr1.write(mean_1[i].get(j) + ",");
              errorAvgk[1] =
                  (mean_1[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                          * (mean_1[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                      + errorAvgk[1];
            }
          } else {
            if (i == 0) {
              for (int j = 0; j < mean_1[i].length - overlap1; j++) {
                writerAvr1.write(mean_1[i].get(j) + ",");
                errorAvgk[1] =
                    (mean_1[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                            * (mean_1[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                        + errorAvgk[1];
              }
            } else if (i > 0 && i < numSections1 - 1) {
              for (int j = 0; j < overlap1; j++) {
                writerAvr1.write(
                    (mean_1[i].get(j) + mean_1[i - 1].get(cellsec1 - overlap1 + j)) / 2 + ",");
                errorAvgk[1] =
                    ((mean_1[i].get(j) + mean_1[i - 1].get(cellsec1 - overlap1 + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_1[i].length - overlap1) + j, 0))
                            * ((mean_1[i].get(j) + mean_1[i - 1].get(cellsec1 - overlap1 + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_1[i].length - overlap1) + j, 0))
                        + errorAvgk[1];
              }
              for (int j = 0; j < mean_1[i].length - 2 * overlap1; j++) {
                writerAvr1.write(mean_1[i].get(overlap1 + j) + ",");
                errorAvgk[1] =
                    (mean_1[i].get(overlap1 + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_1[i].length - overlap1) + overlap1 + j, 0))
                            * (mean_1[i].get(overlap1 + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_1[i].length - overlap1) + overlap1 + j, 0))
                        + errorAvgk[1];
              }
            } else if (i == numSections1 - 1) {
              for (int j = 0; j < overlap1; j++) {
                writerAvr1.write(
                    (mean_1[i].get(j) + mean_1[i - 1].get(cellsec1 - overlap1 + j)) / 2 + ",");
                errorAvgk[1] =
                    ((mean_1[i].get(j) + mean_1[i - 1].get(cellsec1 - overlap1 + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_1[i].length - overlap1) + j, 0))
                            * ((mean_1[i].get(j) + mean_1[i - 1].get(cellsec1 - overlap1 + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_1[i].length - overlap1) + j, 0))
                        + errorAvgk[1];
              }
              for (int j = 0; j < mean_1[i].length - overlap1; j++) {
                writerAvr1.write(mean_1[i].get(overlap1 + j) + ",");
                errorAvgk[1] =
                    (mean_1[i].get(overlap1 + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_1[i].length - overlap1) + overlap1 + j, 0))
                            * (mean_1[i].get(overlap1 + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_1[i].length - overlap1) + overlap1 + j, 0))
                        + errorAvgk[1];
              }
            }
          }
          for (int j = 0; j < mean_1[i].length; j++) {
            writerSection1[i].write(mean_1[i].get(j) + ",");
          }
          double errorSection1 =
              (((mean_1[i].sub(trueSolution1[i].trueStates).transpose())
                          .mmul((mean_1[i].sub(trueSolution1[i].trueStates))))
                      .get(0, 0))
                  / ((double) cellsec1);
          Error1.write(errorSection1 + ",");
          ErrorAvg1 = ErrorAvg1 + errorSection1 / ((double) numSections1);
          writerSection1[i].write("\n");
        }
        Error1.write(ErrorAvg1 + ",");
        errorAvg[1] = errorAvg[1] + ErrorAvg1 / ((double) (limite));
        errAvgEntire[1] =
            errorAvgk[1] / ((double) (limite * trueSolutionCTM.cells)) + errAvgEntire[1];

        for (int i = 0; i < numSections2; i++) {
          mean_2[i] = estimations2[i].getDensityMean();
          if (numSections2 == 1) {
            for (int j = 0; j < mean_2[i].length; j++) {
              writerAvr2.write(mean_2[i].get(j) + ",");
              errorAvgk[2] =
                  (mean_2[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                          * (mean_2[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                      + errorAvgk[2];
            }
          } else {
            if (i == 0) {
              for (int j = 0; j < mean_2[i].length - overlap2; j++) {
                writerAvr2.write(mean_2[i].get(j) + ",");
                errorAvgk[2] =
                    (mean_2[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                            * (mean_2[i].get(j) - trueSolutionCTM.trueStatesCTM.get(j, 0))
                        + errorAvgk[2];
              }
            } else if (i > 0 && i < numSections2 - 1) {
              for (int j = 0; j < overlap2; j++) {
                writerAvr2.write(
                    (mean_2[i].get(j) + mean_2[i - 1].get(cellsec2 - overlap2 + j)) / 2 + ",");
                errorAvgk[2] =
                    ((mean_2[i].get(j) + mean_2[i - 1].get(cellsec2 - overlap2 + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_2[i].length - overlap2) + j, 0))
                            * ((mean_2[i].get(j) + mean_2[i - 1].get(cellsec2 - overlap2 + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_2[i].length - overlap2) + j, 0))
                        + errorAvgk[2];
              }
              for (int j = 0; j < mean_2[i].length - 2 * overlap2; j++) {
                writerAvr2.write(mean_2[i].get(overlap2 + j) + ",");
                errorAvgk[2] =
                    (mean_2[i].get(overlap2 + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_2[i].length - overlap2) + overlap2 + j, 0))
                            * (mean_2[i].get(overlap2 + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_2[i].length - overlap2) + overlap2 + j, 0))
                        + errorAvgk[2];
              }
            } else if (i == numSections2 - 1) {
              for (int j = 0; j < overlap2; j++) {
                writerAvr2.write(
                    (mean_2[i].get(j) + mean_2[i - 1].get(cellsec2 - overlap2 + j)) / 2 + ",");
                errorAvgk[2] =
                    ((mean_2[i].get(j) + mean_2[i - 1].get(cellsec2 - overlap2 + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_2[i].length - overlap2) + j, 0))
                            * ((mean_2[i].get(j) + mean_2[i - 1].get(cellsec2 - overlap2 + j)) / 2
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_2[i].length - overlap2) + j, 0))
                        + errorAvgk[2];
              }
              for (int j = 0; j < mean_2[i].length - overlap2; j++) {
                writerAvr2.write(mean_2[i].get(overlap2 + j) + ",");
                errorAvgk[2] =
                    (mean_2[i].get(overlap2 + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_2[i].length - overlap2) + overlap2 + j, 0))
                            * (mean_2[i].get(overlap2 + j)
                                - trueSolutionCTM.trueStatesCTM.get(
                                    i * (mean_2[i].length - overlap2) + overlap2 + j, 0))
                        + errorAvgk[2];
              }
            }
          }
          for (int j = 0; j < mean_2[i].length; j++) {
            writerSection2[i].write(mean_2[i].get(j) + ",");
          }
          double errorSection2 =
              (((mean_2[i].sub(trueSolution2[i].trueStates))
                          .transpose()
                          .mmul((mean_2[i].sub(trueSolution2[i].trueStates))))
                      .get(0, 0))
                  / ((double) (cellsec2));
          Error2.write(errorSection2 + ",");
          ErrorAvg2 = ErrorAvg2 + errorSection2 / ((double) numSections2);
          writerSection2[i].write("\n");
        }
        Error2.write(ErrorAvg2 + ",");
        errorAvg[2] = errorAvg[2] + ErrorAvg2 / ((double) (limite));
        errAvgEntire[2] =
            errorAvgk[2] / ((double) (limite * trueSolutionCTM.cells)) + errAvgEntire[2];

        writerAvr.write("\n");
        writerAvr1.write("\n");
        writerAvr2.write("\n");

        Error.write("\n");
        Error1.write("\n");
        Error2.write("\n");

        Section[] secs = new Section[numSections];
        Section[] secs1 = new Section[numSections1];
        Section[] secs2 = new Section[numSections2];

        for (int i = 0; i < numSections; i++) {
          secs[i] = trueSolution[i].setSections(); // every step, update mode
        }
        for (int i = 0; i < numSections1; i++) {
          secs1[i] = trueSolution1[i].setSections();
        }
        for (int i = 0; i < numSections2; i++) {
          secs2[i] = trueSolution2[i].setSections();
        }
        for (int i = 0; i < numSections; i++) {
          secs[i].Estimates = mean[i];
        }
        for (int i = 0; i < numSections1; i++) {
          secs1[i].Estimates = mean_1[i];
        }
        for (int i = 0; i < numSections2; i++) {
          secs2[i].Estimates = mean_2[i];
        }

        for (int i = 0; i < numSections; i++) {
          if (secs[i].getClass().getSimpleName().equals("FC")) {
            secs[i].getwavefrontfromEstimation();
            if (secs[i].wavefront < 0) {
              secs[i].wavefront = 0;
            }
            if (secs[i].wavefront <= cellsec - 2) {
              if (trueSolution[i].flux(secs[i].Estimates.get(secs[i].wavefront, 0))
                      - trueSolution[i].flux(secs[i].Estimates.get(secs[i].wavefront + 1, 0))
                  > 0) {
                secs[i].wavedirection = 0;
              } else {
                secs[i].wavedirection = 1;
              }
            } else if (secs[i].wavefront == cellsec - 1) {
              if (secs[i].index != numSections - 1) {
                if (trueSolution[i].flux(secs[i].Estimates.get(secs[i].wavefront, 0))
                        - trueSolution[i + 1].flux(secs[i].Estimates.get(overlap, 0))
                    > 0) {
                  secs[i].wavedirection = 0;
                } else {
                  secs[i].wavedirection = 1;
                }
              } else {
                secs[i].wavedirection = 0;
              }
            }
            secs[i].getModelA();
            secs[i].getModelB1();
            secs[i].getModelB2();
          } else if (secs[i].getClass().getSimpleName().equals("CF")) {
            secs[i].getwavefrontfromEstimation();
            secs[i].getModelA();
            secs[i].getModelB1();
            secs[i].getModelB2();
          }
        }

        for (int i = 0; i < numSections1; i++) {
          if (secs1[i].getClass().getSimpleName().equals("FC")) {
            secs1[i].getwavefrontfromEstimation();
            if (secs1[i].wavefront < 0) {
              secs1[i].wavefront = 0;
            }
            if (secs1[i].wavefront <= cellsec1 - 2) {
              if (trueSolution1[i].flux(secs1[i].Estimates.get(secs1[i].wavefront, 0))
                      - trueSolution1[i].flux(secs1[i].Estimates.get(secs1[i].wavefront + 1, 0))
                  > 0) {
                secs1[i].wavedirection = 0;
              } else {
                secs1[i].wavedirection = 1;
              }
            } else if (secs1[i].wavefront == cellsec1 - 1) {
              if (secs1[i].index != numSections1 - 1) {
                if (trueSolution1[i].flux(secs1[i].Estimates.get(secs1[i].wavefront, 0))
                        - trueSolution1[i + 1].flux(secs1[i].Estimates.get(overlap1, 0))
                    > 0) {
                  secs1[i].wavedirection = 0;
                } else {
                  secs1[i].wavedirection = 1;
                }
              } else {
                secs1[i].wavedirection = 0;
              }
            }
            secs1[i].getModelA();
            secs1[i].getModelB1();
            secs1[i].getModelB2();
          } else if (secs1[i].getClass().getSimpleName().equals("CF")) {
            secs1[i].getwavefrontfromEstimation();
            secs1[i].getModelA();
            secs1[i].getModelB1();
            secs1[i].getModelB2();
          }
        }

        for (int i = 0; i < numSections2; i++) {
          if (secs2[i].getClass().getSimpleName().equals("FC")) {
            secs2[i].getwavefrontfromEstimation();
            if (secs2[i].wavefront < 0) {
              secs2[i].wavefront = 0;
            }
            if (secs2[i].wavefront <= cellsec2 - 2) {
              if (trueSolution2[i].flux(secs2[i].Estimates.get(secs2[i].wavefront, 0))
                      - trueSolution2[i].flux(secs2[i].Estimates.get(secs2[i].wavefront + 1, 0))
                  > 0) {
                secs2[i].wavedirection = 0;
              } else {
                secs2[i].wavedirection = 1;
              }
            } else if (secs2[i].wavefront == cellsec2 - 1) {
              if (secs2[i].index != numSections2 - 1) {
                if (trueSolution2[i].flux(secs2[i].Estimates.get(secs2[i].wavefront, 0))
                        - trueSolution2[i + 1].flux(secs2[i].Estimates.get(overlap2, 0))
                    > 0) {
                  secs2[i].wavedirection = 0;
                } else {
                  secs2[i].wavedirection = 1;
                }
              } else {
                secs2[i].wavedirection = 0;
              }
            }
            secs2[i].getModelA();
            secs2[i].getModelB1();
            secs2[i].getModelB2();
          } else if (secs2[i].getClass().getSimpleName().equals("CF")) {
            secs2[i].getwavefrontfromEstimation();
            secs2[i].getModelA();
            secs2[i].getModelB1();
            secs2[i].getModelB2();
          }
        }
        for (int i = 0; i < numSections; i++) {
          estimations[i].setSection(secs[i]);
        }
        for (int i = 0; i < numSections1; i++) {
          estimations1[i].setSection(secs1[i]);
        }
        for (int i = 0; i < numSections2; i++) {
          estimations2[i].setSection(secs2[i]);
        }
        for (int i = 0; i < numSections; i++) {
          trueSolution[i].section = secs[i];
        }
        for (int i = 0; i < numSections1; i++) {
          trueSolution1[i].section = secs1[i];
        }
        for (int i = 0; i < numSections2; i++) {
          trueSolution2[i].section = secs2[i];
        }
        for (int i = 0; i < numSections; i++) {
          if (i == 0) {
            GammaWrite[i].write(estimations[i].filter.gammaStar + ",");
          } else if (i == numSections - 1) {
            GammaWrite[i].write(estimations[i].filter.gammaStar + ",");
          } else {
            GammaWrite[i].write(estimations[i].filter.gammaStar + ",");
          }
          GammaWrite[i].write("\n");
        }
        for (int i = 0; i < numSections; i++) {
          Mode[i].write(estimations[i].roadModel.section.getClass().getSimpleName() + ",");
          Mode[i].write(
              estimations[i].roadModel.section.wavefront + ","); // estimated location of shock
          Mode[i].write(
              estimations[i].roadModel.section._wavefront + ","); // true location of shock
          Mode[i].write(estimations[i].roadModel.section.wavedirection + ",");
          Mode[i].write(estimations[i].roadModel.section._wavedirection + ",");
          Mode[i].write("\n");
        }
        for (int i = 0; i < numSections1; i++) {
          Mode1[i].write(estimations1[i].roadModel.section.getClass().getSimpleName() + ",");
          Mode1[i].write(estimations1[i].roadModel.section.wavefront + ",");
          Mode1[i].write(estimations1[i].roadModel.section._wavefront + ",");
          Mode1[i].write(estimations1[i].roadModel.section.wavedirection + ",");
          Mode1[i].write(estimations1[i].roadModel.section._wavedirection + ",");
          Mode1[i].write("\n");
        }
        for (int i = 0; i < numSections2; i++) {
          Mode2[i].write(estimations2[i].roadModel.section.getClass().getSimpleName() + ",");
          Mode2[i].write(estimations2[i].roadModel.section.wavefront + ",");
          Mode2[i].write(estimations2[i].roadModel.section._wavefront + ",");
          Mode2[i].write(estimations2[i].roadModel.section.wavedirection + ",");
          Mode2[i].write(estimations2[i].roadModel.section._wavedirection + ",");
          Mode2[i].write("\n");
        }

        for (int i = 0; i < numSections; i++) {
          //						trueSolution[i].updateMeasurement();
          //						roadModels[i].updateMeasurement();
          estimations[i].filter.getNewParametersFromModel();
        }

        for (int i = 0; i < numSections1; i++) {
          //						trueSolution[i].updateMeasurement();
          //						roadModels[i].updateMeasurement();
          estimations1[i].filter.getNewParametersFromModel();
        }

        for (int i = 0; i < numSections2; i++) {
          //						trueSolution[i].updateMeasurement();
          //						roadModels[i].updateMeasurement();
          estimations2[i].filter.getNewParametersFromModel();
        }

        for (int i = 0; i < numSections; i++) {
          S[i] =
              (estimations[i].filter.measure.transpose())
                  .mmul(InverseMatrix.invPoSym(estimations[i].filter.measureVar))
                  .mmul(estimations[i].filter.measure);
        }

        double disag = 0;
        for (int i = 0; i < numSections - 1; i++) {
          disag =
              disag
                  + (((mean[i]
                                  .getRange(cellsec - overlap, cellsec, 0, 1)
                                  .sub(mean[i + 1].getRange(0, overlap, 0, 1)))
                              .transpose()
                              .mmul(
                                  mean[i]
                                      .getRange(cellsec - overlap, cellsec, 0, 1)
                                      .sub(mean[i + 1].getRange(0, overlap, 0, 1))))
                          .get(0, 0))
                      / ((double) overlap);
        }
        disag = disag / ((double) (numSections - 1));
        writerDisagreement.write(disag + ",");
        disagAvg[0] = disagAvg[0] + disag / ((double) limite);
        for (int i = 0; i < numSections - 1; i++) {
          writerDisagreement.write(
              ((mean[i]
                              .getRange(cellsec - overlap, cellsec, 0, 1)
                              .sub(mean[i + 1].getRange(0, overlap, 0, 1)))
                          .transpose()
                          .mmul(
                              mean[i]
                                  .getRange(cellsec - overlap, cellsec, 0, 1)
                                  .sub(mean[i + 1].getRange(0, overlap, 0, 1))))
                      .get(0, 0)
                  + ",");
        }
        writerDisagreement.write("\n");

        double disag1 = 0;
        for (int i = 0; i < numSections1 - 1; i++) {
          disag1 =
              disag1
                  + (((mean_1[i]
                                  .getRange(cellsec1 - overlap1, cellsec1, 0, 1)
                                  .sub(mean_1[i + 1].getRange(0, overlap1, 0, 1)))
                              .transpose()
                              .mmul(
                                  mean_1[i]
                                      .getRange(cellsec1 - overlap1, cellsec1, 0, 1)
                                      .sub(mean_1[i + 1].getRange(0, overlap1, 0, 1))))
                          .get(0, 0))
                      / ((double) overlap1);
        }
        disag1 = disag1 / ((double) (numSections1 - 1));
        writerDisagreement1.write(disag1 + ",");
        disagAvg[1] = disagAvg[1] + disag1 / ((double) limite);
        for (int i = 0; i < numSections1 - 1; i++) {
          writerDisagreement1.write(
              ((mean_1[i]
                              .getRange(cellsec1 - overlap1, cellsec1, 0, 1)
                              .sub(mean_1[i + 1].getRange(0, overlap1, 0, 1)))
                          .transpose()
                          .mmul(
                              mean_1[i]
                                  .getRange(cellsec1 - overlap1, cellsec1, 0, 1)
                                  .sub(mean_1[i + 1].getRange(0, overlap1, 0, 1))))
                      .get(0, 0)
                  + ",");
        }
        writerDisagreement1.write("\n");

        double disag2 = 0;
        for (int i = 0; i < numSections2 - 1; i++) {
          disag2 =
              disag2
                  + (((mean_2[i]
                                  .getRange(cellsec2 - overlap2, cellsec2, 0, 1)
                                  .sub(mean_2[i + 1].getRange(0, overlap2, 0, 1)))
                              .transpose()
                              .mmul(
                                  mean_2[i]
                                      .getRange(cellsec2 - overlap2, cellsec2, 0, 1)
                                      .sub(mean_2[i + 1].getRange(0, overlap2, 0, 1))))
                          .get(0, 0))
                      / ((double) overlap2);
        }
        disag2 = disag2 / ((double) (numSections2 - 1));
        writerDisagreement2.write(disag2 + ",");
        disagAvg[2] = disagAvg[2] + disag2 / ((double) limite);
        for (int i = 0; i < numSections2 - 1; i++) {
          writerDisagreement2.write(
              ((mean_2[i]
                              .getRange(cellsec2 - overlap2, cellsec2, 0, 1)
                              .sub(mean_2[i + 1].getRange(0, overlap2, 0, 1)))
                          .transpose()
                          .mmul(
                              mean_2[i]
                                  .getRange(cellsec2 - overlap2, cellsec2, 0, 1)
                                  .sub(mean_2[i + 1].getRange(0, overlap2, 0, 1))))
                      .get(0, 0)
                  + ",");
        }
        writerDisagreement2.write("\n");

        trueSolutionCTM.update();

        // **start defining boundary condition
        int cells = trueSolutionCTM.trueStatesCTMPrior.getRows();
        if (bdry == 0) {
          double inflow = trueSolutionCTM.receiving(trueSolutionCTM.trueStatesCTMPrior.get(0, 0));
          double outflow =
              trueSolutionCTM.sending(trueSolutionCTM.trueStatesCTMPrior.get(cells - 1, 0));
          double upOut =
              trueSolutionCTM.computeFlux(
                  trueSolutionCTM.trueStatesCTMPrior.get(0, 0),
                  trueSolutionCTM.trueStatesCTMPrior.get(1, 0));
          trueSolutionCTM.trueStatesCTM.put(
              0,
              0,
              trueSolutionCTM.trueStatesCTMPrior.get(0, 0)
                  + (trueSolutionCTM.dt / trueSolutionCTM.dx) * (inflow - upOut));

          double downIn =
              trueSolutionCTM.computeFlux(
                  trueSolutionCTM.trueStatesCTMPrior.get(cells - 2, 0),
                  trueSolutionCTM.trueStatesCTMPrior.get(cells - 1, 0));
          trueSolutionCTM.trueStatesCTM.put(
              cells - 1,
              0,
              trueSolutionCTM.trueStatesCTMPrior.get(cells - 1, 0)
                  + (trueSolutionCTM.dt / trueSolutionCTM.dx) * (downIn - outflow));
        } else if (bdry == 1) {
          double inflow = 0.1125 + 0.1125 * Math.sin(k * (Math.PI / 4000) + (Math.PI));
          if (inflow > trueSolutionCTM.receiving(trueSolutionCTM.trueStatesCTMPrior.get(0, 0))) {
            inflow = trueSolutionCTM.receiving(trueSolutionCTM.trueStatesCTMPrior.get(0, 0));
          }

          double outflow =
              trueSolutionCTM.receiving(trueSolutionCTM.trueStatesCTMPrior.get(cells - 1, 0));
          //						double outflow=0.1125+0.1125*Math.sin(k*(Math.PI/1000));
          //						if
          // (outflow>trueSolution[numSections-1].sending(trueSolution[numSections-1].trueStatesPrior.get(cellsec-1,0))){
          //
          //	outflow=trueSolution[numSections-1].sending(trueSolution[numSections-1].trueStatesPrior.get(cellsec-1,0));
          //						}

          double upOut =
              trueSolutionCTM.computeFlux(
                  trueSolutionCTM.trueStatesCTMPrior.get(0, 0),
                  trueSolutionCTM.trueStatesCTMPrior.get(1, 0));
          trueSolutionCTM.trueStatesCTM.put(
              0,
              0,
              trueSolutionCTM.trueStatesCTMPrior.get(0, 0)
                  + (trueSolutionCTM.dt / trueSolutionCTM.dx) * (inflow - upOut));

          double downIn =
              trueSolutionCTM.computeFlux(
                  trueSolutionCTM.trueStatesCTMPrior.get(cells - 2, 0),
                  trueSolutionCTM.trueStatesCTMPrior.get(cells - 1, 0));
          trueSolutionCTM.trueStatesCTM.put(
              cells - 1,
              0,
              trueSolutionCTM.trueStatesCTMPrior.get(cells - 1, 0)
                  + (trueSolutionCTM.dt / trueSolutionCTM.dx) * (downIn - outflow));
        } else {
          double inflow = 0.1125 + 0.1125 * Math.sin(k * (Math.PI / 8000) + (Math.PI));
          if (inflow > trueSolutionCTM.receiving(trueSolutionCTM.trueStatesCTMPrior.get(0, 0))) {
            inflow = trueSolutionCTM.receiving(trueSolutionCTM.trueStatesCTMPrior.get(0, 0));
          }

          double outflow =
              trueSolutionCTM.receiving(trueSolutionCTM.trueStatesCTMPrior.get(cells - 1, 0));
          //						double outflow=0.1125+0.1125*Math.sin(k*(Math.PI/1000));
          //						if
          // (outflow>trueSolution[numSections-1].sending(trueSolution[numSections-1].trueStatesPrior.get(cellsec-1,0))){
          //
          //	outflow=trueSolution[numSections-1].sending(trueSolution[numSections-1].trueStatesPrior.get(cellsec-1,0));
          //						}

          double upOut =
              trueSolutionCTM.computeFlux(
                  trueSolutionCTM.trueStatesCTMPrior.get(0, 0),
                  trueSolutionCTM.trueStatesCTMPrior.get(1, 0));
          trueSolutionCTM.trueStatesCTM.put(
              0,
              0,
              trueSolutionCTM.trueStatesCTMPrior.get(0, 0)
                  + (trueSolutionCTM.dt / trueSolutionCTM.dx) * (inflow - upOut));

          double downIn =
              trueSolutionCTM.computeFlux(
                  trueSolutionCTM.trueStatesCTMPrior.get(cells - 2, 0),
                  trueSolutionCTM.trueStatesCTMPrior.get(cells - 1, 0));
          trueSolutionCTM.trueStatesCTM.put(
              cells - 1,
              0,
              trueSolutionCTM.trueStatesCTMPrior.get(cells - 1, 0)
                  + (trueSolutionCTM.dt / trueSolutionCTM.dx) * (downIn - outflow));
          // *define boundary conditions here
        }
        // **end defining boundary condition

        trueSolutionCTM.getMeasurement();

        for (int i = 0; i < numSections; i++) {
          trueSolution[i].update();
        }

        for (int i = 0; i < numSections; i++) {
          trueSolution[i].updatemeasurement();
        }

        for (int i = 0; i < numSections1; i++) {
          trueSolution1[i].update();
        }

        for (int i = 0; i < numSections1; i++) {
          trueSolution1[i].updatemeasurement();
        }

        for (int i = 0; i < numSections2; i++) {
          trueSolution2[i].update();
        }

        for (int i = 0; i < numSections2; i++) {
          trueSolution2[i].updatemeasurement();
        }

        for (int i = 0; i < numSections; i++) {
          estimations[i].nextStepWithoutUpdateTrue();
        }

        for (int i = 0; i < numSections1; i++) {
          estimations1[i].nextStepWithoutUpdateTrue();
        }

        for (int i = 0; i < numSections2; i++) {
          estimations2[i].nextStepWithoutUpdateTrue();
        }

        if (estimations[0].consensus) {

          for (int i = 0; i < numSections; i++) {
            estimations[i].filter.ComputeEig();
          }
          for (int i = 0; i < numSections; i++) {
            if (i == 0) {
              estimations[i].filter.ComputeGammaStar2(estimations[1].filter);
            } else if (i == numSections - 1) {
              estimations[i].filter.ComputeGammaStar1(estimations[numSections - 2].filter);
            } else {
              estimations[i].filter.ComputeGammaStar(
                  estimations[i - 1].filter, estimations[i + 1].filter);
            }
          }

          DoubleMatrix[] mean1 = new DoubleMatrix[numSections];
          mean1[0] = estimations[0].filter.Consensus2(estimations[1].filter);
          writerConsensusTerm.write(estimations[0].filter.scaling.get(0) + ",");
          writerConsensusTerm.write(estimations[0].filter.scaling.get(1) + ",");

          for (int i = 1; i < numSections - 1; i++) {
            mean1[i] =
                estimations[i].filter.Consensus(
                    estimations[i - 1].filter, estimations[i + 1].filter);
            writerConsensusTerm.write(estimations[i].filter.scaling.get(0) + ",");
            writerConsensusTerm.write(estimations[i].filter.scaling.get(1) + ",");
          }

          mean1[numSections - 1] =
              estimations[numSections - 1].filter.Consensus1(estimations[numSections - 2].filter);
          writerConsensusTerm.write(estimations[numSections - 1].filter.scaling.get(0) + ",");
          writerConsensusTerm.write(estimations[numSections - 1].filter.scaling.get(1) + ",");
          writerConsensusTerm.write("\n");
          for (int i = 0; i < numSections; i++) {
            estimations[i].filter.mean = mean1[i];
          }
        }
      }

      for (int i = 0; i < numSections; i++) {
        writerSection[i].flush();
        writerSection[i].close();
        Mode[i].flush();
        Mode[i].close();
        LyapSection[i].flush();
        LyapSection[i].close();
        GammaWrite[i].flush();
        GammaWrite[i].close();
      }
      for (int i = 0; i < numSections1; i++) {
        writerSection1[i].flush();
        writerSection1[i].close();
        Mode1[i].flush();
        Mode1[i].close();
      }
      for (int i = 0; i < numSections2; i++) {
        writerSection2[i].flush();
        writerSection2[i].close();
        Mode2[i].flush();
        Mode2[i].close();
      }
      writerAvr.flush();
      writerAvr.close();
      writerConsensusTerm.flush();
      writerConsensusTerm.close();
      writerAvr1.flush();
      writerAvr1.close();
      writerAvr2.flush();
      writerAvr2.close();
      Error.flush();
      Error.close();
      Error1.flush();
      Error1.close();
      Error2.flush();
      Error2.close();
      Lyap.flush();
      Lyap.close();
      writerTrue.flush();
      writerTrue.close();
      writerDisagreement.flush();
      writerDisagreement.close();
      writerDisagreement1.flush();
      writerDisagreement1.close();
      writerDisagreement2.flush();
      writerDisagreement2.close();

      System.out.print("Disag_avg_DLKCF=" + disagAvg[0] + "\n");
      System.out.print("Disag_avg_DLKF=" + disagAvg[1] + "\n");
      System.out.print("Disag_avg_LKF=" + disagAvg[2] + "\n");
      System.out.print("Err_avg_DLKCF=" + errorAvg[0] + "\n");
      System.out.print("Err_avg_DLKF=" + errorAvg[1] + "\n");
      System.out.print("Err_avg_LKF=" + errorAvg[2] + "\n");

      System.out.println(" End");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #24
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完毕…………");
  }