Snippet Wednesday - 🌳 Grasshopper Tree inputs 🌳

In our documentation we mentioned that it’s preferable to flatten all lists in Grasshopper inputs. While that is still true, in some cases it is very useful to use the Tree Structure as an input.

Why is this useful?
In some (bigger) grasshopper projects, it is preferable that the whole script is not run at once, but in modules. This allows for some steps to have a quick response time, and other steps do the heavy calculations [This is usually how we solve big Grasshopper solutions!]. Communication between these modules often comes in the Tree structure.

How is this done?
First of all, a Hops input needs to be told that it has Tree Access.

image

Then it is possible through code to add branches to your input:

input_trees = []

tree = gh.DataTree("key")
tree.Append([0, 0, 0], ['some data'])
tree.Append([0, 1, 0], ['other data'])

input_trees.append(tree)

Which will result in an output like this:
image

From json to datatree
Now if you have imported a dict in your worker directory; the following snippet can translate your json to a datatree:

some_data = {  
  "{0;0;0}": ['some data'],
  "{0;1;0}": ['other data'],
}

def index_of_branch(branch_input):
  """Given an Rhino branch as string, return a list  of the indexes"""
  integers = re.findall(r"\d+", branch_input)
  # Convert the list of strings to a list of integers
  integers = [int(i) for i in integers]
  return integers

input_trees = []

tree = gh.DataTree("key")

for branch, values in some_data.items():
    tree.Append(index_of_branch(branch), [str(i) for i in values])
  
input_trees.append(tree)

...

Hopefully this helps you out with some of the bigger Grasshopper scripts!

6 Likes