test_robust_solver.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. """Test script for RobustMotorCADSolver - Step 1: Connection and variable probing.
  2. This script tests:
  3. 1. Motor-CAD connection (open_new_instance=True + set_visible=True)
  4. 2. Model loading
  5. 3. Variable probing (get common variable names)
  6. 4. Parameter write-back verification
  7. 5. Single magnetic calculation
  8. 6. Result export and parsing
  9. All source is ASCII only.
  10. """
  11. import os
  12. import sys
  13. import time
  14. import json
  15. # Add project root to path
  16. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  17. from scripts.robust_motorcad import (
  18. RobustMotorCADSolver,
  19. ensure_environment,
  20. is_running_as_admin,
  21. check_license_server,
  22. )
  23. def main():
  24. print("=" * 60)
  25. print("RobustMotorCADSolver Test - Step 1: Connection & Probing")
  26. print("=" * 60)
  27. # Pre-checks
  28. print("\n[Pre-checks]")
  29. print(f" Running as admin: {is_running_as_admin()}")
  30. license_ok, license_msg = check_license_server()
  31. print(f" License server: {license_msg}")
  32. ensure_environment()
  33. print(f" MOTORCAD_ACTIVEX: {os.environ.get('MOTORCAD_ACTIVEX', 'not set')}")
  34. print(f" ANSYSLMD_LICENSE_FILE: {os.environ.get('ANSYSLMD_LICENSE_FILE', 'not set')}")
  35. # Model path
  36. model_path = os.path.join(
  37. os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  38. "models", "MARS-12S10P_SSSR_D76-C150_V5.0-0819.mot"
  39. )
  40. print(f"\n Model path: {model_path}")
  41. print(f" Model exists: {os.path.exists(model_path)}")
  42. if not os.path.exists(model_path):
  43. print("ERROR: Model file not found!")
  44. return 1
  45. # Create solver
  46. print("\n[Creating solver]")
  47. solver = RobustMotorCADSolver(
  48. model_path=model_path,
  49. output_dir=os.path.join(
  50. os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  51. "output", f"test_connect_{time.strftime('%Y%m%d_%H%M%S')}"
  52. ),
  53. point_timeout=120,
  54. max_retries=2,
  55. headless=False,
  56. )
  57. print(f" Output dir: {solver.output_dir}")
  58. # Connect
  59. print("\n[Step 1: Connecting to Motor-CAD]")
  60. try:
  61. solver.connect()
  62. print(" Connection SUCCESS")
  63. # Suppress popups immediately to prevent GUI dialogs from blocking batch
  64. solver._suppress_popups()
  65. print(" Popup suppression enabled (MessageDisplayState=2)")
  66. except Exception as e:
  67. print(f" Connection FAILED: {e}")
  68. return 1
  69. # Run preflight
  70. print("\n[Step 2: Running preflight self-check]")
  71. try:
  72. preflight = solver.run_preflight()
  73. print(preflight.summary())
  74. except Exception as e:
  75. print(f" Preflight error: {e}")
  76. # Probe variables
  77. print("\n[Step 3: Probing common variables]")
  78. common_vars = [
  79. "Motor_Type",
  80. "Stator_Number_Of_Slots",
  81. "Rotor_Number_Of_Poles",
  82. "Airgap",
  83. "Magnet_Arc_[ED]",
  84. "MagnetCentralArc_HalbachRing",
  85. "Slot_Opening",
  86. "Slot_Width",
  87. "Copper_Width",
  88. "TorquePointsPerCycle",
  89. "AirgapMeshPoints_mesh",
  90. "AirgapMeshPoints_layers",
  91. "Shaft_Speed",
  92. "Peak_Phase_Current",
  93. ]
  94. probed = {}
  95. for var in common_vars:
  96. try:
  97. value = solver.mc.get_variable(var)
  98. probed[var] = value
  99. print(f" {var} = {value}")
  100. except Exception as e:
  101. print(f" {var} = ERROR: {e}")
  102. # Save probed variables
  103. probe_file = os.path.join(solver.output_dir, "probed_variables.json")
  104. with open(probe_file, "w", encoding="utf-8") as f:
  105. json.dump(probed, f, indent=2, default=str)
  106. print(f"\n Probed variables saved to: {probe_file}")
  107. # Test parameter write-back verification
  108. print("\n[Step 4: Testing parameter write-back verification]")
  109. test_var = "TorquePointsPerCycle"
  110. if test_var in probed:
  111. original_value = float(probed[test_var])
  112. test_value = 60 # Test with 60 points
  113. print(f" Original {test_var} = {original_value}")
  114. print(f" Testing write {test_var} = {test_value}")
  115. try:
  116. applied = solver._write_and_verify(test_var, test_value)
  117. print(f" Write-back verification SUCCESS: applied={applied}")
  118. # Restore original
  119. solver._write_and_verify(test_var, original_value)
  120. print(f" Restored {test_var} = {original_value}")
  121. except Exception as e:
  122. print(f" Write-back verification FAILED: {e}")
  123. else:
  124. print(f" {test_var} not available, skipping write test")
  125. # Test single magnetic calculation
  126. print("\n[Step 5: Testing single magnetic calculation]")
  127. try:
  128. start = time.time()
  129. solver.mc.do_magnetic_calculation()
  130. elapsed = time.time() - start
  131. print(f" Magnetic calculation SUCCESS in {elapsed:.1f}s")
  132. except Exception as e:
  133. print(f" Magnetic calculation FAILED: {e}")
  134. # Test result export
  135. print("\n[Step 6: Testing result export]")
  136. try:
  137. export_file = os.path.join(solver.raw_dir, "test_export.csv")
  138. solver.mc.export_results("EMagnetic", export_file)
  139. if os.path.exists(export_file):
  140. file_size = os.path.getsize(export_file)
  141. print(f" Export SUCCESS: {export_file} ({file_size} bytes)")
  142. # Parse and show metrics
  143. metrics = solver._parse_export(export_file)
  144. print(f" Parsed {len(metrics)} metrics:")
  145. for k, v in metrics.items():
  146. print(f" {k} = {v}")
  147. else:
  148. print(" Export file not created!")
  149. except Exception as e:
  150. print(f" Export FAILED: {e}")
  151. # Disconnect
  152. print("\n[Step 7: Disconnecting]")
  153. solver.disconnect()
  154. print(" Disconnected")
  155. # Summary
  156. print("\n" + "=" * 60)
  157. print("Test Summary")
  158. print("=" * 60)
  159. print(f" Output directory: {solver.output_dir}")
  160. print(f" Probed variables: {len(probed)}")
  161. print(f" Log file: {solver._log_path}")
  162. print("\n Test completed successfully!")
  163. return 0
  164. if __name__ == "__main__":
  165. sys.exit(main())