import pip
import csv
import traceback
# Load all the necessary Python libraries, install them if they are missing
try:
from ansys.mapdl.core import launch_mapdl, inline_functions
import numpy as np
except ImportError:
pip.main(['install', 'ansys.mapdl.core'])
pip.main(['install', 'numpy'])
from ansys.mapdl.core import launch_mapdl, inline_functions
import numpy as np
def extract_reactions(rst_path):
# Create a dictionary to store results
result_dict = {}
# Enter POST1 and load the .RST file with first timestep
mapdl.post1()
mapdl.file(fname=rst_path)
mapdl.set(lstep='FIRST')
# Get a list of all named selections that start with 'BOLT' name
named_selection_list = [mapdl.get(entity='COMP', item1='NAME', entnum=item) for item in
range(int(mapdl.get(entity='COMP', item1='NCOMP'))) if
str(mapdl.get(entity='COMP', item1='NAME', entnum=item)).startswith('BOLT_')]
# Iterate throughout the named selection list and extract reaction forces
for named_selection in named_selection_list:
# Select a named selection
mapdl.cmsel(type_='S', name=named_selection)
# Initiate FSUM command
mapdl.fsum()
# Extract reaction forces in the global coordinate system
f_x = round(mapdl.get(entity='FSUM', item1='ITEM', it1num='FX'), 2)
f_y = round(mapdl.get(entity='FSUM', item1='ITEM', it1num='FY'), 2)
f_z = round(mapdl.get(entity='FSUM', item1='ITEM', it1num='FZ'), 2)
# Save results to a dictionary
result_dict[named_selection] = [f_x, f_y, f_z]
# Exit MAPDL instance and return the dictionary with reaction forces
mapdl.exit()
return result_dict
def save_to_excel(results, dir_path):
# Create a new file and write data to it
with open(dir_path + '/' + 'BoltReactionForces.csv', 'w', newline='') as file:
# Create field names and write them
fieldnames = ['Bolt_name', 'Reaction_X', 'Reaction_Y', 'Reaction_Z']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
# Iterate over elements and write results
for key, value in results.items():
name = key
fx = value[0]
fy = value[1]
fz = value[2]
writer.writerow(
{'Bolt_name': name, 'Reaction_X': fx, 'Reaction_Y': fy, 'Reaction_Z': fz})
if __name__ == "__main__":
# Input parameters
directory_path = r'C:\ANSYS_Project_Folder\dp0\SYS-1\MECH'
rst_file_path = directory_path + r'\file.rst'
ansys_version = 23.1
number_of_cpu = 2
# Launch MAPDL instance
mapdl = launch_mapdl(run_location=directory_path, nproc=number_of_cpu, version=ansys_version, override=True)
try:
reactions = extract_reactions(rst_file_path)
save_to_excel(reactions, directory_path)
except Exception:
mapdl.clear()
mapdl.exit()
traceback.print_exc()