# Tutorials

Welcome to the Py-Engineering tutorials. These instructions will get you up and running in no-time. More in depth information about each subject can be found in the Documentation. Ready to start, but no Py-Engineering account yet? Request a demo!

Please stay tuned as we keep on working on a more tutorials to cover all features.

# Tutorial A: Basic example

We’ll start this example covering the basic concept of a tool in Py-Engineering.com. In this basic example we will, step by step, create a simple tool to calculate the length of the sides of a triangle using the Pythagoras theorem.

This can be done in the platform menu directly or by clicking ‘add tool’ in Platform ‣ Tools.

The least you have to provide is a name and a slug. The name will appear as title of your tool. Slug has to be unique and defines the URL that can be used to access the tool. In this example, we’ll name our tool Pythagoras.

Go to Platform ‣ Tools ‣ Add tool

 Name Pythagoras Defines name of tool Slug  pythagoras  https://py-engineering.com/examples/ pythagoras

## Step 2: Main script

A tool on Py-Engineering takes user input and runs a python function to print and/or return some output. Say we want to use side A and B of a right triangle to determine the length of the side C, opposite the right angle with the Pythagorean theorem. We need to write a very basic python function like this:

Python code
import math

def main_function(input_dict):

a = input_dict['a']
b = input_dict['b']
c = math.sqrt(a ** 2 + b ** 2)

print(f'a = {a}')
print(f'b = {b}')print(f'c = {c:.1f}')

return {'c': c}


You’re free to define the python script with many other functions or classes, but the function that runs by clicking ‘Calculate’ has to be called main_function and takes a dictionary called input_dict as argument. Everything printed by the python script will show up in the results tab of the tool.

The return value of main_function will not be shown in the Results tab of the GUI and might as well be None. However, the tool can also be accessed through an API where the return value is retrieved in case it is a dictionary. Read more about this in the tutorial .

## Step 3: Input parameters and graphical user interface

All keys as expected to be present in the input_dict have to be defined as input parameters. The least you have to provide is a code which corresponds to the key in the input_dict as used in the python function. In this example, that’s a and b. The parameter can also have a name and/or a unit. Input_type is an integer in this example and determines the type of the value in the input_dict.

## Step 4: Info tab

By now, the tool is ready to be used. Just to provide the user some background information, we’ll add an extra tab that will appear in the GUI next to the ‘Results’ tab. These so called info tabs can be defined using HTML. The first tab, based on order will be visible by default. We’ll use the following html for a tab called ‘Info’.

Go to Platform ‣ Info tabs ‣ Add info tab

 Name Information Information [en] see HTML below
HTML code
<p>
In mathematics, the Pythagorean theorem, also known as Pythagoras' theorem,
is a fundamental relation in Euclidean geometry among the three sides of a right triangle.
</p>

<img class="img-fluid" style="display: block; margin-left: auto; margin-right: auto;" src="https://pye-fileserver.s3.eu-central-1.amazonaws.com/media/public/images/pythagoras_AgL1OaF.png" alt="Pythagoras" width="262" height="131" />

<p>
It states that the square of the hypotenuse (the side opposite the right angle)
is equal to the sum of the squares of the other two sides. The theorem can be written
as an equation relating the lengths of the sides A, B and C, often called the "
Pythagorean equation" where C represents the length of the hypotenuse and A and B
the lengths of the triangle's other two sides.
</p>


## Step 5: Result

Fill the form and click ‘Calculate’ in the embedded tool below or click here to view the tool on Py-Engineering.com.

# Tutorial B: Input types

This example uses a copy of the basic tool as created in . Here we’ll explore more input types and their behavior in the GUI.

## Step 1: Integer (slider)

By default, an input variable is defined as input type integer. In the GUI, a html input element for numbers will be available. If lower and upper bounds for the parameter are defined, the input type can also be a slider. In the block input parameters and graphical user interface, select integer (slider) from the input type dropdown.

## Step 2: Boolean

Input type boolean can be used in the input dictionary with python values True or False. It appears in the GUI as a checkbox. Say, we want to optionally calculate the angles of the triangle. The user can check ‘Show angles’ before clicking ‘Calculate’.

In the block Main script, the python script is extended with an if statement to optionally print the angles in degrees

Python code
import math

def main_function(input_dict):

a = input_dict['a']
b = input_dict['b']
c = math.sqrt(a ** 2 + b ** 2)

print(f'a = {a}')
print(f'b = {b}')
print(f'c = {c:.1f}')

angle_ac = math.atan(b / a) * (180 / math.pi)
angle_bc = math.atan(a / b) * (180 / math.pi)

if input_dict['calculate_angles']:
print(f'Angle AC = {angle_ac:.1f} degrees')
print(f'Angle BC = {angle_bc:.1f} degrees')

return {'c': c}

## Step 3: Result

Fill the form and click ‘Calculate’ in the embedded tool below or click here.

# Tutorial C: Input list

Form elements that use a set of options like radio buttons and dropdowns can be created using Input lists. In this tutorial, we create a tool that includes a radio button with two options.

## Step 1: Main script

Like in , a python function defines the tool. In this case we take the variables shape, r and h and calculate the surface area of either a cone or a cylinder.

Python code
import math

def main_function(input_dict):

shape = input_dict['shape']
r = input_dict['r']
h = input_dict['h']

if shape == 'cone':
a = math.pi * r * (r + math.sqrt(r ** 2 + h ** 2))
if shape == 'cylinder':
a = 2 * math.pi * r * (r + h)

print(f"The surface area of a {shape} = {a:.1f}")

return

## Step 2: Info tab

An info tab containing a HTML table shows the user the difference between a cone and a cylinder with their attributes and formula to calculate the surface area.

HTML code
<table class="table">
<tr>
<th>Shape</th>
<th>Formula</th>
<th>Variables</th>
</tr>
<tbody>
<tr>
<td>Cylinder<br>(incl. bottom and top)</td>
<td><i>A = 2&pi;r(r+h)</i></td>
<td>
<a title="Ag2gaeh, CC BY-SA 4.0 <https://creativecommons.org/licenses/by-sa/4.0>, via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File:Zylinder-1-tab.svg"><img width="128" alt="Zylinder-1-tab" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/81/Zylinder-1-tab.svg/128px-Zylinder-1-tab.svg.png"></a>
</td>
</tr>
<tr>
<td>Cone<br>(incl. bottom)</td>
<td>
<a title="Ag2gaeh, CC BY-SA 4.0 <https://creativecommons.org/licenses/by-sa/4.0>, via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File:Kegel-1-tab.svg"><img width="128" alt="Kegel-1-tab" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/Kegel-1-tab.svg/128px-Kegel-1-tab.svg.png"></a>
</td>
</tr>
</tbody>
</table>


## Step 3: Input parameters and graphical user interface

The arguments r, h and shape that are used in the python function need to be defined as input variables. For shape, well select input type radio.

## Step 4: Input list

At this point, the form element for shape only shows the label ‘Shape’. We want to provide the user two radiobuttons which will set the value of shape either to ‘cone’ or ‘cylinder’. This can be achieved by adding an input list.

In this case we limit the input list to one level which basically means it’s a list of options. These options can be provided in a JSON script as shown below. The JSON object should include a list with the name ‘choices’. The list itself contains objects with at least the names ‘id’ and ‘name’. ‘id’ is the actual value provided in the input dictionary. Name is the name used in the form element.

JSON code
{
"choices": [
{
"id": "cylinder",
"name": "Cylinder"
},
{
"id": "cone",
"name": "Cone"
}
]
}


## Result

Fill the form and click ‘Calculate’ in the embedded tool below or click here .

# Tutorial D: Input related actions

This tutorial takes a copy of where we add the option ‘Cuboid’ to the input list ‘shapes’.

## Step 1: Main script

We’ll modify the script so that the surface area of a cuboid is shown if that shape is selected.

Python code
import math

def main_function(input_dict):

shape = input_dict['shape']
r = input_dict.get('r', 0)
h = input_dict.get('h', 0)
a = input_dict.get('a', 0)
b = input_dict.get('b', 0)
c = input_dict.get('c', 0)

if shape == 'sphere':
area = 4 * math.pi * r ** 2
if shape == 'cuboid':
area = 2 * (a*b + a*c + b*c)
if shape == 'cone':
area = math.pi * r * (r + math.sqrt(r ** 2 + h ** 2))
if shape == 'cylinder':
area = 2 * math.pi * r * (r + h)

print(f"The surface area of a {shape} = {area:.1f} mm_sup[2_sup]")

return

## Step 2: Input parameters and graphical user interface

As the main script shows: We might have a, b, and c in the input dictionary. Therefore, we need to define it as input variables. In this case integers with the label ‘Side’, abbreviation a, b and c and unit mm.

## Step 2: Input list

Since shape can now also have the value ‘cuboid’, we need to add this option to the input list.

JSON code
{
"choices": [
{
"id": "cuboid",
"name": "Cuboid"
},
{
"id": "cylinder",
"name": "Cylinder"
},
{
"id": "cone",
"name": "Cone"
}
]
}

## Step 3: Info tab

An extra row in the HTML table in the info tab shows the user the different shapes with their formula for the surface area

HTML code
<table class="table table-responsive">
<tr>
<th>Shape</th>
<th>Formula</th>
<th>Variables</th>
</tr>
<tbody>
<td>Cuboid</td>
<td><i>A = 2(ab + ac + bc)</i></td>
<td>
</td>
</tr>
<tr>
<td>Cylinder<br>(incl. bottom and top)</td>
<td><i>A = 2&pi;r(r+h)</i></td>
<td>
<a title="Ag2gaeh, CC BY-SA 4.0 &lt;https://creativecommons.org/licenses/by-sa/4.0&gt;, via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File:Zylinder-1-tab.svg"><img width="88" alt="Zylinder-1-tab" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/81/Zylinder-1-tab.svg/128px-Zylinder-1-tab.svg.png"></a>
</td>
</tr>
<tr>
<td>Cone<br>(incl. bottom)</td>
<td>
<a title="Ag2gaeh, CC BY-SA 4.0 &lt;https://creativecommons.org/licenses/by-sa/4.0&gt;, via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File:Kegel-1-tab.svg"><img width="88" alt="Kegel-1-tab" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/Kegel-1-tab.svg/128px-Kegel-1-tab.svg.png"></a>
</td>
</tr>
</tbody>
</table>

## Step 4: Input related actions

At this stage, the tool actually works. It’s just not convenient that the user self has te decide if the parameters r and h need to be provided or a, b and c, depending on the selected shape. This is were input related actions come in very handy. Basically, it’s an if .. then statement, triggered by the change on a certain form element. In this case: If shape is cone, show a, b and c else show r and h. This is done in 5 rules. One rule for each affected input parameter.

## Result

Fill the form and click ‘Calculate’ in the embedded tool below or click here .

# Tutorial E: Show image from selection

We take a copy of . The goal of this tutorial is to add an image of the selected shape above the input field. This is done in two steps:

## Step 1: Input list

To provide the actual image, we provide an extra name/value pair in the JSON data of the input list. The name is URL and the value is the link to the actual image.

JSON code
{
"choices": [
{
"id": "cuboid",
"name": "Cuboid"
},
{
"id": "cylinder",
"name": "Cylinder"
},
{
"id": "cone",
"name": "Cone"
}
]
}

## Step 2: Input parameters and graphical user interface

To actually show the image as provided in the input list, edit the lay-out of the input element above which the image must be shown. In this case, that is the selection of shape. Instead of the raio select button, we change the input type to ‘Select (1st level)’ so it becomes a dropdown.

## Result

Fill the form and click ‘Calculate’ in the embedded tool.

# Tutorial F: Input validation

For this tutorial, we create a new tool to calculate the maximum deflection of a simply supported beam. The goal is to get familiar with the different levels of input validation.

# Step 1: Main script

The python function that calculates the max deflection at a certain distance x, takes force (F), length (L), stiffness (EI) and distance from the load to the closest support (a).

Python code
import math

def main_function(input_dict):

F = input_dict.get('F')
L = input_dict.get('L')
EI = input_dict.get('EI')
a = input_dict.get('a')

u_max = (F * a * (L ** 2 - a ** 2) ** (3/2)) / (9 * math.sqrt(3) * L * EI )
x = math.sqrt((L ** 2 - a ** 2) / 3)

print(f"u_max = {u_max:.2f} mm")
print(f"x = {x:.2f} m")

return

## Step 2: Input parameters and graphical user interface

The input for F, L, EI and a are defined as shown below.

By default, required is True. This is the first level of input validation. If an input element is required, but not filled, the input element is colored red and there will no python code be executed before the user provides valid input.

## Step 3: Validation script

A more complex validation can be achieved using a validation script. Like the main script, this is a Python function. It takes the same argument (input_dict). If it returns something or prints something, the input is considered invalid. The keys from the input_dict can be used as keys in the return value to show specific text on the invalid form element.

In our main script, a is the distance of the force to the closest support. Therefore, it can never be more than half the length of the beam, L. See the validation script below:

Python code
def validate_input(input_dict):
if input_dict.get('a') >= input_dict.get('L'):
return {'a': f"Make sure a is smaller then L (< {input_dict.get('L')} m)"}

In case of invalid provided input as shown in the image below, the validation script runs, but the main script will not run until valid input is provided.

## Result

Fill the form and click ‘Calculate’ in the embedded tool below or click here.

# Tutorial G: Input layout

## Result

Fill the form and click ‘Calculate’ in the embedded tool below or click here.

# Tutorial H: Upload and use files

import pandas as pandas

def main_function(input_dict):

pandas.set_option('display.max_rows', None)
df = df.rename(columns={'Country name': 'Continent'})
df = df[df['Continent'].isin(input_dict.get('continents'))]
df = df.pivot(index='Year', columns='Continent', values='Population')

print(df)

return

## Result

Fill the form and click ‘Calculate’ in the embedded tool below or click here .

# Tutorial I: HTML output

import pandas

def main_function(input_dict):

pandas.set_option('display.max_rows', None)
df = df.rename(columns={'Country name': 'Continent'})
df = df[df['Continent'].isin(input_dict.get('continents'))]

df = df.pivot(index='Year', columns='Continent', values='Population')

print(df.to_html(classes="table table-hover table-responsive table-sm"))

return

## Result

Fill the form and click ‘Calculate’ in the embedded tool below or click here .

# Tutorial J: PDF output

\documentclass{article}
\usepackage{graphicx} % includegraphics command is implemented here
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{textcomp}
\usepackage{lastpage}
\usepackage{tikz}

\begin{document}
\normalsize
\section{Pythagoras}

In mathematics, the Pythagorean theorem, also known as Pythagoras' theorem, is a fundamental relation in Euclidean geometry among the three sides of a right triangle.
It states that the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides. The theorem can be written as an equation relating the lengths of the sides $a$, $b$ and $c$, often called the "Pythagorean equation":

$$a^2+b^2=c^2,$$

where $c$ represents the length of the hypotenuse and $a$ and $b$ the lengths of the triangle's other two sides.

\label{sec:Pythagoras}

\begin{tikzpicture}
\draw (0,0)
-- (\VAR{b}/2, 0) node[anchor=north]{$b$=\VAR{b}}
-- (\VAR{b}, 0)
-- (\VAR{b}/2, \VAR{a}/2) node[anchor=south west]{$c$=\VAR{c}}
-- (0, \VAR{a})
-- (0, \VAR{a}/2) node[anchor=east]{$a$=\VAR{a}}
-- cycle;
\end{tikzpicture}

\begin{tabular}{r|l|l}
\hline
\hline
a&\VAR{a}&$m$\\
b&\VAR{b}&$m$\\
\hline
c&\VAR{c}&$m$\\
\hline
\end{tabular}

\end{document}

## Result

Fill the form and click ‘Calculate’ in the embedded tool below or click here.

# Tutorial K: XLSX output

import pandas

def main_function(input_dict):

pandas.set_option('display.max_rows', None)
df = df.rename(columns={'Country name': 'Continent'})
df = df[df['Continent'].isin(input_dict.get('continents'))]

df = df.pivot(index='Year', columns='Continent', values='Population')

print(df.to_html(classes="table table-hover table-responsive table-sm"))

return

## Result

Fill the form and click ‘Calculate’ in the embedded tool below or click here .

# Tutorial L: Image output

import pandas as pandas
import plotly.express as px

def main_function(input_dict):

df = df.rename(columns={'Country name': 'Continent'})
df = df[df['Continent'].isin(input_dict.get('continents'))]

fig = px.line(df, x="Year", y="Population", color="Continent")
fig.write_image('population.png')
print('_img[population.png]')

df = df.pivot(index='Year', columns='Continent', values='Population')
print(df)

return

## Result

Fill the form and click ‘Calculate’ in the embedded tool below or click here .