Tips | DataTree in Python

  1. Usage
    1. Libraries / Objects to be needed
    2. Declaration
    3. Add / Call
  2. Functions
    1. Path
    2. Tree

Usage

Libraries / Objects to be needed

Grasshopper core library is to be imported to use DataTree in Python. To import Grasshopper core library, you need to import “clr” library. And also System library is needed to use DataTree with rhinosctiptsyntax.

import rhinoscriptsyntax as rs

import clr
clr.AddReference("Grasshopper")
import Grasshopper.Kernel.Data.GH_Path as ghpath
import Grasshopper.DataTree as datatree

import System

Declaration

Declaration of DataTree is following:

<DataTree name> = datatree[<Object type to store>]()

Unlike list, DataTree is to be declared before use. Using with rhinoscriptsyntax, you can declare DataTree like following:

tree = datatree[System.Object]()

Add / Call

Adding data into DataTree, you need GH_Path, which is DataPath in Grasshopper, in addition. For example, the script to input integer data “5” at Path”{2;3}” and input data list “[0,1,2,3]” at Path”{3;4}” into DataTree is following:

import rhinoscriptsyntax as rs
import clr
clr.AddReference("Grasshopper")
import Grasshopper.Kernel.Data.GH_Path as ghpath
import Grasshopper.DataTree as datatree
import System

tree = datatree[System.Object]()
path1 = ghpath(2,3)
path2 = ghpath(3,4)

tree.Add(5, path1)
tree.AddRange([0,1,2,3], path2)

And to get a branch as list from DataTree, you can write a code like following:

import rhinoscriptsyntax as rs
import clr
clr.AddReference("Grasshopper")
import Grasshopper.Kernel.Data.GH_Path as ghpath
import Grasshopper.DataTree as datatree
import System

tree = datatree[System.Object]()

for i in range(10):
 path = ghpath(i)
 tree.AddRange(range(10))

a = tree.Branch(3)

Functions

Path

  • <path name>.Indices  –  get list of indices of path
  • <path name>.Length  –  get length of indices
  • <path name>.LengthIncrement(<path index>,<increment>)  –  get path added <increment> to <path index>
  • <path name>.LengthAppendElement(<path number>)  –  add additional branch to the path with <path number>
  • <path name>.LengthCullElement()  –  delete last branch in the path

Tree

  • <tree name>.AllData()  –  get all the data in tree as list
  • <tree name>.Branch(<path>)  –  get data in <path> as list
  • <tree name>.Branches  –  get all the data in tree as list in list
  • <tree name>.Paths  –  get all the paths in tree as list
  • <tree name>.BranchCount  –  get the amount of paths in tree
  • <tree name>.DataCount  –  get the amount of data in tree
  • <tree name>.TopologyDescription  –  get topology description as text