Techno Blender
Digitally Yours.

Goodbye Boring PLAXIS Output with Python | by Philip Tsang | Dec, 2022

0 44


PLAXIS AUTOMATION SERIES

Step-by-step guide toward automation

Photo by Mika Baumeister on Unsplash

If you are a frequent PLAXIS user like me, you must have asked this question: why on earth I need to keep repeating this copy and paste action to extract results?

PLAXIS, with no doubt, is a powerful FE software. As Geotechnical engineers, we want to focus on the analysis and spend less time on post-processing. Python provides the most extensive possibilities toward automating output extraction and visualisation, thanks to the modules developed by the open source communities. Some common modules include:

  • Pandas
  • Xlsxwriter
  • Matplotlib
  • Seaborn

The ultimate goal of this tutorial is to show you how to use Python script to extract outputs from a structural element in PLAXIS 2D. This can be done with the following four steps.

  1. Use IDE to open PLAXIS Output
  2. Install external module to PLAXIS environment
  3. Extract Plate results from PLAXIS
  4. Export as excel spreadsheet

This tutorial requires the readers have VS Code and PLAXIS environment installed. Follow the instructions from the article below if you’re new to this page. Let’s get started!

I used a PLAXIS 2D model published by the official Bentley website as shown below.

In the link, download the command log file from V22.01. To the best of author’s knowledge, the Python commands have changed significantly from V21 to V22. Hence, make sure you got PLAXIS V22 or above (V22.01 and V22.02) installed to ensure the Python script in this tutorial works properly.

Screenshot by the author

Once you have run the command using “Run commands…”, you should be able to see the following geometry.

Screenshot from PLAXIS by the author

This example models the construction of an excavation which consists of a diaphragm wall (Plate element). Our goal is to extract the results of the plate element.

Calculate the model and we are ready to extract the results using Python.

Unlike first tutorial, this time we will open a PLAXIS file we just downloaded and hence the code for starting the server needs to be slightly modified. You will need to save the calculated model in a preferred working directory.

My location of the PLAXIS file:

C:\Users\phtsang\Desktop\Current_Projects\LinkedIn\Blog_2\Excavation

I will first create an empty python script called it “open_output.py”.

After that, we write the code below to the python file. The code is very similar to the one from first tutorial but this time we will be opening an exisiting PLAXIS file. In order to do this, we made the following three changes:

  1. Since this time we need to open a PLAXIS file, the working directory of the file needs to be specified which is stored as “FILE_PATH”.
  2. We then open the file using PLAXIS command “s_i.open(FILE_PATH)”.
  3. To open PLAXIS output, we write “g_i.view(g_i.Phases[1])” which allows us to view the results of Phase_1’s calculation.
from plxscrpting.easy import *
import subprocess, time
import os

###############################################
PLAXIS_PATH = r'C:\Program Files\Bentley\Geotechnical\PLAXIS 2D CONNECT Edition V22\\Plaxis2DXInput.exe' # Specify PLAXIS path on server.
FILE_PATH = r'C:\Users\phtsang\Desktop\Current_Projects\LinkedIn\Blog_2\\Excavation' # Specify PLAXIS file location and name
PORT_i = 10000 # Define a port number.
PORT_o = 10001
PASSWORD = 'SxDBR<TYKRAX834~' # Define a password.

subprocess.Popen([PLAXIS_PATH, f'--AppServerPassword={PASSWORD}', f'--AppServerPort={PORT_i}'], shell=False) # Start the PLAXIS remote scripting service.
time.sleep(5) # Wait for PLAXIS to boot before sending commands to the scripting service.

# Start the scripting server.
# global g_i, s_i
s_i, g_i = new_server('localhost', PORT_i, password=PASSWORD)
s_o, g_o = new_server('localhost', PORT_o, password=PASSWORD)

s_i.open(FILE_PATH)

g_i.gotostages()
g_i.view(g_i.Phases[1])

Screenshot from VS Code by the author

To test that the code above is working properly, we will run “open_output.py” in terminal as shown below. Type “python open_output.py” and click Enter.

Screenshot from VS Code by the author

Both PLAXIS 2D input and output apps should be opened automatically. From the output app, you should see “SERVER ACTIVE on port 10001”.

Screenshot from PLAXIS by the author

We now have the PLAXIS API connected, we are ready to move to the next step.

When using the PLAXIS scripting environment it is common to use Python modules allowing for extending the functionality of a Python script. Since our goal is to extract results from PLAXIS and export to excel spreadsheet, we need two external modules:

These modules can be installed through PLAXIS command prompt window as shown in the steps below. Before proceeding, make sure you have gone through Step 1 with PLAXIS Input opened.

Go to menu option Expert > Python > Command prompt. This will open the Windows Command prompt with the PLAXIS set as the current environment.

Screenshot from PLAXIS by the author

Change directory to the PLAXIS Python Distribution folder. This can be done with the following command:

pushd C:\ProgramData\Bentley\Geotechnical\PLAXIS Python Distribution V2\python\Lib\site-packages
Screenshot from PLAXIS by the author

In the Command prompt you can now install any new Python modules using the command shown in the example below.

For instance, if you want to install the pandas module:

python -m pip install pandas
Screenshot from PLAXIS by the author

Also, install the xlsxwriter module:

python -m pip install xlsxwriter

Now that we have installed all the required modules. We can then extract results from PLAXIS using Python script.

Our main goal Step 3 is to extract four result types for the plate element (Diaphragm wall) in the last phase (Third excavation stage [Phase_5]). The result types we will extract are:

  • Y Coordinates
  • Shear
  • Bending Moment
  • Axial Force

In Step 4, we will then export the results to excel spreadsheet with the columns shown below.

Screenshot from excel by the author

First, we create an empty python file and call it “output_plate.py”.

Import Modules and Strat Server

We need to make sure the API is connected, as well as import the modules we installed earlier.

from plxscripting.easy import *
import subprocess, time
import math
import pandas as pd
import os
import xlsxwriter

###############################################
PORT_i = 10000 # Define a port number.
PORT_o = 10001
PASSWORD = 'SxDBR<TYKRAX834~' # Define a password.

# Start the scripting server.
s_i, g_i = new_server('localhost', PORT_i, password=PASSWORD)
s_o, g_o = new_server('localhost', PORT_o, password=PASSWORD)

Define File Name

Since we need to export the results to excel, we need the specify the exported file location and its name.

File location: make sure there is double slash (\\) after your working directory

File name: can be any name you want

EXCEL_PATH=r'C:\Users\phtsang\Desktop\PLAXIS_V22\Script\\'
EXCEL_NAME='plate_output.xlsx'

FILENAME=EXCEL_PATH+EXCEL_NAME

Input Definition

After that, we will input the structural element and the corresponding phase we would like to extract. In this case: ‘Plate_1’ and ‘Third excavation stage [Phase_5]’.

The code underneath is to find the existing plate elements and phases in the model and store them as list.

plate_input=['Plate_1'] # Input by user
phase_input=['Third excavation stage [Phase_5]'] # Input by user

###############################################
#Exisiting model element:

plate=[plt for plt in g_o.Plates[:]] # Loop through the plate object in existing model
phase=[p for p in g_o.Phases[:]] # Loop through all available phases

Two important concepts here:

For loop: the action of finding existing elements in PLAXIS requires for loop. This is a very common command in programming. For example in “plate”, we have:

for plt in g_o.Plates[:]

This line means we are looping through all the plate elements in “g_o.Plates[:]” (which is how PLAXIS store objects) and name it as “plt”.

List: As mentioned in first tutorial, it is common to store values in a list which is represented by a square bracket [ ]. The syntax has slightly changed compared to first tutorial as it has been simplified.

This line:

plate=[plt for plt in g_o.Plates[:]]

Can be extended as:

plate=[]

for plt in g_o.Plates[:]

plate.append(plt)

Both code will give the same result but the first one is much neater which is commonly used in Python.

So far, your script should look like:

Screenshot from VS Code by the author

After the pre-processing as mentioned above, we can start extracting plate results. To do that, we will define a function to extract results, call is “get_plate()”. Few key points here:

Y coordinate = ResultTypes.Plate.Y

Shear = ResultTypes.Plate.Q2D

Bending Moment = ResultTypes.Plate.M2D

Axial Force = ResultTypes.Plate.Nx2D

  • The next few lines are to create column names as specified in the target spreadsheet.
  • Results are then stored as “results”. Here I introduce a new data type called Dictionary in Python which is represented by curly bracket { }. Dictionary is particularly useful when you want to create a table, it contains a key-value pair. For example:

‘Y’ is the key of dictionary

plateY is the value of dictionary. An array of values can be stored to the specified key.

  • Once the dictionary is created, the next line converts dictionary to dataframe. Dataframe is one of most common data structure we use in Python. You can interpret it as a table in excel. This is done by running command: “pd.DataFrame(results)”
  • I also sort the results using Y coordinate in a descending order

Make sure the indentation is correct as shown in the screenshot below.

def get_plate(plate_o,phase_o):

plateY=g_o.getresults(plate_o,phase_o,g_o.ResultTypes.Plate.Y, "node")
plateQ=g_o.getresults(plate_o,phase_o,g_o.ResultTypes.Plate.Q2D, "node")
plateM=g_o.getresults(plate_o,phase_o,g_o.ResultTypes.Plate.M2D, "node")
plateAxial=g_o.getresults(plate_o,phase_o,g_o.ResultTypes.Plate.Nx2D, "node")

phasename=str(phase_o.Identification).split('[')[0]
col1='Shear [kN]'+'_'+phasename
col2='Bending Moment [kNm/m]'+'_'+phasename
col3='Axial Force [kN]'+'_'+phasename

results = {'Y': plateY, col1: plateQ,col2: plateM,col3: plateAxial}

plateresults=pd.DataFrame(results)
plateresults = plateresults.sort_values(by=['Y'],ascending=False)

return plateresults

Screenshot from VS Code by the author

Lastly, we will export the dataframe we created to excel.

We create a function, call it “export_excel()”.

  • writer is to use the xlsxwriter module we installed to export excel
  • name & sheet_name is where I create a worksheet name with format “Plate_1_Phase 5”.
  • Then, I use the function “get_plate()” we created in earlier to generate the dataframe and store as “results”. It should be a dataframe which can then be export to excel using pandas command “results.to_excel()”.
def export_excel(plate_input,phase_input,filename):
writer = pd.ExcelWriter(filename, engine='xlsxwriter')

name=str(phase[5].Identification).split(' [')[1]
name=name.split(']')[0]
sheet_name = "%s_%s" % (plate[0].Name, name)
results = get_plate(plate[0], phase[5])
results.to_excel(writer,sheet_name=sheet_name,index=False)
writer.save()

export_excel(plate_input,phase_input,FILENAME)

Screenshot from VS Code by the author

Run the script with the following.

(PLAXIS) C:\Users\phtsang\Desktop\PLAXIS_V22\Script>python output_plate.py

You will see the results we look for have been automatically extracted as shown in the command window.

Screenshot from PLAXIS by the author

Now if you open the excel spreadsheet in the location you specified earlier, you can see we have extracted the Y coordinate, Shear, Bending moment and Axial force as we want.

Screenshot from excel by the author

Well done! You have just extracted results from PLAXIS using Python script.

That’s all for the second tutorial on extracting PLAXIS output using Python. By now, you should be able to extract output for a single structural element from PLAXIS. In future tutorials, I will show how to extract results for multiple structural elements and different structure types such as interfaces and embedded beams.

If you enjoy reading this type of content, feel free to follow my page. I will keep posting this series of tutorials on automating PLAXIS with Python. Apart from that, I’m also keen to share knowledge on how to use Python to automate workflow in engineering.


PLAXIS AUTOMATION SERIES

Step-by-step guide toward automation

Photo by Mika Baumeister on Unsplash

If you are a frequent PLAXIS user like me, you must have asked this question: why on earth I need to keep repeating this copy and paste action to extract results?

PLAXIS, with no doubt, is a powerful FE software. As Geotechnical engineers, we want to focus on the analysis and spend less time on post-processing. Python provides the most extensive possibilities toward automating output extraction and visualisation, thanks to the modules developed by the open source communities. Some common modules include:

  • Pandas
  • Xlsxwriter
  • Matplotlib
  • Seaborn

The ultimate goal of this tutorial is to show you how to use Python script to extract outputs from a structural element in PLAXIS 2D. This can be done with the following four steps.

  1. Use IDE to open PLAXIS Output
  2. Install external module to PLAXIS environment
  3. Extract Plate results from PLAXIS
  4. Export as excel spreadsheet

This tutorial requires the readers have VS Code and PLAXIS environment installed. Follow the instructions from the article below if you’re new to this page. Let’s get started!

I used a PLAXIS 2D model published by the official Bentley website as shown below.

In the link, download the command log file from V22.01. To the best of author’s knowledge, the Python commands have changed significantly from V21 to V22. Hence, make sure you got PLAXIS V22 or above (V22.01 and V22.02) installed to ensure the Python script in this tutorial works properly.

Screenshot by the author

Once you have run the command using “Run commands…”, you should be able to see the following geometry.

Screenshot from PLAXIS by the author

This example models the construction of an excavation which consists of a diaphragm wall (Plate element). Our goal is to extract the results of the plate element.

Calculate the model and we are ready to extract the results using Python.

Unlike first tutorial, this time we will open a PLAXIS file we just downloaded and hence the code for starting the server needs to be slightly modified. You will need to save the calculated model in a preferred working directory.

My location of the PLAXIS file:

C:\Users\phtsang\Desktop\Current_Projects\LinkedIn\Blog_2\Excavation

I will first create an empty python script called it “open_output.py”.

After that, we write the code below to the python file. The code is very similar to the one from first tutorial but this time we will be opening an exisiting PLAXIS file. In order to do this, we made the following three changes:

  1. Since this time we need to open a PLAXIS file, the working directory of the file needs to be specified which is stored as “FILE_PATH”.
  2. We then open the file using PLAXIS command “s_i.open(FILE_PATH)”.
  3. To open PLAXIS output, we write “g_i.view(g_i.Phases[1])” which allows us to view the results of Phase_1’s calculation.
from plxscrpting.easy import *
import subprocess, time
import os

###############################################
PLAXIS_PATH = r'C:\Program Files\Bentley\Geotechnical\PLAXIS 2D CONNECT Edition V22\\Plaxis2DXInput.exe' # Specify PLAXIS path on server.
FILE_PATH = r'C:\Users\phtsang\Desktop\Current_Projects\LinkedIn\Blog_2\\Excavation' # Specify PLAXIS file location and name
PORT_i = 10000 # Define a port number.
PORT_o = 10001
PASSWORD = 'SxDBR<TYKRAX834~' # Define a password.

subprocess.Popen([PLAXIS_PATH, f'--AppServerPassword={PASSWORD}', f'--AppServerPort={PORT_i}'], shell=False) # Start the PLAXIS remote scripting service.
time.sleep(5) # Wait for PLAXIS to boot before sending commands to the scripting service.

# Start the scripting server.
# global g_i, s_i
s_i, g_i = new_server('localhost', PORT_i, password=PASSWORD)
s_o, g_o = new_server('localhost', PORT_o, password=PASSWORD)

s_i.open(FILE_PATH)

g_i.gotostages()
g_i.view(g_i.Phases[1])

Screenshot from VS Code by the author

To test that the code above is working properly, we will run “open_output.py” in terminal as shown below. Type “python open_output.py” and click Enter.

Screenshot from VS Code by the author

Both PLAXIS 2D input and output apps should be opened automatically. From the output app, you should see “SERVER ACTIVE on port 10001”.

Screenshot from PLAXIS by the author

We now have the PLAXIS API connected, we are ready to move to the next step.

When using the PLAXIS scripting environment it is common to use Python modules allowing for extending the functionality of a Python script. Since our goal is to extract results from PLAXIS and export to excel spreadsheet, we need two external modules:

These modules can be installed through PLAXIS command prompt window as shown in the steps below. Before proceeding, make sure you have gone through Step 1 with PLAXIS Input opened.

Go to menu option Expert > Python > Command prompt. This will open the Windows Command prompt with the PLAXIS set as the current environment.

Screenshot from PLAXIS by the author

Change directory to the PLAXIS Python Distribution folder. This can be done with the following command:

pushd C:\ProgramData\Bentley\Geotechnical\PLAXIS Python Distribution V2\python\Lib\site-packages
Screenshot from PLAXIS by the author

In the Command prompt you can now install any new Python modules using the command shown in the example below.

For instance, if you want to install the pandas module:

python -m pip install pandas
Screenshot from PLAXIS by the author

Also, install the xlsxwriter module:

python -m pip install xlsxwriter

Now that we have installed all the required modules. We can then extract results from PLAXIS using Python script.

Our main goal Step 3 is to extract four result types for the plate element (Diaphragm wall) in the last phase (Third excavation stage [Phase_5]). The result types we will extract are:

  • Y Coordinates
  • Shear
  • Bending Moment
  • Axial Force

In Step 4, we will then export the results to excel spreadsheet with the columns shown below.

Screenshot from excel by the author

First, we create an empty python file and call it “output_plate.py”.

Import Modules and Strat Server

We need to make sure the API is connected, as well as import the modules we installed earlier.

from plxscripting.easy import *
import subprocess, time
import math
import pandas as pd
import os
import xlsxwriter

###############################################
PORT_i = 10000 # Define a port number.
PORT_o = 10001
PASSWORD = 'SxDBR<TYKRAX834~' # Define a password.

# Start the scripting server.
s_i, g_i = new_server('localhost', PORT_i, password=PASSWORD)
s_o, g_o = new_server('localhost', PORT_o, password=PASSWORD)

Define File Name

Since we need to export the results to excel, we need the specify the exported file location and its name.

File location: make sure there is double slash (\\) after your working directory

File name: can be any name you want

EXCEL_PATH=r'C:\Users\phtsang\Desktop\PLAXIS_V22\Script\\'
EXCEL_NAME='plate_output.xlsx'

FILENAME=EXCEL_PATH+EXCEL_NAME

Input Definition

After that, we will input the structural element and the corresponding phase we would like to extract. In this case: ‘Plate_1’ and ‘Third excavation stage [Phase_5]’.

The code underneath is to find the existing plate elements and phases in the model and store them as list.

plate_input=['Plate_1'] # Input by user
phase_input=['Third excavation stage [Phase_5]'] # Input by user

###############################################
#Exisiting model element:

plate=[plt for plt in g_o.Plates[:]] # Loop through the plate object in existing model
phase=[p for p in g_o.Phases[:]] # Loop through all available phases

Two important concepts here:

For loop: the action of finding existing elements in PLAXIS requires for loop. This is a very common command in programming. For example in “plate”, we have:

for plt in g_o.Plates[:]

This line means we are looping through all the plate elements in “g_o.Plates[:]” (which is how PLAXIS store objects) and name it as “plt”.

List: As mentioned in first tutorial, it is common to store values in a list which is represented by a square bracket [ ]. The syntax has slightly changed compared to first tutorial as it has been simplified.

This line:

plate=[plt for plt in g_o.Plates[:]]

Can be extended as:

plate=[]

for plt in g_o.Plates[:]

plate.append(plt)

Both code will give the same result but the first one is much neater which is commonly used in Python.

So far, your script should look like:

Screenshot from VS Code by the author

After the pre-processing as mentioned above, we can start extracting plate results. To do that, we will define a function to extract results, call is “get_plate()”. Few key points here:

Y coordinate = ResultTypes.Plate.Y

Shear = ResultTypes.Plate.Q2D

Bending Moment = ResultTypes.Plate.M2D

Axial Force = ResultTypes.Plate.Nx2D

  • The next few lines are to create column names as specified in the target spreadsheet.
  • Results are then stored as “results”. Here I introduce a new data type called Dictionary in Python which is represented by curly bracket { }. Dictionary is particularly useful when you want to create a table, it contains a key-value pair. For example:

‘Y’ is the key of dictionary

plateY is the value of dictionary. An array of values can be stored to the specified key.

  • Once the dictionary is created, the next line converts dictionary to dataframe. Dataframe is one of most common data structure we use in Python. You can interpret it as a table in excel. This is done by running command: “pd.DataFrame(results)”
  • I also sort the results using Y coordinate in a descending order

Make sure the indentation is correct as shown in the screenshot below.

def get_plate(plate_o,phase_o):

plateY=g_o.getresults(plate_o,phase_o,g_o.ResultTypes.Plate.Y, "node")
plateQ=g_o.getresults(plate_o,phase_o,g_o.ResultTypes.Plate.Q2D, "node")
plateM=g_o.getresults(plate_o,phase_o,g_o.ResultTypes.Plate.M2D, "node")
plateAxial=g_o.getresults(plate_o,phase_o,g_o.ResultTypes.Plate.Nx2D, "node")

phasename=str(phase_o.Identification).split('[')[0]
col1='Shear [kN]'+'_'+phasename
col2='Bending Moment [kNm/m]'+'_'+phasename
col3='Axial Force [kN]'+'_'+phasename

results = {'Y': plateY, col1: plateQ,col2: plateM,col3: plateAxial}

plateresults=pd.DataFrame(results)
plateresults = plateresults.sort_values(by=['Y'],ascending=False)

return plateresults

Screenshot from VS Code by the author

Lastly, we will export the dataframe we created to excel.

We create a function, call it “export_excel()”.

  • writer is to use the xlsxwriter module we installed to export excel
  • name & sheet_name is where I create a worksheet name with format “Plate_1_Phase 5”.
  • Then, I use the function “get_plate()” we created in earlier to generate the dataframe and store as “results”. It should be a dataframe which can then be export to excel using pandas command “results.to_excel()”.
def export_excel(plate_input,phase_input,filename):
writer = pd.ExcelWriter(filename, engine='xlsxwriter')

name=str(phase[5].Identification).split(' [')[1]
name=name.split(']')[0]
sheet_name = "%s_%s" % (plate[0].Name, name)
results = get_plate(plate[0], phase[5])
results.to_excel(writer,sheet_name=sheet_name,index=False)
writer.save()

export_excel(plate_input,phase_input,FILENAME)

Screenshot from VS Code by the author

Run the script with the following.

(PLAXIS) C:\Users\phtsang\Desktop\PLAXIS_V22\Script>python output_plate.py

You will see the results we look for have been automatically extracted as shown in the command window.

Screenshot from PLAXIS by the author

Now if you open the excel spreadsheet in the location you specified earlier, you can see we have extracted the Y coordinate, Shear, Bending moment and Axial force as we want.

Screenshot from excel by the author

Well done! You have just extracted results from PLAXIS using Python script.

That’s all for the second tutorial on extracting PLAXIS output using Python. By now, you should be able to extract output for a single structural element from PLAXIS. In future tutorials, I will show how to extract results for multiple structural elements and different structure types such as interfaces and embedded beams.

If you enjoy reading this type of content, feel free to follow my page. I will keep posting this series of tutorials on automating PLAXIS with Python. Apart from that, I’m also keen to share knowledge on how to use Python to automate workflow in engineering.

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.

Leave a comment