编程语言
首页 > 编程语言> > JTree,优化算法,Java

JTree,优化算法,Java

作者:互联网

我的合作伙伴和我,我们正在努力优化频率流程……

我们想要在JTree中尽可能地简化我们的问题.

enter image description here

如您所见,每个节点或叶子每个节点/叶子都有一个numResampleOperations.

L -> Increment or multiplication
M -> Decrement or division

我们如何计算价值?

Target = Source*L/M
numResampleOperations = filterSize * Source * Integer.max(L, M);

我们希望只获得JTextField中显示的每个频率的一个值,删除不需要的分支.

对于此示例,我们仅使用5个有序目标频率(仅允许整数值),但可以增长到50个频率值.

JTree必须至少保留一个150Hz的目标频率,至少160Hz,……,210Hz之一.

最高优先级是numResampleOperations涉及的最小总和

如何删除不需要的分支(那些总和非常高的分支),节点或叶子,保证至少有一个(JTextField需要的频率),但所有numResampleOperations的总和是最小的?

你对我们有什么建议?

我们从Generate List with Combination of Subset of List, Java开始
但由于尺寸,解决方案不可行.

编辑1

我的课

public class NodeResample {

  private int incrementL;
  private int decrementM;
  private int sampleRateSource;
  private int sampleRateTarget;
  private double maxPassFreq;
  private Integer filterSize;
  private Integer numResampleOperations;

  public NodeResample(int incrementL, int decrementM, int sampleRateSource, int sampleRateTarget, double maxPassFreq, Integer filterSize, Integer numResampleOperations) {
    this.incrementL = incrementL;
    this.decrementM = decrementM;
    this.sampleRateSource = sampleRateSource;
    this.sampleRateTarget = sampleRateTarget;
    this.maxPassFreq = maxPassFreq;
    this.filterSize = filterSize;
    this.numResampleOperations = numResampleOperations;
  }

  public int getIncrementL() {
    return incrementL;
  }

  public void setIncrementL(int incrementL) {
    this.incrementL = incrementL;
  }

  public int getDecrementM() {
    return decrementM;
  }

  public void setDecrementM(int decrementM) {
    this.decrementM = decrementM;
  }

  public int getSampleRateSource() {
    return sampleRateSource;
  }

  public void setSampleRateSource(int sampleRateSource) {
    this.sampleRateSource = sampleRateSource;
  }

  public int getSampleRateTarget() {
    return sampleRateTarget;
  }

  public void setSampleRateTarget(int sampleRateTarget) {
    this.sampleRateTarget = sampleRateTarget;
  }

  public double getMaxPassFreq() {
    return maxPassFreq;
  }

  public void setMaxPassFreq(double maxPassFreq) {
    this.maxPassFreq = maxPassFreq;
  }

  public Integer getFilterSize() {
    return filterSize;
  }

  public void setFilterSize(Integer filterSize) {
    this.filterSize = filterSize;
  }

  public Integer getNumResampleOperations() {
    return numResampleOperations;
  }

  public void setNumResampleOperations(Integer numResampleOperations) {
    this.numResampleOperations = numResampleOperations;
  }

  @Override
  public String toString() {
    return "NodeResample{" + "L=" + incrementL + ", M=" + decrementM
        + ", Source=" + sampleRateSource + ", Target=" + sampleRateTarget
        + ", filterSize=" + filterSize + ", numResampleOperations=" + numResampleOperations + "}   ";
  }

}

现在,我注意到某些分支是必不可少的,例如包含210的First(Top)分支,因为树的其他分支不包含它.

首先,我需要一个代码来查找包含该值(200)或最便宜的分支.将找到的分支添加到另一个Target JTree.
这部分的一些代码?

我还注意到其他分支仍然具有200的值,但是,添加另一个分支的成本大于继续使用第一个“必要”分支,因为这只添加了两个节点,其总和小于添加另一个分支.

其次,我需要知道这两个节点的值numResampleOperations – > (267960 1091720),并且值为另一个分支,进行比较并将最佳选项添加到另一个Target JTree.这部分的一些代码?

解决方法:

我解决了我的问题……

我想改进我的所有方法,特别是searchNodeResamplePerValue和getOptimizedTree.

我创建了一种填充方法… https://pastebin.com/LvCefdc4

您可以复制,粘贴和执行.

树 – >未经优化!
enter image description here

treeOut – >优化!
enter image description here

public class OptimizationResample {

  public static void main(String[] args) {

    final JTree tree = new JTree();
    tree.setRootVisible(false);
    removeAllTreeNodes(tree);
    fillTreeNestedListNodeResample(tree, filler());
    expandAllNodes(tree);

    List<Integer> listSampleRateFinal = Arrays.asList(210, 200, 180, 160, 150);
    JTree treeOut = getOptimizedTree(tree, listSampleRateFinal);
    expandAllNodes(treeOut);
    final JTextField textField = new JTextField(listSampleRateFinal.toString());//listSampleRateFinal .collect(Collectors.joining(","));

    JSplitPane splitPane = new JSplitPane();
    splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
    splitPane.setTopComponent(new JScrollPane(tree));
    splitPane.setBottomComponent(new JScrollPane(treeOut));
    splitPane.setDividerLocation(350);
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
    panel.add(textField);
    panel.add(splitPane);

    JFrame frame = new JFrame("Optimization NodeResample");
    frame.setContentPane(panel);
    frame.pack();
    frame.setSize(new Dimension(600, 700));
    frame.setVisible(true);

  }

  private static JTree getOptimizedTree(JTree tree, List<Integer> listSampleRateFinal) {
    JTree treeOut = new JTree();
    treeOut.setRootVisible(false);
    removeAllTreeNodes(treeOut);
    listSampleRateFinal.forEach(target -> {
      List<List<NodeResample>> nestedListPerValue = searchNodeResamplePerValue(tree, target);
      Long lastMinimum = Long.MAX_VALUE;
      List<NodeResample> minimumlistPerValue = null;
      for (List<NodeResample> listPerValue : nestedListPerValue) {
        // I can't easily copy all nodes from treeOut to tempTree (I had problem with new JTree(treeOut.getModel());)
        List<List<NodeResample>> nestedListNodeResample2 = getNestedListNodeResampleFromTree(treeOut);
        JTree tempTree = new JTree();
        tempTree.setRootVisible(false);
        removeAllTreeNodes(tempTree);
        fillTreeNestedListNodeResample(tempTree, nestedListNodeResample2);
        addNodeResampleToTree(tempTree, listPerValue);

        List<DefaultMutableTreeNode> listNodes = getListNodesFromTree(tempTree);
        Long accumulator = listNodes.stream()
            .filter(leaf -> leaf.getUserObject() instanceof NodeResample)
            .map(leaf -> (NodeResample) leaf.getUserObject())
            .map(nodeResample -> (long) nodeResample.getNumResampleOperations())
            .mapToLong(Long::longValue).sum();
        if (accumulator < lastMinimum) {
          lastMinimum = accumulator;
          minimumlistPerValue = listPerValue;
        }
      }
      if (minimumlistPerValue != null) {
        System.out.println("\nminimumlistPerValue:" + Arrays.toString(minimumlistPerValue.toArray()) + "\n");
      } else {
        System.out.println("\nminimumlistPerValue:" + null + "\n");
      }

      addNodeResampleToTree(treeOut, minimumlistPerValue);
    });
    return treeOut;
  }

  private static List<List<NodeResample>> searchNodeResamplePerValue(JTree tree, int value) {
    List<DefaultMutableTreeNode> listNodes = getListNodesFromTree(tree);
    List<DefaultMutableTreeNode> listNodesWithValue = listNodes.stream()
        .filter(node -> node.getUserObject() instanceof NodeResample)
        .filter(node -> value == ((NodeResample) node.getUserObject()).getSampleRateTarget())
        .collect(Collectors.toList());

    List<List<NodeResample>> out = new ArrayList<>();
    Long lastSumNumResampleOperations = Long.MAX_VALUE;

    for (DefaultMutableTreeNode leaf : listNodesWithValue) {

      List<NodeResample> listNodeResample = new ArrayList<>();
      listNodeResample.add((NodeResample) leaf.getUserObject());
      TreeNode treeNode = leaf.getParent();
      while (treeNode != null) {
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) treeNode;
        if ((parent).getUserObject() instanceof NodeResample) {
          listNodeResample.add(0, (NodeResample) parent.getUserObject());
        }
        treeNode = parent.getParent();
      }

//      Long totalNumResampleOperations = listNodeResample.stream()
//          .map(nodeResample -> (long) nodeResample.getNumResampleOperations())
//          .mapToLong(Long::longValue).sum();
//      if (totalNumResampleOperations < lastSumNumResampleOperations) {
//        lastSumNumResampleOperations = totalNumResampleOperations;
//        //out = listNodeResample;
//      }
      out.add(listNodeResample);
    }
    return out;
  }

  private static void removeAllTreeNodes(JTree tree) {
    DefaultMutableTreeNode rootTreeNode = (DefaultMutableTreeNode) tree.getModel().getRoot();
    if (rootTreeNode != null) {
      rootTreeNode.removeAllChildren();
    }
    reloadTree(tree);
  }

  private static void reloadTree(JTree tree) {
    DefaultTreeModel treeModel = ((DefaultTreeModel) tree.getModel());
    DefaultMutableTreeNode rootTreeNode = (DefaultMutableTreeNode) treeModel.getRoot();
    treeModel.reload(rootTreeNode);
  }

  private static void expandAllNodes(JTree tree) {
    expandAllNodes(tree, 0, tree.getRowCount());
  }

  private static void expandAllNodes(JTree tree, int ini, int rows) {
    try {
      if (tree != null) {
        for (int i = ini; i < rows; ++i) {
          tree.expandRow(i);
        }

        if (tree.getRowCount() != rows) {
          expandAllNodes(tree, rows, tree.getRowCount());
        }
      }
    } catch (ArrayIndexOutOfBoundsException ex) {
    } catch (Exception ex) {
    }
  }

  private static void fillTreeNestedListNodeResample(JTree tree, List<List<NodeResample>> nestedListNodeResample) {
    nestedListNodeResample.stream()
        .forEachOrdered(listNodeResample -> {
          addNodeResampleToTree(tree, listNodeResample);
        });
  }

  private static void addNodeResampleToTree(JTree tree, List<NodeResample> listNodeResample) {
    try {
      DefaultTreeModel treeModel = ((DefaultTreeModel) tree.getModel());
      DefaultMutableTreeNode rootTreeNode = (DefaultMutableTreeNode) treeModel.getRoot();
      DefaultMutableTreeNode nodeResampleTreeNode = rootTreeNode;
      if (listNodeResample != null) {
        for (NodeResample nodeResample : listNodeResample) {
          nodeResampleTreeNode = getDefaultMutableTreeNode(nodeResampleTreeNode, nodeResample, true);
        }
      }
      treeModel.reload(rootTreeNode);
    } catch (Exception e) {
      throw e;
    }
  }

  private static DefaultMutableTreeNode getDefaultMutableTreeNode(DefaultMutableTreeNode parent, NodeResample newChild, Boolean isLeaf) {
    if (parent != null) {
      DefaultMutableTreeNode child;
      for (int i = 0; i < parent.getChildCount(); i++) {
        child = (DefaultMutableTreeNode) parent.getChildAt(i);
        if (child.toString().equals(newChild.toString())) {
          return child;
        }
      }
      child = new DefaultMutableTreeNode(newChild, isLeaf);
      parent.add(child);
      return child;
    } else {
      return null;
    }
  }

  private static List<List<NodeResample>> getNestedListNodeResampleFromTree(JTree tree) {
    List<List<NodeResample>> nestedListNodeResample = new ArrayList<>();
    List<DefaultMutableTreeNode> listLeafDefaultMutableTreeNode = getListLeafsFromTree(tree);
    listLeafDefaultMutableTreeNode.stream()
        .filter(node -> node.getUserObject() instanceof NodeResample)
        .forEach(leaf -> {
          List<NodeResample> listNodeResample = new ArrayList<>();
          listNodeResample.add((NodeResample) leaf.getUserObject());
          TreeNode treeNode = leaf.getParent();
          while (treeNode != null) {
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) treeNode;
            if ((parent).getUserObject() instanceof NodeResample) {
              listNodeResample.add(0, (NodeResample) parent.getUserObject());
            }
            treeNode = parent.getParent();
          }
          nestedListNodeResample.add(listNodeResample);
        });
    return nestedListNodeResample;
  }

  private static List<DefaultMutableTreeNode> getListLeafsFromTree(JTree tree) {
    DefaultTreeModel treeModel = ((DefaultTreeModel) tree.getModel());
    DefaultMutableTreeNode rootTreeNode = (DefaultMutableTreeNode) treeModel.getRoot();
    List<DefaultMutableTreeNode> listLeafDefaultMutableTreeNode = new ArrayList<>();
    getLeafs(rootTreeNode, listLeafDefaultMutableTreeNode);
    return listLeafDefaultMutableTreeNode;
  }

  private static void getLeafs(DefaultMutableTreeNode parent, List<DefaultMutableTreeNode> listLeafDefaultMutableTreeNode) {
    if (parent.isLeaf()) {
      listLeafDefaultMutableTreeNode.add(parent);
    } else {
      for (int i = 0; i < parent.getChildCount(); i++) {
        DefaultMutableTreeNode child = (DefaultMutableTreeNode) parent.getChildAt(i);
        getLeafs(child, listLeafDefaultMutableTreeNode);
      }
    }
  }

  private static void getListNodesFromTree(TreeNode treeNode, List<DefaultMutableTreeNode> out) {
    DefaultMutableTreeNode nodeResampleTreeNode = (DefaultMutableTreeNode) treeNode;
    out.add(nodeResampleTreeNode);
    if (treeNode.getChildCount() >= 0) {
      for (Enumeration e = treeNode.children(); e.hasMoreElements();) {
        TreeNode n = (TreeNode) e.nextElement();
        getListNodesFromTree(n, out);
      }
    }
  }

  private static List<DefaultMutableTreeNode> getListNodesFromTree(JTree tree) {
    TreeNode root = (TreeNode) tree.getModel().getRoot();
    List<DefaultMutableTreeNode> out = new ArrayList<>();
    getListNodesFromTree(root, out);
    return out;
  }

  private static List<List<NodeResample>> filler() {
    List<List<NodeResample>> nestedListNodeResample = null;//Look in Paste bin 

    return nestedListNodeResample;
  }

}

标签:jtree,java
来源: https://codeday.me/bug/20191003/1848434.html