Python Code Generation Tutorial

Python Code Generation Tutorial

A live version of this calculation is available at EngineeringPaper.xyz.

EngineeringPaper.xyz makes it easy to define, plot, and evaluate complex expressions. However, there may be occasions where the full power of Python may be needed to perform some additional numerical analyses. Fortunately, EngineeringpPaper.xyz allows you to generate Python code directly from your sheets.

In the following example we define a sinusoidal pulse with a triangle envelope. First we define the triangle shaped envelope using the piecewise function capability of EngineeringPaper.xyz as follows:

$$ triangle = \begin{cases} x+1 &: \quad -1\le x\le0 \ -\left(x-1\right) &: \quad 0\le x\le1 \ 0 &: \quad \text{otherwise} \end{cases} $$

It can be seen that the triangle envelope function is a function of x. Next, we define y as the product of a sine wave and the triangle function:

$$ y=triangle\cdot\sin\left(10\cdot x\right) $$

Finally, we plot both the triangle function and y over a range of x values:

In order to be able to generate Python code for the function y, we need to create a query cell calling y as a function with numerical values provided for all of its unknown parameters (in this case only x is unknown):

$$ y\left(x=.5\right)= -0.479462137331569 $$

Anytime a function call with all numerical inputs evaluates to a numeric value, a generate code button

will automatically appear on the right hand side of the math cell. Click this button and the Python code for this function will be generated. This Python code can be copied and pasted into a Python program or a Jupyter notebook. Note that it is always important to check the results of the generated Python code against the results in the EngineeringPaper.xyz sheet.

Note that if the input and/or output values have units, the input and output units that appear in the function call will be used for the generated Python code, see the following example:

$$ ThermalExpansion=\alpha\cdot L\cdot\left(T-T_0\right) $$

$$ ThermalExpansion\left(L=36\left\lbrack in\right\rbrack,:\alpha=10.8e-6\left\lbrack\frac{1}{K}\right\rbrack,:T_0=70\left\lbrack degF\right\rbrack,:T=212\left\lbrack degF\right\rbrack\right)=\left\lbrack in\right\rbrack =0.030672 \left\lbrack in\right\rbrack $$

Note that the code generated expects the input values to be in the units provided in the function call (for example, the length parameter L is expected to be in inches). Internally, the function converts all input parameters to SI units, performs the calculation, and finally converts the result to the desired output units, if required. In this case, the output is converted to inches because of the [in] provided after the equals sign. Additionally, a comment is automatically generated for the Python function that includes the expected units for the input parameters and the result.