When using the Python component in Grasshopper, we sometimes encounter circumstances to deal with the unique tree structure of Grasshopper. There are two ways to handle this issue, one is a more scripting version, the other is a much simpler version.
(1) The given tree structure
For this tutorial, I simply made a secondary depth tree structure, adding series of numbers.
(2) Dealing with list of list
Let's say we want to import this tree to the python component and double each item in tree lists. To do this simple job, as python can't understand tree structure directly, we should take steps to convert the original list. The first method is to deal with list of list using "for" syntax in python. Below is the code.
import rhinoscriptsyntax as rs
import Grasshopper.DataTree as dt
#step 1. Expand tree structure and append the results to python list.
n_of_branches = x.BranchCount
gh_to_py_listlist = []
for i in range(n_of_branches):
gh_to_py_listlist.append(x.Branch(i))
# x.Branch(i) = A list in each branch
# Append lists to prepared python list
#step 2. Manipulating data and storing
new_list = []
for list in gh_to_py_listlist:
list = [2*i for i in list] #Manipulating original data
new_list.append(list)
#step 3. Reorganizing python list to Grasshopper tree structure.
convert_list = dt[object]()
paths = x.Paths
for i in range(n_of_branches):
convert_list.AddRange(new_list[i], paths[i])
a = convert_list
(3) Avoid dealing with list of list
However, the upper method is not so handy. It takes long sentences of codes. The good news is that Grasshopper already provides nice function which directly converts tree structure into nested list structure in Python, which is quite similar to tree structure. Below is the code.
import rhinoscriptsyntax as rs
import ghpythonlib.treehelpers as th
x = th.tree_to_list(x,retrieve_base=None)
new_list = []
for list in x:
list = [2*i for i in list]
new_list.append(list)
a = th.list_to_tree(new_list)
Converting code is much simpler now. Note that to use this embedded function, it is necessary to import treehelpers method. treehelpers provide two functions, one function converts tree to list, and other function converts list to tree. Important thing is that to return the whole lists of tree, we should specify retrieve_base to None, otherwise, it will only return the first list of the tree structure.
(4) Comparing results
Just like our intention, the results appeared to double the original list items.
* Original Rhino developers docs posts regarding this issue can be found here:
http://developer.rhino3d.com/guides/rhinopython/grasshopper-datatrees-and-python/
* Github link for the same code:
https://github.com/OllyKim/Grasshopper-and-python/blob/main/33a_Dealing_with_Tree_Structure.py
'Python & Coding > Python in Grasshopper' 카테고리의 다른 글
그래스호퍼에서 비트맵 이미지 벡터화하기 1 (0) | 2023.06.03 |
---|---|
Sorting 8 cuboid points in Python Grasshopper (0) | 2021.06.20 |
라이노 그래스호퍼에서 파이썬 사용하기 (0) | 2021.06.03 |