How to use GhPython

From TOI-Pedia

Introduction

LEVEL: INTERMEDIATE
Expected Time: 90 min
An example of a TU Delft student project using Python in Grasshopper

In this tutorial, we will dive into the basics of using GHPython. In the beginning of this tutorial, we will explain you why to use Python. If this is still hard to understand, continue reading, to the part where we explain how to use it. Next, we create a basic Pythagoras formula in Python. Finally, this tutorial will conclude with an overview of modules that are relevant for Python programming in Grasshopper.

What is GH python?

The GhPython logo

Python is a programming language that can be used for scripting in Grasshopper. Besides Python there are other programming languages available: C# and VB. Python in general, is known for its easy to read language and extensive amount of open-source plugins. Therefore it is a good language to start learning programming after learning the basics of Grasshopper. Grasshopper is using a specific version of Python: Iron Python 2.7 (June, 2021) Therefore, unfortunately, you do not have access to all online available modules for Python, but still, it is a very useful tool for algorithm design in Grasshopper.

Why using GhPython?

So far in the Grasshopper tutorials, we have only covered functions that are pre-made by the developers of Grasshopper. Most of the time, these functions should suite all your needs creating a basic algorithm. However, sometimes it can be useful to develop a function yourself. Situations where it might be useful are:

  • Functions that are not available in Grasshopper;
  • Functions of Grasshopper that are not efficient or fast enough;
  • Scripts that need some kind of looping implemented.
  • Situations where you want Grasshopper to interact with other software or your PC;
  • Scripts that use more complex data structures like JSON or python dictionaries.
  • Creating and sharing your own components.


Why not using GHPython?

Although programming your own components may sound appealing, there are also disadvantages of using Python in Grasshopper.

  • The Python interface of Grasshopper does not have an extensive debugger. Simply said, a debugger is a tool that notices and marks mistakes in your script. You can compare it with spelling correction.
  • Most Grasshopper scripts can be created without programming. Only in specific cases, you might really need it because there is no alternative.
  • Iron Python 2.7 does not support important modules like Numpy and Scipy (June, 2021). There are some workarounds to be able to do this, but it is not recommended for people starting with Python.


How to use GHPython?

Add a Python component to the canvas

Just like other Grasshopper function, GHPython has a specific component that can be added to the canvas. For simplicity, in this tutorial you will learn how to create a Pythagoras function

Add a Python component to the canvas. As you can see, the component has two inputs and two outputs. All inputs and outputs can be defined by the developer, except for the "out" parameter. This output can send the developer a message about the running of the script. For example, when the inputs are not correctly defined, the output sends a message where it goes wrong.

  • Add a Python component to the canvas


Let's edit the settings of the inputs and outputs of the component. A Python input needs information about three aspects:

  • The name of the input;
  • The variable type of the input;
  • The data type: a single item, a list or a data tree.
  • For the output, you only need to set a name.


Rename the inputs and output

The name of the inputs and outputs can be changed by right-clicking and typing a name in top bar. Set the name to A, B and C.

  • Set the input names to A and B;
  • Set the output a to the name C.


Change the variable types of the inputs

The variable type can be changed by right clicking on the in/output and selecting Type hint. Some developers of McNeel suggest that the script runs faster when we set the type to "No type hint". However, for good practice, set the types to float.

  • Change the variable types of input A and B to floats RMB on input » Type hint » Float

A float is a finite decimal number, in contradiction to an integer, which has no decimals.

The available data types

Finally, we need to set the data type. Since we only want to calculate one value, you can leave the Data Type to Item Access.

Connect two slider to the A and B input

Connect two Number Sliders to the A input and the B input. As you probably know, our script will calculate the root of A squared plus B squared.

  • Connect a Number Slider to A and B Params » Input » Number Slider


Open the Python Script Editor

Now we need to open the script. Double click on the Python icon. A new viewport will be opened with a basic script.

  • Open the Python Script Editor Double click on Python logo

Let's go through the basics. The first lines of the script display a green text. This text is cited as what we call a multi-line string. A string is a line of text that Python handles as text, not as numbers, vectors etc.

Change the input and output descriptions

By changing the Inputs and Output text to our initially created variables, we can add a description.

  • Change the description to our Pythagoras definition


Holding your mouse on an input or output displays our description

Click on OK, the Python viewport will be closed. When we now hold our cursor above one of the inputs or output, you can see that the description has changed.

  • Click on OK
  • Hold your mouse on the inputs or output to display a description


Author and version of the script

Open the Python editor again. After the script description, you will find information about the author and the version. This can be useful if you want to share a script with others.

Importing modules to your script

In the next line after the script description, you can find the imported modules. Standard, Python adds the Rhinscriptsyntax module which enables the Rhino functions in your script.

Other modules are also available, just type import and you will see a list of extra modules. For example, importing the Random module will give you access to functions that generate pseudo random numbers.

A module is a piece of Python code that contains several useful functions for scripting. The basic library of Python includes some modules that include essential function necessary for programming. Splitting up a programming language into multiple modules, has the advantage that a basic script does not include more data (functions) than it actually needs.

Some basic programming code

At line 13, you can start writing your own code. Let's start with printing a basic text.

  • Type print("Hello World")
  • Click on Test

In the output you will see the message "Hello World"

Oops, we forgot a bracket...

Click on Ok and connect a panel from the out output. You will see that grasshopper prints the text Hello World. Usually we do not use the out output for variables that we want to get with our script. The output is used for error messages. For example, remove the last bracket in your script and click on Test. The output will give an error in line 13: a SyntaxError. This happens when you make a mistake in your script.

  • Remove the code from the previous step.


Type the Pythagoras formula

To calculate the Pythagoras formula, we will need to calculate the square root. Unfortunately, there is no such function available in standard Python. Therefore we import it from the Math module.

  • Import the sqrt function from the math module
  • Now type C = sqrt(A * A + B * B) in line 14
  • Click on Ok


The result of our script

By connecting a panel you will see that the C outputs the result we needed.

The result of our script

Next, we will try something more complex. Let's say we want the result of a list of values. Connect a panel with multiple values to the A input. You will see that this results in a list of outputs.

  • Connect a list of values to the A input

Don't forget to set the panel to multiline data.

Implicit Grasshopper Cycles

If you do the calculation again within the Python Script Editor, you will see a message that there is an implicit Grasshopper Cycle. This is caused by the fact that we didn't change the A input data type: a list of values.

Change the A input to List Access
  • Change the A input data type to list.


Error...

Unfortunately, our script is not working anymore. Python does not know how to multiply a list of values by one single number. Therefore we would need to create a manual for-loop.

Looping over the list of values

This tutorial would dive too deep into the matter explaining how to program in Python. Online, many tutorials are available to explain you the basic procedures. For now type the following text, exactly as in the image.

  • Type the code similar to the following illustration


The result without implicit cycles

By clicking on OK you will see the result we were expecting.

Make a more complex formula

Within the two brackets, you can also make a way more complex function. For example:

The final result

You now get a list of the results with different variables.

Efficiently Printing

Set the output panel to text

For calculations with loads of values (in the range of 10000s), printing a result can take a while. Set the output mode to text to make your script run more efficiently.

Modules

In this chapter, we will discuss some important modules of GHPython. Modules can be imported by adding an extra line after the “import rhinoscriptsyntax” statement. By adding the “as …” you can make a simplified version of the name, to access it more easily. For example, by using the function tu.tudelftiscool(), you would use the function tudelftiscool() from the module tu.

Ghpythonlib

Import the Ghpythonlib module

The Ghpythonlib consists out of five separated submodules. These modules are used to do basic interactions with Grasshopper. Three of these submodules are relevant for starters with Python. Just import this module by adding a line with “import ghpythonlib” followed by a dot with the corresponding submodule.

Ghpythonlib.components

Create a circle with Ghpythonlib.components

The components submodules gives access to all available functions in the Grasshopper. For example, you can create a circle with the ghpythonlib.components.circle function(). When you enter the function, the Help panel will give some suggestions for the inputs and outputs. As you can see, the function requires a Plane, which we can add on the canvas, and a radius. Finally, the function returns a circle.

Ghpythonlib.treehelpers

Two functions in the treehelpers submodule

When you connect a Data Tree to a Python component, the data needs to be converted to be used by python. Specifically, python handles a data tree as a list-in-list structure. The Treehelpers submodule has two functions: convert a tree_to_list (input), and convert a list_to_tree (output).

Convert a data_in Data Tree to a lists-in-list structure

When you are using the tree_to_list function, make sure you always add the "None" statement, behind the first parameter of the function. Otherwise, Python will only extract the first branch of your Data Tree.

A lists-in list structure printed in the Output panel

A printed version of a Data Tree looks like the following illustration. Make sure you set the input type to Data Tree. Also make sure you simplify the input. Otherwise the result will be a list in a second list in a third list.

To get the data from Python to Grasshopper again, you will need to convert it back to a Data Tree using the list_to_tree function.

Ghpythonlib.parallel

Use the CurveClosestPoint function with multiple CPU cores

This is a complex topic for developers with more experience in Python. Skip this part if you are a beginner.

This submodule is used for parallel CPU core computing. It can be helpful to make algorithms with big data sets run more efficiently. The parallel function uses a definition with one parameter and a list of values. Next, using multiple cores, the function iterates over the list of values. The last (boolean) parameter of the parallel function indicates if the result can be flattened. This will lead to a more efficient calculation, but the result will be in a different order than the input.

The right images gives an example of parallel computing. In the case of this example, we used a CurveClosestPoint function of the GhPythonlib module. In practice, it is recommended to only use functions from the Rhinoscriptsyntax or RhinoCommon library, which will be explained in th next chapters.

Rhinoscriptsyntax

Using Rhinoscriptsyntax to find the closest point parameter on a curve

This module allows you to use Rhino geometry, commands, document objects and application methods. More information about this module can be found at: RhinoScriptSyntax in Python with Python (rhino3d.com). If you need to find a specific function, take a look at the developers documentation: rhinoscriptsyntax (rhino3d.com)

Rhino (RhinoCommon)

All functions in Rhinoscriptsyntax are created using RhinoCommon. RhinoCommon is a software development kit that was used to develop Rhino for both Windows and Mac. You can get access to the function by importing the Rhino module.

Rhino.geometry

Create a 2d point with an x and y coordinate

Next to Rhinoscriptsyntax and the Ghpythonlib, you can use Rhino.geometry to create Rhino objects with your script. Rhino.geometry is the most in-depth version of using Rhino functions and therefore has the greatest amount of options available. All available functions can be found in the RhinoCommon API of McNeel: Rhino.Geometry Namespace (rhino3d.com). The API is focused on C# and VB. Therefore you will not find an extensive explanation for Python. However, by adding the function in the Python Script Editor, you will find some information in the Help tab.

Random

Generate a random integer between 0 and 10

The random module is used to generate pseudo random integers, floats, lists of numbers etc. When importing, the random module may not be directly visible in the list of available modules.

Math

Calculate the cosine of an angle

Math can be used for complex mathematical calculations. For example calculating the cosine of a number.

How to continue?

Ladybug Sunpath Shading Python script

You have now read the basics of Python programming in Grasshopper. Although this tutorial does not explain you how to program, you now know how to implement it in Grasshopper. It may still be a bit overwhelming so here are some suggestions to get started:

  • Follow some online tutorials about Python that cover the basics of: variable types, if-else statements, for-loops and basic external modules. Use a programming environment like Spyder or preferably Visual Studio Code.
  • Practice your Python programming in Grasshopper by recreating a Grasshopper script in Python. Try to use the Rhinoscriptsyntax and RhinoCommon, not the GHPythonlib. In the beginning: focus on mathematical equations and calculations.
  • Take a look at complex Python algorithms in Grasshopper from plugins. For example, ladybug was fully written in Python. You can learn a lot by just figuring out how it works.
  • Challenge yourself by thinking of a project that would not be possible in Grasshopper. Experiment, use the McNeel forum, make mistakes and practice!


Personal tools
Actions
Navigation
Tools