Trim Tree in C#

Does anyone know if there is a way to trim a tree via C# in Grasshopper? I’m looking to achieve the same as the “trim tree” command.

Thanks!

Yes, Grasshopper is C#, so whatever it can do, you can do. Do note you’ll have a hard time duplicating components that deal with trees using a C# script component, because data is converted before it is handed off to a script component. But if you don’t mind that, then it’s just a matter of iterating over the branches of the old tree and building a new one. I’ll come up with an example.

treetrimmish.gh (35.3 KB)

private void RunScript(DataTree<object> T, int K, ref object R)
{
  DataTree<object> tree = new DataTree<object>();

  for (int i = 0; i < T.BranchCount; i++)
  {
    var path = T.Paths[i];
    var list = T.Branch(i);

    // Limit length of path to a maximum of K elements.
    while (path.Length > K)
      path = path.CullElement();

    tree.AddRange(list, path);
  }

  R = tree;
}
3 Likes

Hi @DavidRutten, thanks for your response and example. I will give this a try!

This works perfectly, thanks again David!

Hi David and Chris,
I’m trying something similar to Chris: implementing the behaviour of Trim Tree, but in my case as part of a plugin (as opposed to a standalone C# component) with this code:

public static DataTree<object> TrimTreeD2(DataTree<object> tree)
        {
            DataTree<object> trimmedTree = new DataTree<object>();
            foreach (GH_Path path in tree.Paths)
            {
                int currIndex = path.Indices[0];
                GH_Path flatPath = new GH_Path(currIndex);
                object currItem = tree.Branch(path)[0];
                trimmedTree.Add(currItem, flatPath);
            }
            return trimmedTree;
        }

However, when using a DataTree as argument, I get an error saying

cannot convert from ‘Grasshopper.Datatree<Rhino.Geometry.Brep>’ to ‘Grasshopper.Datatree’.

Can there be a more generic class than object?
Thanks in advance, Eduardo

Great example! But still a problem, If I try to trim all the branches of a tree, it pops up a dialog box complaining “Paths must have at least one element”, but still give me the desired result (tree is flattened), How to stop it from popping up dialog box ? Thanks in advance


See attached

DataTrees_Paths_V1.gh (117.3 KB)