Is there an example workflow that uses the following packages of PyAnsys: PyAEDT, PyAnsysGeometry, PyWorkbench and PyMechanical?
Below is an example workflow that will do the following:
Here is the main script:
import os import pathlib import ansys.aedt.core from ansys.geometry.core import launch_modeler_with_core_service from ansys.geometry.core.misc.options import ImportOptions from ansys.geometry.core.designer.design import Design, DesignFileFormat from ansys.workbench.core import launch_workbench from ansys.mechanical.core import connect_to_mechanical from pint import Quantity ## Define paths workdir = pathlib.Path(__file__).parent workbench_server_workdir= workdir / "wb_server_workdir" if not workbench_server_workdir.exists(): workbench_server_workdir.mkdir(parents=True, exist_ok=True) product_version ="252" # Point to appropriate geometry service root if needed if product_version =="252": os.environ["ANSYS_GEOMETRY_SERVICE_ROOT"] = path_to_geometry_service # Define value for share topology share_topo_tolerance = Quantity(1.0e-3, 'mm') ## PyAEDT workflow # Initialize HFSS project hfss = ansys.aedt.core.Hfss(project=os.path.join(workdir,name+'.aedt'), version=product_version) # Export design as step file hfss.export_3d_model( file_path=workdir, file_name="Geometry_initial", file_format=".step" ) # Export material per object dict_objs_materials = { obj.name:obj.material_name for obj in [hfss.modeler.get_object_from_name(oobj) for oobj in hfss.modeler.get_matched_object_name('*')] } ansys.aedt.core.generic.file_utils._create_json_file( dict_objs_materials, os.path.join(workdir,"Material_assignment.json") ) aedt_file_name = os.path.join(str(workdir.absolute()), "Aedt_model.aedt") hfss.save_project(file_name=aedt_file_name) hfss.release_desktop(True,True) ## Geometry workflow modeler = launch_modeler_with_core_service(server_log_level=0, version=product_version) print(f'Successfully launched modeler with core service in version {product_version}') import_opt = ImportOptions() import_opt.cleanup_bodies = False upload_file = True if os.environ.get("ON_WORKFLOW", False) else False cad_filename = os.path.join(workdir,'Geometry_initial.step') design = modeler.open_file(cad_filename, upload_file) bodylist = design.get_all_bodies() modeler.prepare_tools.share_topology(bodylist,tol=share_topo_tolerance) geometry_export_filename = pathlib.Path(workdir, "Geometry_modified.pmdb") design.download(geometry_export_filename, DesignFileFormat.PMDB) print('Shared topology and exported file to .pmdb format') ## Workbench workflow export_path = 'wb_log_file.log' print(f"Launching Workbench in version {product_version}...") wb = launch_workbench( show_gui=True, version=product_version, client_workdir=str(workdir.absolute()), server_workdir=str(workbench_server_workdir.absolute()) ) wb.set_log_file(export_path) wb.upload_file(str((geometry_export_filename).absolute())) # Upload Aedt_model file wb.upload_file(aedt_file_name) print("Performing WB script...") script_file_name = str((workdir / "WB_Script.wbjn").absolute()) system_name = wb.run_script_file(script_file_name, log_level='info') ## Mechanical workflow print("Start a PyMechanical service") pymech_port = wb.start_mechanical_server(system_name=system_name) mechanical = connect_to_mechanical(ip='localhost', port=pymech_port) mech_directory = mechanical.project_directory print("Mechanical projet directory is: " + str(mech_directory)) print("Upload JSON material assignment file...") material_file = os.path.join(workdir,"Material_assignment.json") mechanical.upload(file_name=material_file, file_location_destination=mech_directory) base_name = os.path.basename(material_file) combined_path = os.path.join(mech_directory, base_name) mat_file_path = combined_path.replace("\\", "\\\\") mechanical.run_python_script(f"mat_file_path='{mat_file_path}'") result = mechanical.run_python_script("mat_file_path") print(f"mat_file_path on server: {result}") output = mechanical.run_python_script_from_file("mech_script.py") # Go back to WB to save project print("Save workbench project...") wb.run_script_string("Save(FilePath=project_name, Overwrite=True)", log_level='info') print("Creating and downloading archive...") archive_name = "Demo" wb.download_project_archive(archive_name, include_solution_result_files=True, show_progress=True) #wb.exit() print("Saved archive and exited Workbench.")
# Define value for share topology
# Go back to WB to save project
The Workbench journal script:
Here is the script:
import os import json # Define paths work_dir = GetServerWorkingDirectory() geometry_file_path = os.path.join(work_dir, "Geometry_modified.pmdb") aedt_file_path = os.path.join(work_dir, "Aedt_model.aedt") project_name = os.path.join(work_dir, "Demo.wbpj") # Import .aedt file fileType1 = GetFileType(Name="Ansys Electronics Desktop Project") ImportFile( FilePath=GetAbsoluteUserPathName(aedt_file_path), FileType=fileType1) Refresh() # Insert Static Structural and link Geometry and Engineering Data template1 = GetTemplate( TemplateName="Static Structural", Solver="ANSYS") system1 = GetAllSystems()[0] hFSSGeometryComponent1 = system1.GetComponent(Name="HFSSGeometry") componentTemplate1 = GetComponentTemplate(Name="EngDataCellTemplate") system2 = template1.CreateSystem( DataTransferFrom=[Set(FromComponent=hFSSGeometryComponent1, TransferName=None, ToComponentTemplate=componentTemplate1)], Position="Right", RelativeTo=system1) geometryComponent1 = system2.GetComponent(Name="Geometry") hFSSGeometryComponent1.TransferData(TargetComponent=geometryComponent1) engineeringDataComponent1 = system2.GetComponent(Name="Engineering Data") engineeringDataComponent1.Refresh() geometry1 = system2.GetContainer(ComponentName="Geometry") geometryProperties1 = geometry1.GetGeometryProperties() geometryProperties1.GeometryImportMaterialProperties = True geometryComponent1.Refresh() modelComponent1 = system2.GetComponent(Name="Model") modelComponent1.Refresh() #modelComponent1.Update(AllDependencies=True) # Delete sharing of Geometry hFSSGeometryComponent1.DeleteTransfer(TargetComponent=geometryComponent1) # Replace geometry by the geometry that is modified geometry1 = system2.GetContainer(ComponentName="Geometry") geometry1.SetFile(FilePath=GetAbsoluteUserPathName(geometry_file_path)) geometryProperties1.GeometryImportMaterialProperties = True geometryComponent1.Refresh() geometryComponent1.Update(AllDependencies=True) modelComponent1 = system2.GetComponent(Name="Model") modelComponent1.Refresh() # Save name of Static Structural analysis wb_script_result = json.dumps(system2.Name)
The Mechanical script:
import json import os # Load body-material mapping from JSON file math_file_path = path_to_json_file with open(mat_file_path, 'r') as f: body_material_map = json.load(f) bodies = Model.GetChildren(DataModelObjectCategory.Body, True) # Get all available materials and create a case-insensitive lookup available_materials = {mat.Name.lower(): mat.Name for mat in Model.Materials.GetChildren(DataModelObjectCategory.Material,True)} for body in bodies: if body.Name in body_material_map: material_name = body_material_map[body.Name] # Find material in case-insensitive manner material_key = material_name.lower() if material_key in available_materials: body.Material = available_materials[material_key] else: pass for body in bodies: if body.ObjectState == ObjectState.UnderDefined: ExtAPI.Application.Messages.AddError("Error: Body '{0}' has undefined state".format(body.Name))
The code structure should be as follows:
Place all scripts in the same folder and run the workflow from the main file, in a virtual environment where the needed PyAnsys packages have been installed.