Skip to main content
Example Created Edited

Example: Python

shutterstock_2326625677-20231115-062024.jpg

Python

Python is a high-level programming language that operates in an interpreter mode. Developed by Guido van Rossum in 1989, Python is known for its clean and readable syntax, making it beloved and widely used among many programmers. The key features and purposes of Python are as follows:

  1. Readability: Python's concise and intuitive syntax makes it easy for programmers to read and understand code, making it ideal for beginners learning Python.
  2. Versatility: Python can be used for various purposes, including web development, data analysis, artificial intelligence, game development, system administration, automation, scientific research, and more.
  3. Cross-platform: Python runs on various operating systems such as Windows, macOS, and Linux. This means that code can be written once and executed on multiple platforms.
  4. Rich libraries and frameworks: Python provides a wide range of libraries and frameworks, enabling users to perform various tasks efficiently. For example, NumPy and Pandas are powerful tools for data science and mathematical calculations, while Django and Flask simplify web development.
  5. Interpreter language: Python operates in interpreter mode, allowing code to be written and executed immediately. This facilitates quick prototyping and testing.
  6. Community and support: Python has an active community with abundant online resources and help, making it easy to solve problems or find answers to questions.
  7. Object-oriented programming: Python supports object-oriented programming (OOP), allowing code to be structured and modularized using classes and objects.
  8. Dynamic typing: Python does not require the declaration of variable data types, determining the variable's type at runtime. This provides flexibility in programming.

Python is popular among programmers of various levels, from beginners learning programming to professional developers. As a versatile language applicable in various fields, it is also convenient for handling MIDAS Open API.

 

Welcome to Python

Python is provided on the official website as below.

Welcome to Python.org

Installing Python and using it depends on the user's IDE(Integrated Development Environment). This example was written using Visual Studio Code.

 

Requests

To request REST API in Python, you need to install the Request module.

You can find more details about this below.

https://pypi.org/project/requests/

Requests: HTTP for Humans™ — Requests 2.31.0 documentation


The following example demonstrates installing the Request module in Visual Studio Code.

 

  • Open the Visual Studio Code and execute Menu → Terminal → New Terminal
  • When the Terminal opens, copy the below text and paste it into the Terminal.
py -3 -m pip install requests

image-20220422-072358.png

Install Request Module(Visual Studio Code)

image-20220422-081837.png

Complete installation of the Request Module

 

JSON in Python

Handling JSON in Python is straightforward and can be done using the built-in library and various external libraries. Let me explain how to parse or generate JSON data in Python.

 

  • JSON Data Parsing

To parse JSON data in Python, use the basic library JSON. The following example is JSON data parsing.

import json

# Converting Python data through parsing JSON string
json_data = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_data)

# Print result
print(data) # {'name': 'John', 'age': 30, 'city': 'New York'}
print(data['name']) # 'John'
  • Creating JSON data

To convert Python data into JSON in Python, use json.dumps() function. The next example is converting a Python dictionary to a JSON string.

import json

# Converting Python dictionary to JSON string
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
json_data = json.dumps(data)

# Print result
print(json_data) # '{"name": "John", "age": 30, "city": "New York"}'

In the example below, a dictionary is utilized, and the request module automatically converts dictionary data into JSON format during execution. Therefore, there is no need for a separate conversion process.

Exercise Examples

Creating a rectangle section simple beam example with Python.

  • Create an API Request as a function for the first step because it will be used several times.

Please check and input the base_url and mapi_key from the product into lines 5 and 6.

import requests

# function for MIDAS Open API
def MidasAPI(method, command, body=None):
    base_url = "base_url_here"
    mapi_key = "your_api_key_here"

    url = base_url + command
    headers = {
        "Content-Type": "application/json",
        "MAPI-Key": mapi_key
    }

    if method == "POST":
        response = requests.post(url=url, headers=headers, json=body)
    elif method == "PUT":
        response = requests.put(url=url, headers=headers, json=body)
    elif method == "GET":
        response = requests.get(url=url, headers=headers)
    elif method == "DELETE":
        response = requests.delete(url=url, headers=headers)

    print(method, command, response.status_code)
    return response.json()

 

  • Assigning input values. Geometry variables of the beam and material, ID, etc., have been set as variables.
# Unit Setting
unit_dist = "M"     # M, CM, MM, IN, FT
unit_force = "KN"   # KN, N, KGF, TONF, LBF, KIPS

# Input Data
length : float = 10.0
height : float   = 1.0
width : float   = 0.8
add_vertical_load : float = -30.0

# Material Data
mat_standard = "AS17(RC)"
mat_grade = "C32"

# ID (integer)
material_ID : int = 1
section_ID : int = 1
start_node_ID : int = 1
start_elem_ID : int = 1

 

  • Creating a dictionary data for units.
# Create Unit Body
unit_json = {"Assign" : {
    "1" : {
        "DIST" : unit_dist,
        "FORCE" : unit_force
    }
}}

 

  • Creating a dictionary data for materials.
# Create Material Body
matl_json = {"Assign" : {
    material_ID : {
        "TYPE" : "CONC",
        "NAME" : mat_grade,
        "PARAM" : [
            {
            "P_TYPE":1,
            "STANDARD" : mat_standard,
            "DB" : mat_grade
            }
        ]
    }
}}

 

  • Creating a dictionary data for sections.
# Create Section Body
sect_json = {"Assign" : {
    section_ID : {
        "SECTTYPE" : "DBUSER",
        "SECT_NAME" : "Rectangular",
        "SECT_BEFORE" : {
            "USE_SHEAR_DEFORM" : True,
            "SHAPE": "SB",
            "DATATYPE": 2,
            "SECT_I": {
                "vSIZE" : [height, width]
            }
        }
    }
}}

 

  • Using given input values, creating dictionary data through calculating node coordinates.
# Create Node Body
num_divisions = 20
interval = length / int(num_divisions)
x_list = [i * interval for i in range(num_divisions + 1)]

node_json = {"Assign" : {}}

for i, x in enumerate(x_list) :
    node_json["Assign"][start_node_ID + i] = {
        "X" : x,
        "Y" : 0.0,
        "Z" : 0.0
    }

 

  • Creating a dictionary data that connects given nodes sequentially as elements.
# Create Element Body
elem_json = {"Assign" : {}}

for i in range(num_divisions):
    elem_json["Assign"][start_elem_ID + i] = {
        "TYPE" : "BEAM",
        "MATL" : material_ID,
        "SECT" : section_ID,
        "NODE" : [start_node_ID + i, start_node_ID + i + 1]
    }

 

  • Apply boundary conditions on the endpoints of the beam.
# Create Boundary Body
cons_json = {"Assign" : {
    start_node_ID : {
        "ITEMS" : [
            {
                "ID":1,
                "CONSTRAINT" : "1111000"
            }
        ]
    },
    start_node_ID + num_divisions : {
        "ITEMS" : [
            {
                "ID":1,
                "CONSTRAINT" : "0111000"
            }
        ]
    }
}}

 

  • Creating two load cases for static load analysis.
# Create LoadCase Body
load_case_name = ["DL", "SIDL"]
load_case_desc = ["Dead Load", "Super Imposed Dead Load"]

stld_json = {"Assign" : {}}

for i in range(len(load_case_name)) :
    stld_json["Assign"][i + 1] = {
        "NAME" : load_case_name[i],
        "TYPE" : "USER",
        "DESC" : load_case_desc[i],
    }

 

  • Assign self-weight as the first load case.
# Create Self-Weight Load Body
bodf_json = {"Assign" : {
    "1" : {
        "LCNAME" : load_case_name[0],
        "FV" :[
            0,
            0,
            -1
        ]
    }
}}

 

  • Adding an additional load case to the beam.
# Create Beam Load Body
bmld_json = {"Assign" : {}}

for i in range(num_divisions) :
    bmld_json["Assign"][start_elem_ID + i] = {
        "ITEMS" : [
            {
                "ID" : 1,
                "LCNAME" : load_case_name[1],
                "CMD" : "BEAM",
                "TYPE" : "UNILOAD",
                "DIRECTION" : "GZ",
                "D" : [
                    0,
                    1
                ],
                "P" : [
                    add_vertical_load,
                    add_vertical_load
                ]
            }
        ]
    }

 

  • Creating Load Combinations.
# Create Load Combination Body
load_factor = [1.2, 1.5]
lcom_gen_json = {"Assign" : {
    "1" : {
        "NAME" : "Comb1",
        "ACTIVE" : "ACTIVE",
        "iTYPE" : 0,
        "vCOMB" :[
            {
                "ANAL" : "ST",
                "LCNAME" : load_case_name[0],
                "FACTOR" : load_factor[0]
            },
            {
                "ANAL" : "ST",
                "LCNAME" : load_case_name[1],
                "FACTOR" : load_factor[1]
            }
        ]
    }
}}

 

  • Using the "MIDASAPI" function, request the API with the dictionary data in the above procedure.
# SEND DATA TO MIDAS CIVIL
# Create New file
file_res = MidasAPI("POST", "/doc/new", {})
# Sending Request
unit_res = MidasAPI("PUT", "/db/unit", unit_json)
matl_res = MidasAPI("POST", "/db/matl", matl_json)
sect_res = MidasAPI("POST", "/db/sect", sect_json)
node_res = MidasAPI("POST", "/db/node", node_json)
elem_res = MidasAPI("POST", "/db/elem", elem_json)
cons_res = MidasAPI("POST", "/db/cons", cons_json)
stld_res = MidasAPI("POST", "/db/stld", stld_json)
bodf_json = MidasAPI("POST", "/db/bodf", bodf_json)
bmld_res = MidasAPI("POST", "/db/bmld", bmld_json)
lcom_gen_res = MidasAPI("POST", "/db/lcom-gen", lcom_gen_json)

Now, combine all the code snippets into one file and run the code.

 

When you run Python, the response codes for each request will be displayed as follows.

image-20231019-081828.png

Then, a simple beam is created in the MIDAS CIVIL NX as the Python code intended.

image-20231019-082255.png

 

Additional Python examples

Create Nodes/Elements by Alignment with Python

This example uses Python to create nodes and elements based on input alignment information (straight, arc, spline, and parabolic curve).

The users only need to input alignment data (type, length) and segment information (each element distance).

 

Node local axis of the spline with Python

This example creates a Node local axis; a virtual spline is made to obtain the tangent angle if an arbitrary node on the plane is specified.

  • Valid only in X-Y plane.
  • Spline is created in the X-axis increment(+) direction.

 

Divide Beam Elements with Python

This script provides a function to divide the selected beam elements into equal or unequal

 

The Best Tool for Structural Engineers


Python is considered the best tool for structural engineers. It is easy to learn, user-friendly, accessible and well-supported with mathematical/engineering libraries. Moreover, the user community is extensive, and a wealth of help is available online.

We look forward to your first step to MIDAS Open API, starting with Python.

 

1
Was this article helpful?