AnsysLink/test/test_mesh_like_example.py

185 lines
6.0 KiB
Python

#!/usr/bin/env python3
"""
Test mesh generation following the exact pattern from PyMechanical examples
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from backend.pymechanical.session_manager import ANSYSSessionManager
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(levelname)s:%(name)s:%(message)s'
)
def test_mesh_like_example():
"""Test mesh generation following PyMechanical example pattern exactly"""
print("Mesh Generation Following PyMechanical Example")
print("=" * 60)
session_manager = None
try:
# Initialize ANSYS session
session_manager = ANSYSSessionManager(simulation_mode=False)
session_manager.start_session()
print("✓ ANSYS session started")
# Import geometry
geometry_file = "resource\\blade.step"
print(f"1. Importing geometry from {geometry_file}...")
if session_manager.import_geometry(geometry_file):
print("✓ Geometry imported successfully")
else:
print("✗ Geometry import failed")
return
# Follow the exact pattern from PyMechanical embedding example
print("\n2. Following PyMechanical example pattern...")
# Step 1: Set mesh element size (like in example: mesh.ElementSize = Quantity("25 [mm]"))
mesh_setup_script = '''
mesh = Model.Mesh
mesh.ElementSize = Quantity("10 [mm]")
"setup_complete"
'''
setup_result = session_manager.mechanical.run_python_script(mesh_setup_script)
print(f"Setup result: '{setup_result}'")
# Step 2: Generate mesh (like in example: mesh.GenerateMesh())
mesh_generation_script = '''
mesh = Model.Mesh
mesh.GenerateMesh()
"generation_complete"
'''
gen_result = session_manager.mechanical.run_python_script(mesh_generation_script)
print(f"Generation result: '{gen_result}'")
# Step 3: Check mesh using the pattern from PyMechanical tests
# Based on pymechanical/tests/scripts/api.py: mesh_details = {"Nodes": mesh.Nodes, "Elements": mesh.Elements}
print("\n3. Checking mesh using PyMechanical test pattern...")
mesh_check_script = '''
try:
mesh = Model.Mesh
nodes = mesh.Nodes
elements = mesh.Elements
# Try to get some info about the collections
nodes_info = str(type(nodes))
elements_info = str(type(elements))
# Return info about the mesh objects
"nodes:" + nodes_info + "|elements:" + elements_info
except Exception as e:
"error:" + str(e)
'''
check_result = session_manager.mechanical.run_python_script(mesh_check_script)
print(f"Check result: '{check_result}'")
# Step 4: Try alternative ways to verify mesh
print("\n4. Trying alternative mesh verification...")
# Method from the official example - try to access mesh properties
alt_check_script = '''
try:
mesh = Model.Mesh
# Try different approaches to verify mesh
verification_info = []
# Check if mesh object exists
verification_info.append("mesh_exists:True")
# Try to access mesh properties
try:
element_size = mesh.ElementSize
verification_info.append("element_size:" + str(element_size))
except:
verification_info.append("element_size:error")
# Try to check if mesh has been generated
try:
# Some versions might have different properties
verification_info.append("mesh_type:" + str(type(mesh)))
except:
verification_info.append("mesh_type:error")
"|".join(verification_info)
except Exception as e:
"verification_error:" + str(e)
'''
alt_result = session_manager.mechanical.run_python_script(alt_check_script)
print(f"Alternative check result: '{alt_result}'")
# Step 5: Try to save the project (this would fail if mesh is invalid)
print("\n5. Testing project save (mesh validation)...")
save_test_script = '''
try:
# Try to save - this validates that the model is in a good state
project_dir = ExtAPI.DataModel.Project.ProjectDirectory
"project_dir:" + str(project_dir)
except Exception as e:
"save_error:" + str(e)
'''
save_result = session_manager.mechanical.run_python_script(save_test_script)
print(f"Save test result: '{save_result}'")
# Analysis of results
print("\n" + "=" * 60)
print("ANALYSIS OF RESULTS:")
if setup_result == "setup_complete":
print("✅ Mesh setup completed successfully")
else:
print("❌ Mesh setup failed")
if gen_result == "generation_complete":
print("✅ Mesh generation command completed successfully")
else:
print("❌ Mesh generation command failed")
if check_result and "error:" not in check_result:
print("✅ Mesh objects accessible")
print(f" Details: {check_result}")
else:
print("❌ Could not access mesh objects")
if check_result:
print(f" Error: {check_result}")
if alt_result and "verification_error:" not in alt_result:
print("✅ Mesh verification successful")
print(f" Details: {alt_result}")
else:
print("❌ Mesh verification failed")
if alt_result:
print(f" Error: {alt_result}")
if save_result and "save_error:" not in save_result:
print("✅ Project state is valid")
else:
print("❌ Project state validation failed")
print("\n✓ PyMechanical example pattern test completed")
except Exception as e:
print(f"\n✗ Test failed: {str(e)}")
import traceback
traceback.print_exc()
finally:
if session_manager:
session_manager.close_session()
if __name__ == "__main__":
test_mesh_like_example()