Your First Python Script in Grasshopper with Python

Your First Python Script in Grasshopper

This manual is for Grasshopper users who would like to create their own custom scripts using Grasshopper for Rhino.

Introduction

Scripting components works as an integrated part of GH. They can get input and produce output from and to other standard GH components. They can be used to create specialized functionality that opens up tremendous potential beyond the standard components.

But there is a cool twist… the GhPython component supports rhinoscriptsyntax functions. The rhinoscriptsyntax functions can be set to generate geometry inside of Grasshopper that does not live in the Rhino document. We are using a concept called “duck typing” to swap the document that the rhinoscriptsyntax functions target: from the Rhino document to a Grasshopper document. This means that the following script:

will add 10 points to the Rhino document when run from Rhino’s “_RunPythonScript” or “_EditPythonScript” commands. The same script will add 10 points to a Grasshopper document that can be passed on to other components when run inside a GhPython component.

Grasshopper supports multiple .NET scripting languages such as VB and C# to help develop custom code. There is also the Python component. Python supports multiple programming paradigms, often used as a scripting language, but is also used in a wide range of advanced programming contexts. The Rhino.Python website directory is a great place to get more information about Python in Rhino in general.

The GhPython component brings:

  • Rhinoscript syntax to Grasshopper
  • a Python parallel to the C# and Vb.Net scripting components
  • a dynamic UI with control over the number of inputs and outputs
  • ability to reference .NET libraries and a huge number of Python packages
  • integration with the Python editor included in Rhino

Rhino allows access to its algorithms through the Rhino SDK (software development kit). Rhino is written in C++ but it also provides a couple SDKs for scripting and programming languages. The most basic SDK for Python is RhinoScriptSyntax. For more direct access to Rhino functions, more experienced programmers may choose to use the RhinoCommon SDK. There is extensive documentation about RhinoScriptSyntax and Python on the Developer site. For more details about RhinoCommon, please refer to the McNeel RhinoCommon Developer site.

Where to find the script components

To add the Python script component to the canvas, drag and drop the component from the “Script” panel under the “Maths” tab. The component first shows orange indicating a warning. This is because there is no code typed yet inside it. If you click on the bubble at the top-right corner, you can see what the warning is.

The default script component has two inputs and two outputs. The user can change the names of input and output, the data type and data structure of the input and also add more inputs and outputs parameters or remove them.

  • x: first input of a .NET type (object).
  • y: second input of a .NET type (object).
  • out: output string with compiling messages and prints.
  • A: Returned output of type object.

The HelloWorld Script

Let’s start with the classic “Hello World!” example for our first script.

  1. Drag a Python component onto the Grasshopper canvas.
  2. Add a Boolean component (Params toolbar) and connect it to the x input.
  3. Add a Panel component and connect it to the a output.

The “Hello World!” script will check for a TRUE in x to display the Hello World message through the ‘a’ output.

Double-click on the component to bring up the Python editor:

Type in the following Python code:

Click on the OK button of the editor to get back to the Grasshopper Canvas.

If you toggle the Boolean switch from true to false, the Panel should display Hello World! .

Congratulations! You have compete your first Python script in Grasshopper.

To change the script, double-click o the Python component. Add another line of code:

developer.rhino3d.com

DataTree,List,Item access from grasshopper-python

I’m using the python component for grasshopper, and have wondered to access to the data structure which grasshopper consists.

using a=ghdoc seems to be efficient for output, but I can’t get the right data structure as input.

anything will help.

I’m sure that I’m using the latest component(v0.4.1.1)

Replies to This Discussion

attached here is a simple example to iterate a tree.

EDIT: See on GitHub how to convert a GH tree in a Python list of lists, and vice versa.

Permalink Reply by Yasushi Sakai on May 15, 2011 at 8:02pm

Thanks for the fast reply!

I will take a try and play around with your sample!

Permalink Reply by Benjamin Golder on June 10, 2011 at 4:02pm

Instantiating a Data Tree seems a little trickier:

Permalink Reply by Giulio Piacentino on June 10, 2011 at 4:53pm

DataTree should be made specific with a simple type, like Brep, for example.

Then, layerTree.AddRange(geoms, path) can fill the tree with an enumerable (Add with a single object).

Permalink Reply by Benjamin Golder on June 10, 2011 at 5:39pm

Permalink Reply by Andrew Kudless on February 6, 2012 at 3:23am

Could you give an even simpler example of how to add a datatree for output? Your first example (reading datatrees) was really clear, but I got lost on second example dealing with layernames.

Here’s what I want to do:

I have a for loop in which a new list of points is created at every loop. I want to build a datatree so that each list of points is on a new branch and output from the component.

Permalink Reply by Andrew Kudless on February 6, 2012 at 3:35am

Well, I kind of figured it out (I was caught up in casting the wrong type). Still, a simple example would be great because I think I barely understand what I just did.

Permalink Reply by Giulio Piacentino on February 8, 2012 at 3:51pm

Hi Andrew. Yes, DataTree isn’t a very simple construct by its very nature. it’s easiest when it can be avoided entirely, really. a way might be to graft the list output of your script.

At the same time, maybe I can come up with a simpler example if I can use Add() and not AddRange(). Would that be appropriate in your maybe larger case?

Permalink Reply by Benjamin Golder on March 4, 2012 at 1:34pm

I think it’s reasonable to assume that scripters will often want to be able to create DataTrees.

Is there a way to create a DataTree with dynamic data? How could I create a DataTree that holds lists of strings, numbers, and geometry?

Permalink Reply by Giulio Piacentino on March 5, 2012 at 6:27am

it is reasonable that scripters need to use DataTrees but also highly improbable that they need to construct them directly. 95% of the scripts handle lists and single items and return lists. Grasshopper then iterates the logic to create the tree. However, rare cases where full tree creation is needed do come up, so the possibility is provided by the Grasshopper SDK.

I would really not suggest to mix different data types into a single DataTree output. This might indicate instead that multiple output trees should be given as outputs. I cannot identify a single Grasshopper component that returns trees of mixed strings and numbers, for example.

In any case, you can construct a DataTree of objects

and this will accept any input of single data items. This is really part of the Grasshopper SDK, not something particular to Python or GhPython.

I hope this helps,

I just saw this post, but needed to address it because I had forgotten how to it myself.

Here is an example, as python code:

And here are some pictures:

This particular script relies on accessing a list of incoming data, (because it makes a branch for each item, basically it performs a graft.

It also relies on a certain type casting of the incoming data. Notice the line where I make the tree:

DataTree [ Rhino . Geometry . GeometryBase ]()

In this line, I declare the type of data contained in this tree. My input should reflect this choice :

Permalink Reply by 2crunchy on September 10, 2012 at 4:35pm

I’m hoping someone can help with an example that just uses lists, as opposed to GeometryBase.

I’m working with a dynamic list of lists inside Python and am trying to output to grasshopper.

For example I have a list [[[0,1,2],[5,6],[12,13,14,15]], [[2,3],[6]. ] ]

I set up a more simplified (2d array) example in the attached image:

www.grasshopper3d.com

Using Python in Grasshopper

In the previous section we saw how Grasshopper, despite being a great platform for algorithmic design, can also be limiting when trying to incorporate more complex programming elements. On the other hand, programming directly with computer code in a programming language like Python gives us much more control over our models and allows us to develop more complex and interesting design spaces but has a much higher learning curve and can be quite intimidating when first starting out.

So how do we choose one over the other? Luckily we don’t have to! In fact we can easily extend the basic functionality of Grasshopper by embedding Python code directly into special Grasshopper nodes that can then interact with other nodes in our model. This allows us to rely mostly on Grasshopper for basic elements, and use code only when necessary for more complex functionality.

Why Python?

As discussed previously, there are now hundreds of different programming languages to choose from — so why would we choose to work with Python?

Python is a very modern, general-purpose and high-level object-oriented programming language. In recent years Python has become extremely popular in a variety of fields outside of computer programming such as science, medicine, statistics, math, and machine learning. This popularity can be attributed to Python’s

  • relatively simple syntax, with a focus on simplicity, clarity, and readability which makes it less complicated to learn and write
  • extensibility through a large collection of external libraries
  • a huge support community of active users.

Unlike more complex languages such as C++, Python is not meant for full software development. Because of it’s emphasis on ease of use, it also tends to be less efficient and somewhat slower than these languages, but this is usually not an issue for applications outside of software development.

Lately, Python is also starting to be embedded as a scripting language within many different design software, including ArcGIS, QGIS, Rhino, Solidworks, and Autodesk Fusion. This is a big change from earlier years when every design tool had it’s own proprietary scripting language (Rhinoscript for Rhino, EKL for Catia, Actionscript for Illustrator), so you had to learn a whole new language each time you used a new tool. Integrating Python as a standard scripting language allows designers to learn a single language and use it to control a variety of design software. So if you are not a programmer but want to learn one programming language that will give you the most use in your design career, there is a strong argument that the language should be Python.

Python in Rhino and Grasshopper

Starting in version 5 Rhino has Python directly embedded alongside (and as an eventual replacement for) Rhinoscript. In addition to running any standard Python code, it can also communicate with the Rhino interface and work with geometry by using a set of special Python libraries provided by Rhino. Using these libraries designers can use Python to control almost every feature of Rhino, from the model geometry, to its views, cameras, and even the user interface.

You can also work with Python directly in Grasshopper through an external plugin called GHPython. This plugin gives you a ‘Python’ node in Grasshopper which allows you to embed code into your models. Code written in these nodes uses the same libraries to handle geometry and perform various modeling tasks, and is able to communicate with both the Grasshopper and Rhino environments.

The great thing about the GHPython node is that it allows you to mix and match between working with code and normal Grasshopper nodes. This way, there is no pressure to develop your entire model just through code starting with a blank text file, which can be very intimidating for people just starting out with scripting or computational design. Instead, you can develop most of the model using standard Grasshopper nodes, and only use Python nodes to do more complex tasks that are difficult or impossible in standard Grasshopper. In a way GHPython is like a ‘gateway drug’ into using code for computational design. You can start off by writing small, simple scripts for specific purposes, and gradually develop more and more complex code as you learn.

Installing the GHPython library

Unfortunately the GHPython library does not come pre-installed with Grasshopper and must be download and installed separately. Luckily this is very easy to do:

1. Go to http://www.food4rhino.com/app/ghpython and download the latest stable version. At the time of this writing 0.6.0.3 was the latest version and has been tested to work with all the examples in the class.

2. The library is contained in a single file called ghpython.gha. Once this file is downloaded, right click on it and go to properties. If there is a button or a checkbox in the properties window that says ‘Unblock’, check it or click on it to disable the blocking so that Grasshopper can see the file.

3. To load the library into Grasshopper you need to put this file into a special ‘Components’ folder where all the libraries are kept. The easiest way to find this folder is to launch Grasshopper and from the menu go to File -> Special Folders -> Components Folder. Now copy and paste the ghpython.gha file into this folder.

4. To see the GHPython node you need to restart Grasshopper either by restarting Rhino or typing the GrasshopperUnloadPlugin command in Rhino to shut down Grasshopper and then restart it. If you just close the Grasshopper window it only hides it and does not actually shut it down.

Using the GHPython node

The GHPython library ads just one additional node to Grasshopper. You can find it under the Maths tab.

Let’s put one of these nodes onto the canvas and see how it works. You can see that the Python node has input and output ports just like any other node in Grasshopper, except it can have any number of inputs and outputs and you can call them whatever you want.

You can add more inputs and outputs by zooming in on the node until you see minus icons appear next to the input/output names and plus icons appear between them. You can use these icons to either add or remove inputs and outputs. You can also rename them by right clicking on the name and entering a new name in the text box at the top of the menu.

These inputs and outputs are automatically brought into the Python script where you can use them as variables. This allows the Python script to interact with the rest of your Grasshopper model by bringing data in through input variables and then outputting other data that was created within the script.

Double clicking on the center of the node brings up the script editing window where you can write the actual Python code. Let’s create a simple ‘hello world’ example to see how this works.

Change the name of one of the Python node’s inputs to ‘input’ and the name of one of the outputs to ‘output’. Plug a text panel into the input and type whatever you want into the panel. Attach another text panel into the output so we can see the results.

Now type this line of code into the script window:

and click the ‘Test’ button at the bottom of the window. This button will execute the script and you should see the results above. Clicking OK will save changes to your script and close the editor window. Clicking Close will close the window without saving changes. This simple example brings in text from the Grasshopper model through its input node, joins this text to another piece of text, and then assigns the result to the output node, which can then be used in the Grasshopper model.

Integrating code into Grasshopper like this is a very powerful way to extend the basic functionalities of Grasshopper and will allow us to create interesting and complex design spaces using the full tools of computation. The next series of posts will go through how to work with the five fundamental elements of programming in Python and introduce you to some of the basic concepts of the language. Although we won’t be connecting the nodes to anything yet, you can follow along with the code examples by entering them directly into the Python node script editor. Once we establish some of the basics, the following section of posts will go over how we can use Python to work with geometry and interact with other Grasshopper nodes.

For more information about learning the Python programming language you can follow these guides:

For more specific information on working with Python in Rhino and Grasshopper you can consult these resources:

medium.com

Grasshopper data trees and Python

This guide describes how to use data trees in Python.

Data trees, technically

The data tree data structure is a complex data structure that is best kept in Grasshopper realms. It is a .Net class that is part of the Grasshopper SDK and, as such, all its members can be found on the DataTree class Grasshopper SDK documentation site.

On the implementation side, in Python it can be thought as an object with behavior similar to a dict — really, System.Collections.Generic.SortedList — of GH_Path s, or Grasshopper.Kernel.Data.GH_Path. For each one of the paths-keys inside, there is an associated .Net list-value, that is a branch. Items are stored in each list. There is no null-path, but paths can be sparse. Items cannot be sparse, but there can be null-items.

Other data structures would also be able to accommodate similar data. In Python, a similar object with better language support would be a list of lists.

However, a list of lists cannot always represent the merging of two datatrees with different dimensional depth in data (example: a datatree with an item at <0;1>[0] and an item at <0>[1]). If the data tree is constructed by normal and integral Grasshopper logic, it will have constant dimensional depth, and therefore this problem can be avoided. Alternatively, the data tree with inferior dimension can be ‘grafted’ to a branch of an upper dimension, and also this way the problem is avoided.

Coding against the DataTree class

This example shows how to iterate through any data tree and explain the content of it.

On the opposite side, this example shows how to create a data tree from scratch:

A simpler way, coding against lists of lists

As mentioned under the first heading, when possible, it is easier to code against nested lists (lists of lists) in Python, to leverage this more ubiquitous programing paradigm. The ghpythonlib.treehelpers module contains functions that transform trees to nested lists, and vice versa.

The first two examples can be translated to

developer.rhino3d.com

Grasshopper python example

0. GH Python References & Resources

— RhinoPython Reference
http://4.rhino3d.com/5/ironpython/
(In Rhinoceros menu) Tools > PythonScript > Edit
(In Rhino Python Editor menu) Help > Python Help

1. GH Python Basics

— 1-4. If Condition GH file

— 1-5. If Condition (2) GH file

— 1-6. Math Library GH file

— 1-7. Random Number GH file

— 1-8. 2D Nested For Loop GH file

— 1-9. And/Or Condition in Loop GH file

— 1-10. Conditions and Patterning GH file

2. GH Python: Inputs

— 2-1. Integer/Float Input GH file

— 2-3. Point Input (2): Building Geometry Inside Script GH file 3DM file

— 2-4. Point Input (3): Point Clustering GH file

— 2-5. Curve Input: Lines Between Closest Division Points GH file 3DM file

— 2-6. Curve Input (2): Intersections GH file 3DM file

— 2-7. Surface Input : Panelization GH file 3DM file

— 2-8. Surface Input (2) : Panelization GH file 3DM file

— 2-9. Surface Input (3) : Panelization GH file 3DM file

— 2-10. Surface Input (4) : Panelization GH file

— 2-11. Surface Input (5) : Panelization GH file

— 2-12. Surface Input (6) : Panelization GH file

— 2-13. Tree Input: Iteration of All Elements GH file

— 2-14. Tree Input (2): Iteration with Conditions GH file

— 2-15. Tree Input (3): Connecting Closest Tree Elements GH file 3DM file

3. GH Python: Function and Recursion

— 3-1. Simple Function with One Argument GH file 3DM file

— 3-2. Function with Three Arguments GH file 3DM file

— 3-3. Line Branch Function GH file

— 3-4a. Recursion with Line GH file 3DM file

— 3-4b. Recursion with Line GH file

— 3-4c. Recursion with Line GH file

— 3-4d. Recursion with Line GH file

— 3-5a. Branching Lines with Recursion GH file 3DM file

— 3-5b. Branching Lines with Recursion GH file

— 3-6. Rectangular Surface Recursion GH file

— 3-7. Branching Lines and Boxes with Recursion GH file

— 3-8. Box Subdivision on Surface GH file

— 3-9. Hexagonal Branching by Recursion GH file

— 3-10. Subdividing Mesh with Recursion GH file 3DM file

4. GH Python: Baking and Object Attributes

— 4-1. Baking Points with Colors GH file

— 4-2. Baking Curves with Colors GH file

— 4-3. Baking Surfaces with Simple Materials GH file

— 4-4. Baking Breps with Simple Materials GH file

— 4-5. Setting Materials by Attributes GH file

— 4-6. Setting Materials by Name GH file

— 4-7. Baking into Layers GH file

— 4-8. Baking Input Objects with Attributes GH file

— 4-9. Panelization with Materials (1) GH file 3DM file

— 4-10. Panelization with Materials (2) GH file 3DM file

5. GH Python: Object-Oriented Programming

— 5-1. Defining A Class with A Constructor GH file

— 5-2. Adding A Method GH file

— 5-3. Adding A Method with A Return Value GH file

— 5-4. Adding More Methods GH file

— 5-5. Class As Geometric Module(1) GH file

— 5-6. Class As Geometric Module(2) GH file

— 5-7. Class As Geometric Module(3) GH file

— 5-8. Class As Geometric Module(4) GH file

6. GH Python: Connective Module

— 6-1. Connective Module 1: Connection by Distance GH file

— 6-2. Connective Module 2 : Sort and Maximum Link Count GH file

— 6-3. Connective Module 3 : Tree Output GH file

— 6-4. Connective Module 4 : 3 Points Output GH file

— 6-5. Connective Module 5 : Face Points Output GH file

— 6-6. Connective Module 6 : Point Output for Specific Geometry Component GH file

— 6-7. Connective Module 7 : Different Module Types and Links GH file

7. GH Python: Custom Subdivisions

— 7-1. Vertex Control 1: Offset Vertices GH file

— 7-2. Vertex Control 2: Randomize Vertices GH file

— 7-3. Vertex Control 3: Move Vertices by Attractors GH file

— 7-4. Subdivision 1: Triangle Center Subdivision GH file

— 7-5. Subdivision 2: Triangle Subdivision with Vector Interpolation GH file

— 7-6. Subdivision 3: Quad Center Subdivision GH file

— 7-7. Subdivision 4: Quad Subdivision with Vector Interpolation GH file

— 7-8. Subdivision 5: 1D Fractal Quad Subdivision GH file

— 7-9. Subdivision 6: Triangular Probabilistic Subdivision GH file

— 7-10. Subdivision 7: Frame Subdivision GH file

— 7-11. Subdivision 8: Frame Probabilistic Subdivision GH file

— 7-12. Subdivision 9: Quad Subdivision GH file

— 7-13. Subdivision 10: Triangular Subdivision GH file

— 7-14. Subdivision 11: Quad Subdivision with Randomness GH file

— 7-15. Subdivision 12: Quad Subdivision with Attractors GH file

— 7-16. Subdivision 13: Quad Subdivision with Depth Control by Bitmap GH file 3DM file

— 7-17. Subdivision 14: Frame Subdivision with Recursion Control by Bitmap GH file 3DM file

— 7-18. Subdivision 15: Quad Probabilistic Subdivision with Depth Control by Area GH file

— 7-19. Subdivision 16: Linear Subdivision GH file

— 7-20. Subdivision 17: Tubular Subdivision GH file

— 7-21. Subdivision 18: Tubular Subdivision with Tab Faces GH file

— 7-22. Subdivision 19: Long Edge Subdivision GH file 3DM file

— 7-23. Subdivision 20: Mesh Face Offset with Attractors GH file

— 7-24. Subdivision 21: Mesh Face Offset with Randomness GH file

— 7-25. Subdivision 22: Extruded Face Offset with Attractors GH file

— 7-26. Subdivision 23: Polyhedron Face Offset with Randomness GH file

— 7-27. Subdivision 24: Vertex-Based Subdivision 1 GH file

— 7-28. Subdivision 25: Vertex-Based Subdivision 2 GH file

— 7-29. Subdivision 26: Vertex-Based Polyhedron Subdivision GH file

— 7-30. Custom Mesh Tool 1: Dispatch Faces Randomly GH file

— 7-31. Custom Mesh Tool 2: Dispatch Faces by Attractors GH file

— 7-32. Custom Subdivision Combination Example 1 GH file

Randomize Vertices (7-2)
+ Dispatch Faces Randomly (7-23)
+ Triangulate (Grasshopper mesh command)
+ Mesh Join (Grasshopper mesh command)
+ Weld Mesh (Grasshopper mesh command)
+ Frame Probabilistic Subdivision (7-11)
+ Mesh Thicken (Weaverbird command)
+ Frame Probabilistic Subdivision (7-11)
+ Catmull-Clark Subdivision (Weaverbird command)
+ Mesh Thicken (Weaverbird command)
+ Quad Subdivision with Attractors (7-15)

— 7-33. Custom Subdivision Combination Example 2 GH file

— 7-34. Custom Subdivision Combination Example 3 GH file

— 7-35. Custom Subdivision Combination Example 4 GH file

— 7-36. Custom Subdivision Combination Example 5 GH file

Linear Subdivision (7-19)
+ Mesh Join (Grasshopper mesh command)
+ Weld Mesh (Grasshopper mesh command)
+ Linear Subdivision (7-19)
+ Mesh Join (Grasshopper mesh command)
+ Weld Mesh (Grasshopper mesh command)
+ Triangulate (Grasshopper mesh command)
+ Dispatch Faces Randomly (7-23)
+ Linear Subdivision (7-19)
+ Frame Subdivision (7-10)
+ Mesh Join (Grasshopper mesh command)
+ Weld Mesh (Grasshopper mesh command)

atlv.org

Share:
No comments

Добавить комментарий

Your e-mail will not be published. All fields are required.

×
Recommend