Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

swing - JTree, Optimization algorithm, Java

My Partners and me, we are trying to optimize frequency process...

What we want to simplify our problem as much as possible in a JTree.

enter image description here

As you can see, each node or leaf has a numResampleOperations involved per node/leaf.

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

How do we calculate the values?

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

We want to obtain only one value per frequency shown in the JTextField, removing not needed branch.

For this example we used only 5 ordered Target frequencies (only integers value are allowed), but can grow until 50 frequency values.

The JTree must preserve at least one per included Target frequency of 150Hz, at least one of 160Hz, .., 210Hz.

The highest priority is to have the minimum sum involved of numResampleOperations

How remove not needed branchs (those whose sum is very high), nodes or leafs, with the guarantee of having at least one (frequency required on JTextField), but the sum of all numResampleOperations is minimum?

What do you suggest to us?

We starting with Generate List with Combination of Subset of List, Java But due to the dimensions the solution is not viable.

EDIT 1

my class

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 + "}   ";
  }

}

Now , I noticed that certain branches are essential, for example the First (Top) branch that includes the 210, because no other branch of the tree includes it.

First, I need a code to find the branch that includes that value (200) 'or the cheapest'. Add the found branch to another Target JTree. Some code for this part?

I also noticed that other branches still have the value of 200, however, the cost of adding another branch is greater than continuing to use the first 'essential' branch, since this is only adding two nodes, whose sum is less than adding another branch.

Second, I need to know the value of these two nodes numResampleOperations -> (267960 + 1091720), and the values another branches, to do comparison and add the best option to the another Target JTree. Some code for this part?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I solved my question...

I want to improve all my methods, especially searchNodeResamplePerValue and getOptimizedTree.

I created a filler method... https://pastebin.com/LvCefdc4

You can copy and paste and execute.

tree -> Non Optimized! enter image description here

treeOut -> Optimized! 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("
minimumlistPerValue:" + Arrays.toString(minimumlistPerValue.toArray()) + "
");
      } else {
        System.out.println("
minimumlistPerValue:" + null + "
");
      }

      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;
  }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...