AnsysLink/test/test_verify_mesh.py

199 lines
6.7 KiB
Python

#!/usr/bin/env python3
"""
Verify mesh generation results by actually checking the mesh
"""
import sys
import os
sys.path.append(os.path.dirname(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_verify_mesh():
"""Verify mesh generation by checking actual mesh data"""
print("Mesh Verification Test")
print("=" * 50)
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
# Apply basic mesh settings only (no complex controls)
print("\n2. Applying basic mesh settings...")
basic_mesh_setup = '''
# Basic mesh setup - minimal settings for successful generation
mesh = Model.Mesh
mesh.ElementSize = Quantity("5.0 [mm]") # Larger element size for reliability
print("Basic mesh setup completed")
'''
setup_result = session_manager.mechanical.run_python_script(basic_mesh_setup)
print(f"Setup result: '{setup_result}'")
# Generate mesh with verification
print("\n3. Generating mesh with verification...")
mesh_generation_and_verify = '''
# Generate mesh and verify results
try:
mesh = Model.Mesh
# Clear any existing mesh
try:
mesh.ClearGeneratedData()
print("Cleared existing mesh data")
except:
print("No existing mesh to clear")
# Generate mesh
print("Starting mesh generation...")
mesh.GenerateMesh()
print("Mesh generation call completed")
# Verify mesh exists by checking different properties
verification_results = {
"mesh_exists": False,
"has_elements": False,
"has_nodes": False,
"element_count": 0,
"node_count": 0
}
# Method 1: Check if mesh object has data
try:
# Check if mesh has been generated
mesh_info = mesh.Info
if mesh_info:
verification_results["mesh_exists"] = True
print("Mesh object has info - mesh exists")
except:
print("Could not get mesh info")
# Method 2: Try to access mesh elements and nodes
try:
elements = mesh.Elements
if elements:
verification_results["has_elements"] = True
print("Mesh has elements collection")
# Try to get element count
try:
element_count = len(elements)
verification_results["element_count"] = element_count
print("Element count: " + str(element_count))
except:
print("Could not get element count with len()")
try:
# Alternative method
element_count = elements.Count
verification_results["element_count"] = element_count
print("Element count (Count property): " + str(element_count))
except:
print("Could not get element count with Count property")
except Exception as e:
print("Could not access elements: " + str(e))
try:
nodes = mesh.Nodes
if nodes:
verification_results["has_nodes"] = True
print("Mesh has nodes collection")
# Try to get node count
try:
node_count = len(nodes)
verification_results["node_count"] = node_count
print("Node count: " + str(node_count))
except:
print("Could not get node count with len()")
try:
# Alternative method
node_count = nodes.Count
verification_results["node_count"] = node_count
print("Node count (Count property): " + str(node_count))
except:
print("Could not get node count with Count property")
except Exception as e:
print("Could not access nodes: " + str(e))
# Method 3: Check mesh statistics
try:
# Try to get mesh statistics
print("Checking mesh statistics...")
# Some versions might have different properties
if hasattr(mesh, 'Statistics'):
stats = mesh.Statistics
print("Mesh statistics available: " + str(stats))
except Exception as e:
print("Could not get mesh statistics: " + str(e))
# Final verification
mesh_generated = (verification_results["has_elements"] and
verification_results["element_count"] > 0) or verification_results["mesh_exists"]
if mesh_generated:
print("SUCCESS: Mesh generation verified!")
print("Elements: " + str(verification_results["element_count"]))
print("Nodes: " + str(verification_results["node_count"]))
else:
print("FAILED: No mesh found after generation")
except Exception as e:
print("ERROR: Mesh generation failed: " + str(e))
import traceback
traceback.print_exc()
'''
verification_result = session_manager.mechanical.run_python_script(mesh_generation_and_verify)
print(f"\nVerification result:\n{verification_result}")
# Additional check: Try to save the project to see if mesh data exists
print("\n4. Additional verification - saving project...")
save_check = '''
# Try to save project - this will fail if mesh is corrupted
try:
project_dir = ExtAPI.DataModel.Project.ProjectDirectory
save_path = project_dir + "/verification_test.mechdb"
ExtAPI.DataModel.Project.SaveAs(save_path)
print("Project saved successfully - mesh data is valid")
except Exception as e:
print("Could not save project: " + str(e))
'''
save_result = session_manager.mechanical.run_python_script(save_check)
print(f"Save result: '{save_result}'")
print("\n✓ Mesh verification test completed")
except Exception as e:
print(f"\n✗ Mesh verification test failed: {str(e)}")
import traceback
traceback.print_exc()
finally:
if session_manager:
session_manager.close_session()
if __name__ == "__main__":
test_verify_mesh()